_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
42f98c690c45d4fae7f508a2e98d2fd34ea90a316863b2c5db0012e59fcb5793
lexi-lambda/racket-collections
info.rkt
#lang info (define collection 'multi) (define version "1.3.1") (define deps '(["base" #:version "6.3"] "curly-fn-lib" ["functional-lib" #:version "0.3.1"] "match-plus" "static-rename" "unstable-list-lib")) (define build-deps '())
null
https://raw.githubusercontent.com/lexi-lambda/racket-collections/c4822fc200b0488922cd6e86b4f2ea7cf8c565da/collections-lib/info.rkt
racket
#lang info (define collection 'multi) (define version "1.3.1") (define deps '(["base" #:version "6.3"] "curly-fn-lib" ["functional-lib" #:version "0.3.1"] "match-plus" "static-rename" "unstable-list-lib")) (define build-deps '())
81c38f324cf223415dd7d1c125b5ae97fa31dc819a0b3c11206b6a86226cb49e
bburdette/chordster
AddNoteSet.hs
module Handler.AddNoteSet where import Import import Handler.NoteSet getAddNoteSetR :: Handler Html getAddNoteSetR = do (ndf,etype) <- generateFormPost $ ndForm Nothing defaultLayout $ [whamlet| <h1> Chord type <form method=post enctype=#{etype}> ^{ndf} <input type=submit value="OK"> |] postAddNoteSetR :: Handler Html postAddNoteSetR = do ((res,widg),enctype) <- runFormPost $ ndForm Nothing case res of FormSuccess nsdata -> do nsid <- runDB $ insert $ NoteSet (name nsdata) let indices = (notes nsdata) _ <- mapM (\i -> do runDB $ insert $ Note i (denom nsdata) nsid) indices redirect NoteSetsR _ -> error "error!"
null
https://raw.githubusercontent.com/bburdette/chordster/70d235f1ca379e5ecd4a8f39dc1e734e2d50978b/Handler/AddNoteSet.hs
haskell
module Handler.AddNoteSet where import Import import Handler.NoteSet getAddNoteSetR :: Handler Html getAddNoteSetR = do (ndf,etype) <- generateFormPost $ ndForm Nothing defaultLayout $ [whamlet| <h1> Chord type <form method=post enctype=#{etype}> ^{ndf} <input type=submit value="OK"> |] postAddNoteSetR :: Handler Html postAddNoteSetR = do ((res,widg),enctype) <- runFormPost $ ndForm Nothing case res of FormSuccess nsdata -> do nsid <- runDB $ insert $ NoteSet (name nsdata) let indices = (notes nsdata) _ <- mapM (\i -> do runDB $ insert $ Note i (denom nsdata) nsid) indices redirect NoteSetsR _ -> error "error!"
55810bcf487899f1798ae9afd93c63872983408473eec4a9036e4ef8b74005da
clj-commons/rewrite-clj
parser.cljc
(ns rewrite-clj.parser "Parse Clojure/ClojureScript/EDN source code to nodes. Parsing includes all source code elements including whitespace. After parsing, the typical next step is [[rewrite-clj.zip/edn]] to create zipper. Alternatively consider parsing and zipping in one step from [[rewrite-clj.zip/of-string]] or [[rewrite-clj.zip/of-file]]." (:require [rewrite-clj.node.forms :as nforms] [rewrite-clj.parser.core :as p] [rewrite-clj.reader :as reader])) #?(:clj (set! *warn-on-reflection* true)) # # Parser Core (defn ^:no-doc parse "Parse next form from the given reader." [#?(:cljs ^not-native reader :default reader)] (p/parse-next reader)) (defn ^:no-doc parse-all "Parse all forms from the given reader." [#?(:cljs ^not-native reader :default reader)] (let [nodes (->> (repeatedly #(parse reader)) (take-while identity)) position-meta (merge (meta (first nodes)) (select-keys (meta (last nodes)) [:end-row :end-col]))] (with-meta (nforms/forms-node nodes) position-meta))) # # Specialized Parsers (defn parse-string "Return a node for first source code element in string `s`." [s] (parse (reader/string-reader s))) (defn parse-string-all "Return forms node for all source code elements in string `s`." [s] (parse-all (reader/string-reader s))) #?(:clj (defn parse-file "Return node for first source code element in file `f`." [f] (with-open [r (reader/file-reader f)] (parse r)))) #?(:clj (defn parse-file-all "Return forms node for all source code elements in file `f`." [f] (with-open [r (reader/file-reader f)] (parse-all r))))
null
https://raw.githubusercontent.com/clj-commons/rewrite-clj/6fe5b4bfbf4b3eb00c299c1ca781b007686699e2/src/rewrite_clj/parser.cljc
clojure
(ns rewrite-clj.parser "Parse Clojure/ClojureScript/EDN source code to nodes. Parsing includes all source code elements including whitespace. After parsing, the typical next step is [[rewrite-clj.zip/edn]] to create zipper. Alternatively consider parsing and zipping in one step from [[rewrite-clj.zip/of-string]] or [[rewrite-clj.zip/of-file]]." (:require [rewrite-clj.node.forms :as nforms] [rewrite-clj.parser.core :as p] [rewrite-clj.reader :as reader])) #?(:clj (set! *warn-on-reflection* true)) # # Parser Core (defn ^:no-doc parse "Parse next form from the given reader." [#?(:cljs ^not-native reader :default reader)] (p/parse-next reader)) (defn ^:no-doc parse-all "Parse all forms from the given reader." [#?(:cljs ^not-native reader :default reader)] (let [nodes (->> (repeatedly #(parse reader)) (take-while identity)) position-meta (merge (meta (first nodes)) (select-keys (meta (last nodes)) [:end-row :end-col]))] (with-meta (nforms/forms-node nodes) position-meta))) # # Specialized Parsers (defn parse-string "Return a node for first source code element in string `s`." [s] (parse (reader/string-reader s))) (defn parse-string-all "Return forms node for all source code elements in string `s`." [s] (parse-all (reader/string-reader s))) #?(:clj (defn parse-file "Return node for first source code element in file `f`." [f] (with-open [r (reader/file-reader f)] (parse r)))) #?(:clj (defn parse-file-all "Return forms node for all source code elements in file `f`." [f] (with-open [r (reader/file-reader f)] (parse-all r))))
5c18528ea4b4451ff25143223d858e35fcb0de2e94d08c14ba2418c920f2b802
sile/logi
logi_builtin_sink_fun.erl
2014 - 2016 < > %% %% @doc A built-in sink which consumes log messages by an arbitrary user defined function %% %% The default layout is `logi_builtin_layout_default:new()'. %% %% == NOTE == %% This module is provided for debuging/testing purposes only. %% %% A sink is stored into a logi_channel's ETS. %% Then it will be loaded every time a log message is issued. %% Therefore if the write function (`write_fun/0') of the sink is a huge size anonymous function, %% all log issuers which use the channel will have to pay a non negligible cost to load it. %% %% And there is no overload protection. %% %% == EXAMPLE == %% <pre lang="erlang"> %% > error_logger:tty(false). % Suppresses annoying warning outputs for brevity %% > WriteFun = fun ( _ , Format , Data ) - > io : format("[CONSUMED ] " + + Format + + " \n " , Data ) end . > { ok , _ } = logi_channel : install_sink(logi_builtin_sink_fun : , WriteFun ) , info ) . %% > logi:info("hello world"). %% [CONSUMED] hello world %% </pre> %% @end -module(logi_builtin_sink_fun). -behaviour(logi_sink_writer). %%---------------------------------------------------------------------------------------------------------------------- %% Exported API %%---------------------------------------------------------------------------------------------------------------------- -export([new/2]). -export_type([write_fun/0]). %%---------------------------------------------------------------------------------------------------------------------- %% 'logi_sink_writer' Callback API %%---------------------------------------------------------------------------------------------------------------------- -export([write/4, get_writee/1]). %%---------------------------------------------------------------------------------------------------------------------- %% Types %%---------------------------------------------------------------------------------------------------------------------- -type write_fun() :: fun ((logi_context:context(), io:format(), logi_layout:data()) -> logi_sink_writer:written_data()). %% A function which is used to consume log messages issued by `logi' %%---------------------------------------------------------------------------------------------------------------------- %% Exported Functions %%---------------------------------------------------------------------------------------------------------------------- @doc a new sink instance -spec new(logi_sink:id(), write_fun()) -> logi_sink:sink(). new(Id, Fun) -> _ = erlang:is_function(Fun, 3) orelse error(badarg, [Fun]), logi_sink:from_writer(Id, logi_sink_writer:new(?MODULE, Fun)). %%---------------------------------------------------------------------------------------------------------------------- %% 'logi_sink_writer' Callback Functions %%---------------------------------------------------------------------------------------------------------------------- @private write(Context, Format, Data, Fun) -> Fun(Context, Format, Data). @private get_writee(_) -> undefined.
null
https://raw.githubusercontent.com/sile/logi/1022fbc238a7d18765fe864a7174958142160ee8/src/logi_builtin_sink_fun.erl
erlang
@doc A built-in sink which consumes log messages by an arbitrary user defined function The default layout is `logi_builtin_layout_default:new()'. == NOTE == This module is provided for debuging/testing purposes only. A sink is stored into a logi_channel's ETS. Then it will be loaded every time a log message is issued. Therefore if the write function (`write_fun/0') of the sink is a huge size anonymous function, all log issuers which use the channel will have to pay a non negligible cost to load it. And there is no overload protection. == EXAMPLE == <pre lang="erlang"> > error_logger:tty(false). % Suppresses annoying warning outputs for brevity > logi:info("hello world"). [CONSUMED] hello world </pre> @end ---------------------------------------------------------------------------------------------------------------------- Exported API ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- 'logi_sink_writer' Callback API ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- Types ---------------------------------------------------------------------------------------------------------------------- A function which is used to consume log messages issued by `logi' ---------------------------------------------------------------------------------------------------------------------- Exported Functions ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- 'logi_sink_writer' Callback Functions ----------------------------------------------------------------------------------------------------------------------
2014 - 2016 < > > WriteFun = fun ( _ , Format , Data ) - > io : format("[CONSUMED ] " + + Format + + " \n " , Data ) end . > { ok , _ } = logi_channel : install_sink(logi_builtin_sink_fun : , WriteFun ) , info ) . -module(logi_builtin_sink_fun). -behaviour(logi_sink_writer). -export([new/2]). -export_type([write_fun/0]). -export([write/4, get_writee/1]). -type write_fun() :: fun ((logi_context:context(), io:format(), logi_layout:data()) -> logi_sink_writer:written_data()). @doc a new sink instance -spec new(logi_sink:id(), write_fun()) -> logi_sink:sink(). new(Id, Fun) -> _ = erlang:is_function(Fun, 3) orelse error(badarg, [Fun]), logi_sink:from_writer(Id, logi_sink_writer:new(?MODULE, Fun)). @private write(Context, Format, Data, Fun) -> Fun(Context, Format, Data). @private get_writee(_) -> undefined.
fe20df84ef95cb1fedd4c1281bae2f080a1f0e3a817a1634806fcd7721b0ecca
exoscale/pithos
sig.clj
(ns io.pithos.sig "Compute request signatures as described in " (:require [clojure.string :as s] [clojure.tools.logging :refer [info debug]] [clojure.data.codec.base64 :as base64] [clj-time.core :refer [after? now]] [clj-time.coerce :refer [to-date-time]] [constance.comp :refer [===]] [io.pithos.util :refer [date->rfc822]]) (:import javax.crypto.Mac javax.crypto.spec.SecretKeySpec)) (defn canonicalized "Group headers starting with x-amz, each on a separate line and add uri" [headers uri] (s/join "\n" (concat (->> headers (map (juxt (comp name key) (comp s/trim val))) (filter (comp #(.startsWith % "x-amz") first)) (sort-by first) (map (partial s/join ":"))) [uri]))) (defn string-to-sign "Yield the string to sign for an incoming request" [{:keys [headers request-method sign-uri params] :as request}] (let [content-md5 (get headers "content-md5") content-type (get headers "content-type") date (or (get params :expires) (if-not (get headers "x-amz-date") (get headers "date")))] (s/join "\n" [(-> request-method name s/upper-case) (or content-md5 "") (or content-type "") (or date "") (canonicalized headers sign-uri)]))) (defn sign-string [src secret-key] (let [key (SecretKeySpec. (.getBytes secret-key) "HmacSHA1")] (String. (-> (doto (Mac/getInstance "HmacSHA1") (.init key)) (.doFinal (.getBytes src)) (base64/encode))))) (defn sign-request "Sign the request, signatures are basic HmacSHA1s, encoded in base64" [request secret-key] (sign-string (string-to-sign request) secret-key)) (defn auth "Extract access key and signature from the request, using query string parameters or Authorization header" [request] (if-let [auth-str (get-in request [:headers "authorization"])] (let [[_ access-key sig] (re-matches #"^[Aa][Ww][Ss] (.*):(.*)$" auth-str)] {:sig sig :access-key access-key}) (let [access-key (get-in request [:params :awsaccesskeyid]) sig (get-in request [:params :signature])] (if (and access-key sig) {:sig sig :access-key access-key} nil)))) (defn check-sig [request keystore key str sig] (let [{:keys [secret] :as authorization} (get keystore key) signed (try (sign-string str secret) (catch Exception e {:failed true :exception e}))] (when-not (and (not (nil? sig)) (string? signed) (=== sig signed)) (info "will throw because of failed signature!") (when (:exception signed) (debug (:exception signed) "got exception during signing")) (throw (ex-info "invalid policy signature" {:type :signature-does-not-match :status-code 403 :request request :expected signed :to-sign str}))) (update-in authorization [:memberof] concat ["authenticated-users"]))) (def anonymous {:tenant :anonymous :memberof ["anonymous"]}) (defn validate "Validate an incoming request (e.g: make sure the signature is correct), when applicable (requests may be unauthenticated)" [keystore request] (if-let [data (auth request)] (let [{:keys [sig access-key]} data {:keys [secret] :as authorization} (get keystore access-key) signed (try (sign-request request secret) (catch Exception e {:failed true :exception e}))] (when-not (and (not (nil? sig)) (string? signed) (=== sig signed)) (info "will throw because of failed signature!") (when (:exception signed) (debug (:exception signed) "got exception during signing")) (debug "string-to-sign: " (string-to-sign request)) (throw (ex-info "invalid request signature" {:type :signature-does-not-match :status-code 403 :request request :expected signed :to-sign (string-to-sign request)}))) (when-let [expires (get-in request [:params :expires])] (let [expires (to-date-time (* 1000 (Integer/parseInt expires)))] (when (after? (now) expires) (throw (ex-info "expired request" {:type :expired-request :status-code 403 :request request :expires (date->rfc822 expires)}))))) (update-in authorization [:memberof] concat ["authenticated-users" "anonymous"])) anonymous))
null
https://raw.githubusercontent.com/exoscale/pithos/54790f00fbfd330c6196d42e5408385028d5e029/src/io/pithos/sig.clj
clojure
(ns io.pithos.sig "Compute request signatures as described in " (:require [clojure.string :as s] [clojure.tools.logging :refer [info debug]] [clojure.data.codec.base64 :as base64] [clj-time.core :refer [after? now]] [clj-time.coerce :refer [to-date-time]] [constance.comp :refer [===]] [io.pithos.util :refer [date->rfc822]]) (:import javax.crypto.Mac javax.crypto.spec.SecretKeySpec)) (defn canonicalized "Group headers starting with x-amz, each on a separate line and add uri" [headers uri] (s/join "\n" (concat (->> headers (map (juxt (comp name key) (comp s/trim val))) (filter (comp #(.startsWith % "x-amz") first)) (sort-by first) (map (partial s/join ":"))) [uri]))) (defn string-to-sign "Yield the string to sign for an incoming request" [{:keys [headers request-method sign-uri params] :as request}] (let [content-md5 (get headers "content-md5") content-type (get headers "content-type") date (or (get params :expires) (if-not (get headers "x-amz-date") (get headers "date")))] (s/join "\n" [(-> request-method name s/upper-case) (or content-md5 "") (or content-type "") (or date "") (canonicalized headers sign-uri)]))) (defn sign-string [src secret-key] (let [key (SecretKeySpec. (.getBytes secret-key) "HmacSHA1")] (String. (-> (doto (Mac/getInstance "HmacSHA1") (.init key)) (.doFinal (.getBytes src)) (base64/encode))))) (defn sign-request "Sign the request, signatures are basic HmacSHA1s, encoded in base64" [request secret-key] (sign-string (string-to-sign request) secret-key)) (defn auth "Extract access key and signature from the request, using query string parameters or Authorization header" [request] (if-let [auth-str (get-in request [:headers "authorization"])] (let [[_ access-key sig] (re-matches #"^[Aa][Ww][Ss] (.*):(.*)$" auth-str)] {:sig sig :access-key access-key}) (let [access-key (get-in request [:params :awsaccesskeyid]) sig (get-in request [:params :signature])] (if (and access-key sig) {:sig sig :access-key access-key} nil)))) (defn check-sig [request keystore key str sig] (let [{:keys [secret] :as authorization} (get keystore key) signed (try (sign-string str secret) (catch Exception e {:failed true :exception e}))] (when-not (and (not (nil? sig)) (string? signed) (=== sig signed)) (info "will throw because of failed signature!") (when (:exception signed) (debug (:exception signed) "got exception during signing")) (throw (ex-info "invalid policy signature" {:type :signature-does-not-match :status-code 403 :request request :expected signed :to-sign str}))) (update-in authorization [:memberof] concat ["authenticated-users"]))) (def anonymous {:tenant :anonymous :memberof ["anonymous"]}) (defn validate "Validate an incoming request (e.g: make sure the signature is correct), when applicable (requests may be unauthenticated)" [keystore request] (if-let [data (auth request)] (let [{:keys [sig access-key]} data {:keys [secret] :as authorization} (get keystore access-key) signed (try (sign-request request secret) (catch Exception e {:failed true :exception e}))] (when-not (and (not (nil? sig)) (string? signed) (=== sig signed)) (info "will throw because of failed signature!") (when (:exception signed) (debug (:exception signed) "got exception during signing")) (debug "string-to-sign: " (string-to-sign request)) (throw (ex-info "invalid request signature" {:type :signature-does-not-match :status-code 403 :request request :expected signed :to-sign (string-to-sign request)}))) (when-let [expires (get-in request [:params :expires])] (let [expires (to-date-time (* 1000 (Integer/parseInt expires)))] (when (after? (now) expires) (throw (ex-info "expired request" {:type :expired-request :status-code 403 :request request :expires (date->rfc822 expires)}))))) (update-in authorization [:memberof] concat ["authenticated-users" "anonymous"])) anonymous))
e1f13b43da7587b14e3488576034d05dbfa70ea7d3abdc9e3bca05c1a103a60f
eslick/cl-registry
choose-patient.lisp
;; -*- Mode:Lisp; tab-width:2; indent-tabs-mode:nil -*- (in-package :registry) (registry-proclamations) (defwidget choose-patient () ((hr-p :accessor choose-patient-hr-p :initarg :hr-p :initform t) (mark-siblings-dirty-p :accessor mark-siblings-dirty-p :initarg :mark-siblings-dirty-p :initform nil))) (defmethod render-widget-body ((widget choose-patient) &rest args) (declare (ignore args)) (let* ((user (current-user)) (center (current-center)) (patients (and center (get-patients-for-center center))) (user-patient (and user (get-patient-for-user user))) invalidate) (when user-patient (pushnew user-patient patients :test #'eq)) (with-html (cond ((null patients) (setf (current-patient) nil invalidate t) (htm (str #!"You do not have access to any patients"))) ((null (cdr patients)) (let ((patient (car patients))) (unless (eq patient (current-patient)) (setf (current-patient) patient invalidate t)) (htm "<b>Patient:</b> " (str (id patient))))) (t (let ((patient (current-patient)) (action (lambda (&key patient &allow-other-keys) (cond ((get-patient patient center t) (setf (current-patient) patient) (if (mark-siblings-dirty-p widget) (mark-dirty (car (last (widget-parents widget)))))) (t ;; Somebody deleted or renamed the patient (mark-dirty widget)))))) (setf patients (sort patients #'string-lessp :key #'id)) (unless (member patient patients :test #'eq) (setf patient (car patients) (current-patient) patient invalidate t)) (with-html-form (:get action :use-ajax-p t :class "autodropdown") "<b>Patient:</b> " (render-dropdown "patient" (mapcar 'id patients) :selected-value (id patient) :autosubmitp t))))) (when (choose-patient-hr-p widget) (htm (:hr)))) (when (and invalidate (mark-siblings-dirty-p widget)) (mark-dirty (car (last (widget-parents widget))))))) (defun make-choose-patient-widget (&key (hr-p t) (mark-siblings-dirty-p nil)) (make-instance 'choose-patient :hr-p hr-p :mark-siblings-dirty-p mark-siblings-dirty-p))
null
https://raw.githubusercontent.com/eslick/cl-registry/d4015c400dc6abf0eeaf908ed9056aac956eee82/src/plugins/clinician-home/choose-patient.lisp
lisp
-*- Mode:Lisp; tab-width:2; indent-tabs-mode:nil -*- Somebody deleted or renamed the patient
(in-package :registry) (registry-proclamations) (defwidget choose-patient () ((hr-p :accessor choose-patient-hr-p :initarg :hr-p :initform t) (mark-siblings-dirty-p :accessor mark-siblings-dirty-p :initarg :mark-siblings-dirty-p :initform nil))) (defmethod render-widget-body ((widget choose-patient) &rest args) (declare (ignore args)) (let* ((user (current-user)) (center (current-center)) (patients (and center (get-patients-for-center center))) (user-patient (and user (get-patient-for-user user))) invalidate) (when user-patient (pushnew user-patient patients :test #'eq)) (with-html (cond ((null patients) (setf (current-patient) nil invalidate t) (htm (str #!"You do not have access to any patients"))) ((null (cdr patients)) (let ((patient (car patients))) (unless (eq patient (current-patient)) (setf (current-patient) patient invalidate t)) (htm "<b>Patient:</b> " (str (id patient))))) (t (let ((patient (current-patient)) (action (lambda (&key patient &allow-other-keys) (cond ((get-patient patient center t) (setf (current-patient) patient) (if (mark-siblings-dirty-p widget) (mark-dirty (car (last (widget-parents widget)))))) (t (mark-dirty widget)))))) (setf patients (sort patients #'string-lessp :key #'id)) (unless (member patient patients :test #'eq) (setf patient (car patients) (current-patient) patient invalidate t)) (with-html-form (:get action :use-ajax-p t :class "autodropdown") "<b>Patient:</b> " (render-dropdown "patient" (mapcar 'id patients) :selected-value (id patient) :autosubmitp t))))) (when (choose-patient-hr-p widget) (htm (:hr)))) (when (and invalidate (mark-siblings-dirty-p widget)) (mark-dirty (car (last (widget-parents widget))))))) (defun make-choose-patient-widget (&key (hr-p t) (mark-siblings-dirty-p nil)) (make-instance 'choose-patient :hr-p hr-p :mark-siblings-dirty-p mark-siblings-dirty-p))
4fc6fd4b0b7bb633b3d3fd5d95b9d8dc4fe6392c97b2c4a2727b4d6b90a0eee3
input-output-hk/plutus
ParamName.hs
# LANGUAGE DerivingVia # module PlutusLedgerApi.V3.ParamName ( ParamName (..) , tagWithParamNames ) where import Data.Ix import GHC.Generics import PlutusLedgerApi.Common.ParamName {-| The enumeration of all possible cost model parameter names for this language version. IMPORTANT: The order of appearance of the data constructors here matters. DO NOT REORDER. See Note [Quotation marks in cost model parameter constructors] See Note [Cost model parameters from the ledger's point of view] -} data ParamName = AddInteger'cpu'arguments'intercept | AddInteger'cpu'arguments'slope | AddInteger'memory'arguments'intercept | AddInteger'memory'arguments'slope | AppendByteString'cpu'arguments'intercept | AppendByteString'cpu'arguments'slope | AppendByteString'memory'arguments'intercept | AppendByteString'memory'arguments'slope | AppendString'cpu'arguments'intercept | AppendString'cpu'arguments'slope | AppendString'memory'arguments'intercept | AppendString'memory'arguments'slope | BData'cpu'arguments | BData'memory'arguments | Blake2b_256'cpu'arguments'intercept | Blake2b_256'cpu'arguments'slope | Blake2b_256'memory'arguments | CekApplyCost'exBudgetCPU | CekApplyCost'exBudgetMemory | CekBuiltinCost'exBudgetCPU | CekBuiltinCost'exBudgetMemory | CekConstCost'exBudgetCPU | CekConstCost'exBudgetMemory | CekDelayCost'exBudgetCPU | CekDelayCost'exBudgetMemory | CekForceCost'exBudgetCPU | CekForceCost'exBudgetMemory | CekLamCost'exBudgetCPU | CekLamCost'exBudgetMemory | CekStartupCost'exBudgetCPU | CekStartupCost'exBudgetMemory | CekVarCost'exBudgetCPU | CekVarCost'exBudgetMemory | ChooseData'cpu'arguments | ChooseData'memory'arguments | ChooseList'cpu'arguments | ChooseList'memory'arguments | ChooseUnit'cpu'arguments | ChooseUnit'memory'arguments | ConsByteString'cpu'arguments'intercept | ConsByteString'cpu'arguments'slope | ConsByteString'memory'arguments'intercept | ConsByteString'memory'arguments'slope | ConstrData'cpu'arguments | ConstrData'memory'arguments | DecodeUtf8'cpu'arguments'intercept | DecodeUtf8'cpu'arguments'slope | DecodeUtf8'memory'arguments'intercept | DecodeUtf8'memory'arguments'slope | DivideInteger'cpu'arguments'constant | DivideInteger'cpu'arguments'model'arguments'intercept | DivideInteger'cpu'arguments'model'arguments'slope | DivideInteger'memory'arguments'intercept | DivideInteger'memory'arguments'minimum | DivideInteger'memory'arguments'slope | EncodeUtf8'cpu'arguments'intercept | EncodeUtf8'cpu'arguments'slope | EncodeUtf8'memory'arguments'intercept | EncodeUtf8'memory'arguments'slope | EqualsByteString'cpu'arguments'constant | EqualsByteString'cpu'arguments'intercept | EqualsByteString'cpu'arguments'slope | EqualsByteString'memory'arguments | EqualsData'cpu'arguments'intercept | EqualsData'cpu'arguments'slope | EqualsData'memory'arguments | EqualsInteger'cpu'arguments'intercept | EqualsInteger'cpu'arguments'slope | EqualsInteger'memory'arguments | EqualsString'cpu'arguments'constant | EqualsString'cpu'arguments'intercept | EqualsString'cpu'arguments'slope | EqualsString'memory'arguments | FstPair'cpu'arguments | FstPair'memory'arguments | HeadList'cpu'arguments | HeadList'memory'arguments | IData'cpu'arguments | IData'memory'arguments | IfThenElse'cpu'arguments | IfThenElse'memory'arguments | IndexByteString'cpu'arguments | IndexByteString'memory'arguments | LengthOfByteString'cpu'arguments | LengthOfByteString'memory'arguments | LessThanByteString'cpu'arguments'intercept | LessThanByteString'cpu'arguments'slope | LessThanByteString'memory'arguments | LessThanEqualsByteString'cpu'arguments'intercept | LessThanEqualsByteString'cpu'arguments'slope | LessThanEqualsByteString'memory'arguments | LessThanEqualsInteger'cpu'arguments'intercept | LessThanEqualsInteger'cpu'arguments'slope | LessThanEqualsInteger'memory'arguments | LessThanInteger'cpu'arguments'intercept | LessThanInteger'cpu'arguments'slope | LessThanInteger'memory'arguments | ListData'cpu'arguments | ListData'memory'arguments | MapData'cpu'arguments | MapData'memory'arguments | MkCons'cpu'arguments | MkCons'memory'arguments | MkNilData'cpu'arguments | MkNilData'memory'arguments | MkNilPairData'cpu'arguments | MkNilPairData'memory'arguments | MkPairData'cpu'arguments | MkPairData'memory'arguments | ModInteger'cpu'arguments'constant | ModInteger'cpu'arguments'model'arguments'intercept | ModInteger'cpu'arguments'model'arguments'slope | ModInteger'memory'arguments'intercept | ModInteger'memory'arguments'minimum | ModInteger'memory'arguments'slope | MultiplyInteger'cpu'arguments'intercept | MultiplyInteger'cpu'arguments'slope | MultiplyInteger'memory'arguments'intercept | MultiplyInteger'memory'arguments'slope | NullList'cpu'arguments | NullList'memory'arguments | QuotientInteger'cpu'arguments'constant | QuotientInteger'cpu'arguments'model'arguments'intercept | QuotientInteger'cpu'arguments'model'arguments'slope | QuotientInteger'memory'arguments'intercept | QuotientInteger'memory'arguments'minimum | QuotientInteger'memory'arguments'slope | RemainderInteger'cpu'arguments'constant | RemainderInteger'cpu'arguments'model'arguments'intercept | RemainderInteger'cpu'arguments'model'arguments'slope | RemainderInteger'memory'arguments'intercept | RemainderInteger'memory'arguments'minimum | RemainderInteger'memory'arguments'slope | SerialiseData'cpu'arguments'intercept | SerialiseData'cpu'arguments'slope | SerialiseData'memory'arguments'intercept | SerialiseData'memory'arguments'slope | Sha2_256'cpu'arguments'intercept | Sha2_256'cpu'arguments'slope | Sha2_256'memory'arguments | Sha3_256'cpu'arguments'intercept | Sha3_256'cpu'arguments'slope | Sha3_256'memory'arguments | SliceByteString'cpu'arguments'intercept | SliceByteString'cpu'arguments'slope | SliceByteString'memory'arguments'intercept | SliceByteString'memory'arguments'slope | SndPair'cpu'arguments | SndPair'memory'arguments | SubtractInteger'cpu'arguments'intercept | SubtractInteger'cpu'arguments'slope | SubtractInteger'memory'arguments'intercept | SubtractInteger'memory'arguments'slope | TailList'cpu'arguments | TailList'memory'arguments | Trace'cpu'arguments | Trace'memory'arguments | UnBData'cpu'arguments | UnBData'memory'arguments | UnConstrData'cpu'arguments | UnConstrData'memory'arguments | UnIData'cpu'arguments | UnIData'memory'arguments | UnListData'cpu'arguments | UnListData'memory'arguments | UnMapData'cpu'arguments | UnMapData'memory'arguments | VerifyEcdsaSecp256k1Signature'cpu'arguments | VerifyEcdsaSecp256k1Signature'memory'arguments | VerifyEd25519Signature'cpu'arguments'intercept | VerifyEd25519Signature'cpu'arguments'slope | VerifyEd25519Signature'memory'arguments | VerifySchnorrSecp256k1Signature'cpu'arguments'intercept | VerifySchnorrSecp256k1Signature'cpu'arguments'slope | VerifySchnorrSecp256k1Signature'memory'arguments deriving stock (Eq, Ord, Enum, Ix, Bounded, Generic) deriving IsParamName via (GenericParamName ParamName)
null
https://raw.githubusercontent.com/input-output-hk/plutus/c3918d6027a9a34b6f72a6e4c7bf2e5350e6467e/plutus-ledger-api/src/PlutusLedgerApi/V3/ParamName.hs
haskell
| The enumeration of all possible cost model parameter names for this language version. IMPORTANT: The order of appearance of the data constructors here matters. DO NOT REORDER. See Note [Quotation marks in cost model parameter constructors] See Note [Cost model parameters from the ledger's point of view]
# LANGUAGE DerivingVia # module PlutusLedgerApi.V3.ParamName ( ParamName (..) , tagWithParamNames ) where import Data.Ix import GHC.Generics import PlutusLedgerApi.Common.ParamName data ParamName = AddInteger'cpu'arguments'intercept | AddInteger'cpu'arguments'slope | AddInteger'memory'arguments'intercept | AddInteger'memory'arguments'slope | AppendByteString'cpu'arguments'intercept | AppendByteString'cpu'arguments'slope | AppendByteString'memory'arguments'intercept | AppendByteString'memory'arguments'slope | AppendString'cpu'arguments'intercept | AppendString'cpu'arguments'slope | AppendString'memory'arguments'intercept | AppendString'memory'arguments'slope | BData'cpu'arguments | BData'memory'arguments | Blake2b_256'cpu'arguments'intercept | Blake2b_256'cpu'arguments'slope | Blake2b_256'memory'arguments | CekApplyCost'exBudgetCPU | CekApplyCost'exBudgetMemory | CekBuiltinCost'exBudgetCPU | CekBuiltinCost'exBudgetMemory | CekConstCost'exBudgetCPU | CekConstCost'exBudgetMemory | CekDelayCost'exBudgetCPU | CekDelayCost'exBudgetMemory | CekForceCost'exBudgetCPU | CekForceCost'exBudgetMemory | CekLamCost'exBudgetCPU | CekLamCost'exBudgetMemory | CekStartupCost'exBudgetCPU | CekStartupCost'exBudgetMemory | CekVarCost'exBudgetCPU | CekVarCost'exBudgetMemory | ChooseData'cpu'arguments | ChooseData'memory'arguments | ChooseList'cpu'arguments | ChooseList'memory'arguments | ChooseUnit'cpu'arguments | ChooseUnit'memory'arguments | ConsByteString'cpu'arguments'intercept | ConsByteString'cpu'arguments'slope | ConsByteString'memory'arguments'intercept | ConsByteString'memory'arguments'slope | ConstrData'cpu'arguments | ConstrData'memory'arguments | DecodeUtf8'cpu'arguments'intercept | DecodeUtf8'cpu'arguments'slope | DecodeUtf8'memory'arguments'intercept | DecodeUtf8'memory'arguments'slope | DivideInteger'cpu'arguments'constant | DivideInteger'cpu'arguments'model'arguments'intercept | DivideInteger'cpu'arguments'model'arguments'slope | DivideInteger'memory'arguments'intercept | DivideInteger'memory'arguments'minimum | DivideInteger'memory'arguments'slope | EncodeUtf8'cpu'arguments'intercept | EncodeUtf8'cpu'arguments'slope | EncodeUtf8'memory'arguments'intercept | EncodeUtf8'memory'arguments'slope | EqualsByteString'cpu'arguments'constant | EqualsByteString'cpu'arguments'intercept | EqualsByteString'cpu'arguments'slope | EqualsByteString'memory'arguments | EqualsData'cpu'arguments'intercept | EqualsData'cpu'arguments'slope | EqualsData'memory'arguments | EqualsInteger'cpu'arguments'intercept | EqualsInteger'cpu'arguments'slope | EqualsInteger'memory'arguments | EqualsString'cpu'arguments'constant | EqualsString'cpu'arguments'intercept | EqualsString'cpu'arguments'slope | EqualsString'memory'arguments | FstPair'cpu'arguments | FstPair'memory'arguments | HeadList'cpu'arguments | HeadList'memory'arguments | IData'cpu'arguments | IData'memory'arguments | IfThenElse'cpu'arguments | IfThenElse'memory'arguments | IndexByteString'cpu'arguments | IndexByteString'memory'arguments | LengthOfByteString'cpu'arguments | LengthOfByteString'memory'arguments | LessThanByteString'cpu'arguments'intercept | LessThanByteString'cpu'arguments'slope | LessThanByteString'memory'arguments | LessThanEqualsByteString'cpu'arguments'intercept | LessThanEqualsByteString'cpu'arguments'slope | LessThanEqualsByteString'memory'arguments | LessThanEqualsInteger'cpu'arguments'intercept | LessThanEqualsInteger'cpu'arguments'slope | LessThanEqualsInteger'memory'arguments | LessThanInteger'cpu'arguments'intercept | LessThanInteger'cpu'arguments'slope | LessThanInteger'memory'arguments | ListData'cpu'arguments | ListData'memory'arguments | MapData'cpu'arguments | MapData'memory'arguments | MkCons'cpu'arguments | MkCons'memory'arguments | MkNilData'cpu'arguments | MkNilData'memory'arguments | MkNilPairData'cpu'arguments | MkNilPairData'memory'arguments | MkPairData'cpu'arguments | MkPairData'memory'arguments | ModInteger'cpu'arguments'constant | ModInteger'cpu'arguments'model'arguments'intercept | ModInteger'cpu'arguments'model'arguments'slope | ModInteger'memory'arguments'intercept | ModInteger'memory'arguments'minimum | ModInteger'memory'arguments'slope | MultiplyInteger'cpu'arguments'intercept | MultiplyInteger'cpu'arguments'slope | MultiplyInteger'memory'arguments'intercept | MultiplyInteger'memory'arguments'slope | NullList'cpu'arguments | NullList'memory'arguments | QuotientInteger'cpu'arguments'constant | QuotientInteger'cpu'arguments'model'arguments'intercept | QuotientInteger'cpu'arguments'model'arguments'slope | QuotientInteger'memory'arguments'intercept | QuotientInteger'memory'arguments'minimum | QuotientInteger'memory'arguments'slope | RemainderInteger'cpu'arguments'constant | RemainderInteger'cpu'arguments'model'arguments'intercept | RemainderInteger'cpu'arguments'model'arguments'slope | RemainderInteger'memory'arguments'intercept | RemainderInteger'memory'arguments'minimum | RemainderInteger'memory'arguments'slope | SerialiseData'cpu'arguments'intercept | SerialiseData'cpu'arguments'slope | SerialiseData'memory'arguments'intercept | SerialiseData'memory'arguments'slope | Sha2_256'cpu'arguments'intercept | Sha2_256'cpu'arguments'slope | Sha2_256'memory'arguments | Sha3_256'cpu'arguments'intercept | Sha3_256'cpu'arguments'slope | Sha3_256'memory'arguments | SliceByteString'cpu'arguments'intercept | SliceByteString'cpu'arguments'slope | SliceByteString'memory'arguments'intercept | SliceByteString'memory'arguments'slope | SndPair'cpu'arguments | SndPair'memory'arguments | SubtractInteger'cpu'arguments'intercept | SubtractInteger'cpu'arguments'slope | SubtractInteger'memory'arguments'intercept | SubtractInteger'memory'arguments'slope | TailList'cpu'arguments | TailList'memory'arguments | Trace'cpu'arguments | Trace'memory'arguments | UnBData'cpu'arguments | UnBData'memory'arguments | UnConstrData'cpu'arguments | UnConstrData'memory'arguments | UnIData'cpu'arguments | UnIData'memory'arguments | UnListData'cpu'arguments | UnListData'memory'arguments | UnMapData'cpu'arguments | UnMapData'memory'arguments | VerifyEcdsaSecp256k1Signature'cpu'arguments | VerifyEcdsaSecp256k1Signature'memory'arguments | VerifyEd25519Signature'cpu'arguments'intercept | VerifyEd25519Signature'cpu'arguments'slope | VerifyEd25519Signature'memory'arguments | VerifySchnorrSecp256k1Signature'cpu'arguments'intercept | VerifySchnorrSecp256k1Signature'cpu'arguments'slope | VerifySchnorrSecp256k1Signature'memory'arguments deriving stock (Eq, Ord, Enum, Ix, Bounded, Generic) deriving IsParamName via (GenericParamName ParamName)
8ebdd40f86d4c7b7e9e413378150cadf5f045b2665603f019fc1f79bd08cdc75
DanielG/ghc-mod
CheckSpec.hs
# LANGUAGE CPP # module CheckSpec where import GhcMod import Data.List import System.Process import Test.Hspec import TestUtils import Dir spec :: Spec spec = do describe "checkSyntax" $ do it "works even if an executable depends on the library defined in the same cabal file" $ do withDirectory_ "test/data/ghc-mod-check" $ do res <- runD $ checkSyntax ["main.hs"] res `shouldBe` "main.hs:5:1:Warning: Top-level binding with no type signature: main :: IO ()\n" it "works even if a module imports another module from a different directory" $ do withDirectory_ "test/data/check-test-subdir" $ do _ <- system "cabal configure --enable-tests" res <- runD $ checkSyntax ["test/Bar/Baz.hs"] res `shouldSatisfy` (("test" </> "Foo.hs:3:1:Warning: Top-level binding with no type signature: foo :: [Char]\n") `isSuffixOf`) it "detects cyclic imports" $ do withDirectory_ "test/data/import-cycle" $ do res <- runD $ checkSyntax ["Mutual1.hs"] res `shouldSatisfy` ("Module imports form a cycle" `isInfixOf`) it "works with modules using QuasiQuotes" $ do withDirectory_ "test/data/quasi-quotes" $ do res <- runD $ checkSyntax ["QuasiQuotes.hs"] res `shouldSatisfy` ("QuasiQuotes.hs:6:1:Warning:" `isInfixOf`) #if __GLASGOW_HASKELL__ >= 708 it "works with modules using PatternSynonyms" $ do withDirectory_ "test/data/pattern-synonyms" $ do res <- runD $ checkSyntax ["B.hs"] res `shouldSatisfy` ("B.hs:6:9:Warning:" `isPrefixOf`) #endif it "works with foreign exports" $ do withDirectory_ "test/data/foreign-export" $ do res <- runD $ checkSyntax ["ForeignExport.hs"] res `shouldBe` "" context "when no errors are found" $ do it "doesn't output an empty line" $ do withDirectory_ "test/data/ghc-mod-check/lib/Data" $ do res <- runD $ checkSyntax ["Foo.hs"] res `shouldBe` "" #if __GLASGOW_HASKELL__ >= 708 -- See -yamamoto/ghc-mod/issues/507 it "emits warnings generated in GHC's desugar stage" $ do withDirectory_ "test/data/check-missing-warnings" $ do res <- runD $ checkSyntax ["DesugarWarnings.hs"] res `shouldSatisfy` ("DesugarWarnings.hs:4:9:Warning: Pattern match(es) are non-exhaustive\NULIn a case alternative: Patterns not matched:" `isPrefixOf`) #endif it "works with cabal builtin preprocessors" $ do withDirectory_ "test/data/cabal-preprocessors" $ do _ <- system "cabal clean" _ <- system "cabal build" res <- runD $ checkSyntax ["Main.hs"] res `shouldBe` "Preprocessed.hsc:3:1:Warning: Top-level binding with no type signature: warning :: ()\n" it "Uses the right qualification style" $ do withDirectory_ "test/data/nice-qualification" $ do res <- runD $ checkSyntax ["NiceQualification.hs"] #if __GLASGOW_HASKELL__ >= 800 res `shouldBe` "NiceQualification.hs:4:8:\8226 Couldn't match expected type \8216IO ()\8217 with actual type \8216[Char]\8217\NUL\8226 In the expression: \"wrong type\"\NUL In an equation for \8216main\8217: main = \"wrong type\"\n" #elif __GLASGOW_HASKELL__ >= 708 res `shouldBe` "NiceQualification.hs:4:8:Couldn't match expected type \8216IO ()\8217 with actual type \8216[Char]\8217\NULIn the expression: \"wrong type\"\NULIn an equation for \8216main\8217: main = \"wrong type\"\n" #else res `shouldBe` "NiceQualification.hs:4:8:Couldn't match expected type `IO ()' with actual type `[Char]'\NULIn the expression: \"wrong type\"\NULIn an equation for `main': main = \"wrong type\"\n" #endif
null
https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/test/CheckSpec.hs
haskell
See -yamamoto/ghc-mod/issues/507
# LANGUAGE CPP # module CheckSpec where import GhcMod import Data.List import System.Process import Test.Hspec import TestUtils import Dir spec :: Spec spec = do describe "checkSyntax" $ do it "works even if an executable depends on the library defined in the same cabal file" $ do withDirectory_ "test/data/ghc-mod-check" $ do res <- runD $ checkSyntax ["main.hs"] res `shouldBe` "main.hs:5:1:Warning: Top-level binding with no type signature: main :: IO ()\n" it "works even if a module imports another module from a different directory" $ do withDirectory_ "test/data/check-test-subdir" $ do _ <- system "cabal configure --enable-tests" res <- runD $ checkSyntax ["test/Bar/Baz.hs"] res `shouldSatisfy` (("test" </> "Foo.hs:3:1:Warning: Top-level binding with no type signature: foo :: [Char]\n") `isSuffixOf`) it "detects cyclic imports" $ do withDirectory_ "test/data/import-cycle" $ do res <- runD $ checkSyntax ["Mutual1.hs"] res `shouldSatisfy` ("Module imports form a cycle" `isInfixOf`) it "works with modules using QuasiQuotes" $ do withDirectory_ "test/data/quasi-quotes" $ do res <- runD $ checkSyntax ["QuasiQuotes.hs"] res `shouldSatisfy` ("QuasiQuotes.hs:6:1:Warning:" `isInfixOf`) #if __GLASGOW_HASKELL__ >= 708 it "works with modules using PatternSynonyms" $ do withDirectory_ "test/data/pattern-synonyms" $ do res <- runD $ checkSyntax ["B.hs"] res `shouldSatisfy` ("B.hs:6:9:Warning:" `isPrefixOf`) #endif it "works with foreign exports" $ do withDirectory_ "test/data/foreign-export" $ do res <- runD $ checkSyntax ["ForeignExport.hs"] res `shouldBe` "" context "when no errors are found" $ do it "doesn't output an empty line" $ do withDirectory_ "test/data/ghc-mod-check/lib/Data" $ do res <- runD $ checkSyntax ["Foo.hs"] res `shouldBe` "" #if __GLASGOW_HASKELL__ >= 708 it "emits warnings generated in GHC's desugar stage" $ do withDirectory_ "test/data/check-missing-warnings" $ do res <- runD $ checkSyntax ["DesugarWarnings.hs"] res `shouldSatisfy` ("DesugarWarnings.hs:4:9:Warning: Pattern match(es) are non-exhaustive\NULIn a case alternative: Patterns not matched:" `isPrefixOf`) #endif it "works with cabal builtin preprocessors" $ do withDirectory_ "test/data/cabal-preprocessors" $ do _ <- system "cabal clean" _ <- system "cabal build" res <- runD $ checkSyntax ["Main.hs"] res `shouldBe` "Preprocessed.hsc:3:1:Warning: Top-level binding with no type signature: warning :: ()\n" it "Uses the right qualification style" $ do withDirectory_ "test/data/nice-qualification" $ do res <- runD $ checkSyntax ["NiceQualification.hs"] #if __GLASGOW_HASKELL__ >= 800 res `shouldBe` "NiceQualification.hs:4:8:\8226 Couldn't match expected type \8216IO ()\8217 with actual type \8216[Char]\8217\NUL\8226 In the expression: \"wrong type\"\NUL In an equation for \8216main\8217: main = \"wrong type\"\n" #elif __GLASGOW_HASKELL__ >= 708 res `shouldBe` "NiceQualification.hs:4:8:Couldn't match expected type \8216IO ()\8217 with actual type \8216[Char]\8217\NULIn the expression: \"wrong type\"\NULIn an equation for \8216main\8217: main = \"wrong type\"\n" #else res `shouldBe` "NiceQualification.hs:4:8:Couldn't match expected type `IO ()' with actual type `[Char]'\NULIn the expression: \"wrong type\"\NULIn an equation for `main': main = \"wrong type\"\n" #endif
ad51014accb626f270169f0d41da7c173cd81a57fee43bf738be3455c30e1ad5
spawnfest/eep49ers
wxColourData.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2021 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT -module(wxColourData). -include("wxe.hrl"). -export([destroy/1,getChooseFull/1,getColour/1,getCustomColour/2,new/0,setChooseFull/2, setColour/2,setCustomColour/3]). %% inherited exports -export([parent_class/1]). -type wxColourData() :: wx:wx_object(). -export_type([wxColourData/0]). %% @hidden parent_class(_Class) -> erlang:error({badtype, ?MODULE}). %% @doc See <a href="#wxcolourdatawxcolourdata">external documentation</a>. -spec new() -> wxColourData(). new() -> wxe_util:queue_cmd(?get_env(), ?wxColourData_new), wxe_util:rec(?wxColourData_new). %% @doc See <a href="#wxcolourdatagetchoosefull">external documentation</a>. -spec getChooseFull(This) -> boolean() when This::wxColourData(). getChooseFull(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,?get_env(),?wxColourData_GetChooseFull), wxe_util:rec(?wxColourData_GetChooseFull). %% @doc See <a href="#wxcolourdatagetcolour">external documentation</a>. -spec getColour(This) -> wx:wx_colour4() when This::wxColourData(). getColour(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,?get_env(),?wxColourData_GetColour), wxe_util:rec(?wxColourData_GetColour). %% @doc See <a href="#wxcolourdatagetcustomcolour">external documentation</a>. -spec getCustomColour(This, I) -> wx:wx_colour4() when This::wxColourData(), I::integer(). getCustomColour(#wx_ref{type=ThisT}=This,I) when is_integer(I) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,I,?get_env(),?wxColourData_GetCustomColour), wxe_util:rec(?wxColourData_GetCustomColour). %% @doc See <a href="#wxcolourdatasetchoosefull">external documentation</a>. -spec setChooseFull(This, Flag) -> 'ok' when This::wxColourData(), Flag::boolean(). setChooseFull(#wx_ref{type=ThisT}=This,Flag) when is_boolean(Flag) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,Flag,?get_env(),?wxColourData_SetChooseFull). %% @doc See <a href="#wxcolourdatasetcolour">external documentation</a>. -spec setColour(This, Colour) -> 'ok' when This::wxColourData(), Colour::wx:wx_colour(). setColour(#wx_ref{type=ThisT}=This,Colour) when ?is_colordata(Colour) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,wxe_util:color(Colour),?get_env(),?wxColourData_SetColour). %% @doc See <a href="#wxcolourdatasetcustomcolour">external documentation</a>. -spec setCustomColour(This, I, Colour) -> 'ok' when This::wxColourData(), I::integer(), Colour::wx:wx_colour(). setCustomColour(#wx_ref{type=ThisT}=This,I,Colour) when is_integer(I),?is_colordata(Colour) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,I,wxe_util:color(Colour),?get_env(),?wxColourData_SetCustomColour). %% @doc Destroys this object, do not use object again -spec destroy(This::wxColourData()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxColourData), wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT), ok.
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxColourData.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT inherited exports @hidden @doc See <a href="#wxcolourdatawxcolourdata">external documentation</a>. @doc See <a href="#wxcolourdatagetchoosefull">external documentation</a>. @doc See <a href="#wxcolourdatagetcolour">external documentation</a>. @doc See <a href="#wxcolourdatagetcustomcolour">external documentation</a>. @doc See <a href="#wxcolourdatasetchoosefull">external documentation</a>. @doc See <a href="#wxcolourdatasetcolour">external documentation</a>. @doc See <a href="#wxcolourdatasetcustomcolour">external documentation</a>. @doc Destroys this object, do not use object again
Copyright Ericsson AB 2008 - 2021 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(wxColourData). -include("wxe.hrl"). -export([destroy/1,getChooseFull/1,getColour/1,getCustomColour/2,new/0,setChooseFull/2, setColour/2,setCustomColour/3]). -export([parent_class/1]). -type wxColourData() :: wx:wx_object(). -export_type([wxColourData/0]). parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -spec new() -> wxColourData(). new() -> wxe_util:queue_cmd(?get_env(), ?wxColourData_new), wxe_util:rec(?wxColourData_new). -spec getChooseFull(This) -> boolean() when This::wxColourData(). getChooseFull(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,?get_env(),?wxColourData_GetChooseFull), wxe_util:rec(?wxColourData_GetChooseFull). -spec getColour(This) -> wx:wx_colour4() when This::wxColourData(). getColour(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,?get_env(),?wxColourData_GetColour), wxe_util:rec(?wxColourData_GetColour). -spec getCustomColour(This, I) -> wx:wx_colour4() when This::wxColourData(), I::integer(). getCustomColour(#wx_ref{type=ThisT}=This,I) when is_integer(I) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,I,?get_env(),?wxColourData_GetCustomColour), wxe_util:rec(?wxColourData_GetCustomColour). -spec setChooseFull(This, Flag) -> 'ok' when This::wxColourData(), Flag::boolean(). setChooseFull(#wx_ref{type=ThisT}=This,Flag) when is_boolean(Flag) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,Flag,?get_env(),?wxColourData_SetChooseFull). -spec setColour(This, Colour) -> 'ok' when This::wxColourData(), Colour::wx:wx_colour(). setColour(#wx_ref{type=ThisT}=This,Colour) when ?is_colordata(Colour) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,wxe_util:color(Colour),?get_env(),?wxColourData_SetColour). -spec setCustomColour(This, I, Colour) -> 'ok' when This::wxColourData(), I::integer(), Colour::wx:wx_colour(). setCustomColour(#wx_ref{type=ThisT}=This,I,Colour) when is_integer(I),?is_colordata(Colour) -> ?CLASS(ThisT,wxColourData), wxe_util:queue_cmd(This,I,wxe_util:color(Colour),?get_env(),?wxColourData_SetCustomColour). -spec destroy(This::wxColourData()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxColourData), wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT), ok.
0d1f3408b561d8d0de1236b6056678d7c42c2d08192a4aa1ad19d47aa3bf408e
roman/Haskell-Reactive-Extensions
Types.hs
{-# LANGUAGE EmptyDataDecls #-} module Rx.Scheduler.Types where import Rx.Disposable (Disposable) import Tiempo (TimeInterval) data Async data Sync data Scheduler s = Scheduler { _immediateSchedule :: IO () -> IO Disposable , _timedSchedule :: TimeInterval -> IO () -> IO Disposable } class IScheduler scheduler where immediateSchedule :: scheduler s -> IO () -> IO Disposable timedSchedule :: scheduler s -> TimeInterval -> IO () -> IO Disposable instance IScheduler Scheduler where immediateSchedule = _immediateSchedule timedSchedule = _timedSchedule
null
https://raw.githubusercontent.com/roman/Haskell-Reactive-Extensions/0faddbb671be7f169eeadbe6163e8d0b2be229fb/rx-scheduler/src/Rx/Scheduler/Types.hs
haskell
# LANGUAGE EmptyDataDecls #
module Rx.Scheduler.Types where import Rx.Disposable (Disposable) import Tiempo (TimeInterval) data Async data Sync data Scheduler s = Scheduler { _immediateSchedule :: IO () -> IO Disposable , _timedSchedule :: TimeInterval -> IO () -> IO Disposable } class IScheduler scheduler where immediateSchedule :: scheduler s -> IO () -> IO Disposable timedSchedule :: scheduler s -> TimeInterval -> IO () -> IO Disposable instance IScheduler Scheduler where immediateSchedule = _immediateSchedule timedSchedule = _timedSchedule
7cbc6c9089c576aa9a1f9bc8210ed7ff347c5483bb86aaa3b3acb7f81e438433
onedata/op-worker
connection.erl
%%%------------------------------------------------------------------- @author ( C ) 2019 - 2020 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% This module handles communication using clproto binary protocol. Created connection can be one of the two possible types : %%% - incoming - when it is initiated in response to peer (provider or client) %%% request. It awaits client_messages, handles them and %%% responds with server_messages, %%% - outgoing - when this provider initiates it in order to connect to peer. In order to do so , first http protocol upgrade request on %%% ?CLIENT_PROTOCOL_PATH is send to other provider. %%% If confirmation response is received, meaning that protocol upgrade from http to clproto succeeded , then communication %%% using binary protocol can start. %%% This type of connection can send only client_messages and %%% receive server_messages. %%% %%% Beside type, connection has also one of the following statuses: %%% - upgrading_protocol - valid only for outgoing connection. This status %%% indicates that protocol upgrade request has been %%% sent and response is awaited, %%% - performing_handshake - indicates that connection either awaits %%% authentication request (incoming connection) %%% or response (outgoing connection), %%% - ready - indicates that connection is in operational mode, %%% so that it can send and receive messages. %%% %%% More detailed transitions between statuses for each connection type and %%% message flow is depicted on diagram below. %%% %%% INCOMING | OUTGOING %%% | %%% | Provider B %%% | | | 0 : start_link %%% | | %%% | v Provider A 1 : protocol + ------------+ %%% HTTP listener <------ upgrade ------ | init | %%% | request +------------+ %%% | | | 1.5 | 1.5 %%% | | | %%% v | v + ----------+ 2 : protocol + --------------------+ %%% | init | -------- upgrade ------> | upgrading_protocol | %%% +----------+ response +--------------------+ %%% | | | | 2.5 | | | %%% | | | | %%% v | | | + ----------------------+ 3 : handshake | | | performing_handshake | < ------ request ---------+ | + ----------------------+ | 3.5 %%% | | | | %%% | | | v | | 4 : handshake + ----------------------+ %%% | +--------- response ------> | performing_handshake | %%% | | +----------------------+ %%% | | | 4.5 | 4.5 %%% | | | %%% v | v %%% +-------+ <-------- n: client_message --------- +-------+ %%% | ready | | | ready | %%% +-------+ -------- n+1: server_message -------> +-------+ %%% | %%% %%% In case of errors during init, upgrading_protocol or performing_handshake %%% connection is immediately terminated. %%% On the other hand, when connection is in ready status, every kind of error %%% is logged, but only socket errors terminates it. %%% @end %%%------------------------------------------------------------------- -module(connection). -author("Bartosz Walkowicz"). -behaviour(gen_server). -behaviour(cowboy_sub_protocol). -include("timeouts.hrl"). -include("http/gui_paths.hrl"). -include("http/rest.hrl"). -include("global_definitions.hrl"). -include("proto/common/handshake_messages.hrl"). -include("proto/oneclient/server_messages.hrl"). -include("proto/oneclient/client_messages.hrl"). -include("proto/oneclient/common_messages.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("middleware/middleware.hrl"). -include_lib("ctool/include/aai/aai.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("ctool/include/errors.hrl"). -include_lib("ctool/include/http/headers.hrl"). -record(state, { socket :: ssl:sslsocket(), socket_mode = active_once :: active_always | active_once, transport :: module(), % transport messages ok :: atom(), closed :: atom(), error :: atom(), % connection state type :: incoming | outgoing, status :: upgrading_protocol | performing_handshake | ready, session_id = undefined :: undefined | session:id(), peer_id = undefined :: undefined | od_provider:id() | od_user:id(), peer_ip :: inet:ip4_address(), verify_msg = true :: boolean(), connection_manager = undefined :: undefined | pid(), % routing information base - structure necessary for routing. rib :: router:rib() | undefined }). -type state() :: #state{}. -type error() :: {error, Reason :: term()}. Default value for { packet , N } socket option . When specified , erlang first % reads N bytes to get length of your data, allocates a buffer to hold it % and reads data into buffer after getting each tcp packet. Then it sends the buffer as one msg to your process . -define(PACKET_VALUE, 4). -define(DEFAULT_SOCKET_MODE, op_worker:get_env(default_socket_mode, active_once) ). -define(DEFAULT_VERIFY_MSG_FLAG, op_worker:get_env(verify_msg_before_encoding, true) ). %% API -export([start_link/5, start_link/7, close/1]). -export([send_msg/2, send_keepalive/1]). -export([rebuild_rib/1]). -export([find_outgoing_session/1]). %% Private API -export([connect_with_provider/8]). %% cowboy_sub_protocol callbacks -export([init/2, upgrade/4, upgrade/5, takeover/7]). %% gen_server callbacks -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). -define(REBUILD_RIB_MSG, rebuild_rib). 5 minutes -define(THROTTLE_ERROR(__SESSION_ID, __FORMAT, __ARGS), begin ?debug(__FORMAT, __ARGS), utils:throttle({?MODULE, __SESSION_ID, ?LINE}, ?CONNECTION_AWAIT_LOG_INTERVAL, fun() -> ?error(__FORMAT, __ARGS) end) end ). -define(THROTTLE_ERROR_EXCEPTION(__SESSION_ID, __FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE), begin ?debug_exception(__FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE), utils:throttle({?MODULE, __SESSION_ID, ?LINE}, ?CONNECTION_AWAIT_LOG_INTERVAL, fun() -> ?error_exception(__FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE) end) end ). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% @equiv start_link(ProviderId, SessId, Domain, Host, Port, ranch_ssl, %% timer:seconds(5)). %% @end %%-------------------------------------------------------------------- -spec start_link(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer()) -> {ok, pid()} | error(). start_link(ProviderId, SessId, Domain, Host, Port) -> start_link(ProviderId, SessId, Domain, Host, Port, ranch_ssl, timer:seconds(5) ). %%-------------------------------------------------------------------- %% @doc %% Starts an outgoing connection to peer provider. %% @end %%-------------------------------------------------------------------- -spec start_link(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer()) -> {ok, pid()} | error(). start_link(ProviderId, SessId, Domain, Host, Port, Transport, Timeout) -> ConnManager = self(), proc_lib:start_link(?MODULE, connect_with_provider, [ ProviderId, SessId, Domain, Host, Port, Transport, Timeout, ConnManager ]). %%-------------------------------------------------------------------- %% @doc %% Sends msg for specified connection to shutdown itself. %% @end %%-------------------------------------------------------------------- close(Pid) -> gen_server2:cast(Pid, disconnect). %%------------------------------------------------------------------- %% @doc %% Tries to send a message and provides feedback about success or %% eventual errors while serializing/sending. %% @end %%------------------------------------------------------------------- -spec send_msg(pid(), communicator:message()) -> ok | error(). send_msg(Pid, Msg) -> call_connection_process(Pid, {send_msg, Msg}). %%------------------------------------------------------------------- %% @doc %% Schedules keepalive message to be sent. %% @end %%------------------------------------------------------------------- -spec send_keepalive(pid()) -> ok. send_keepalive(Pid) -> gen_server2:cast(Pid, send_keepalive). %%------------------------------------------------------------------- %% @doc %% Informs connection process that it should rebuild it's rib as it %% may be obsolete (e.g. after node death). %% @end %%------------------------------------------------------------------- -spec rebuild_rib(pid()) -> ok | error(). rebuild_rib(Pid) -> call_connection_process(Pid, ?REBUILD_RIB_MSG). -spec find_outgoing_session(oneprovider:id()) -> {ok, session:id()} | error. find_outgoing_session(ProviderId) -> SessionId = session_utils:get_provider_session_id(outgoing, ProviderId), case session:exists(SessionId) of true -> {ok, SessionId}; false -> error end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% This function is never called. We only define it so that %% we can use the -behaviour(gen_server) attribute. %% @end %%-------------------------------------------------------------------- -spec init([]) -> {ok, undefined}. init([]) -> {ok, undefined}. %%-------------------------------------------------------------------- @private %% @doc %% Handles call messages. %% @end %%-------------------------------------------------------------------- -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: state()) -> {reply, Reply :: term(), NewState :: state()} | {reply, Reply :: term(), NewState :: state(), timeout() | hibernate} | {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), Reply :: term(), NewState :: state()} | {stop, Reason :: term(), NewState :: state()}. handle_call({send_msg, Msg}, _From, #state{status = ready} = State) -> case send_message(State, Msg) of {ok, NewState} -> {reply, ok, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, serialization_failed} = SerializationError -> {reply, SerializationError, State, ?PROTO_CONNECTION_TIMEOUT}; {error, sending_msg_via_wrong_conn_type} = WrongConnError -> {reply, WrongConnError, State, ?PROTO_CONNECTION_TIMEOUT}; Error -> {stop, Error, Error, State} end; handle_call({send_msg, _Msg}, _From, #state{status = Status, socket = Socket} = State) -> ?warning("Attempt to send msg via not ready connection ~p", [Socket]), {reply, {error, Status}, State, ?PROTO_CONNECTION_TIMEOUT}; handle_call(?REBUILD_RIB_MSG, _From, #state{session_id = SessId} = State) -> {reply, ok, State#state{rib = router:build_rib(SessId)}, ?PROTO_CONNECTION_TIMEOUT}; handle_call(Request, _From, State) -> ?log_bad_request(Request), {reply, {error, wrong_request}, State, ?PROTO_CONNECTION_TIMEOUT}. %%-------------------------------------------------------------------- @private %% @doc %% Handles cast messages. %% @end %%-------------------------------------------------------------------- -spec handle_cast(Request :: term(), State :: state()) -> {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. handle_cast(send_keepalive, State) -> case socket_send(State, ?CLIENT_KEEPALIVE_MSG) of {ok, NewState} -> {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; Error -> {stop, Error, State} end; handle_cast(disconnect, State) -> {stop, normal, State}; handle_cast(Request, State) -> ?log_bad_request(Request), {noreply, State, ?PROTO_CONNECTION_TIMEOUT}. %%-------------------------------------------------------------------- @private %% @doc %% Handles all non call/cast messages. %% @end %%-------------------------------------------------------------------- -spec handle_info(Info :: timeout() | {Ok :: atom(), Socket :: ssl:sslsocket(), Data :: binary()} | term(), State :: state()) -> {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. handle_info({upgrade_protocol, Hostname}, State) -> UpgradeReq = connection_utils:protocol_upgrade_request(Hostname), case socket_send(State, UpgradeReq) of {ok, NewState} -> {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{ status = upgrading_protocol, session_id = SessId, socket = Socket, ok = Ok } = State) -> try handle_protocol_upgrade_response(State, Data) of {ok, State1} -> State2 = State1#state{status = performing_handshake}, activate_socket(State2, false), {noreply, State2, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> % Concrete errors were already logged in 'handle_protocol_upgrade_response' % so terminate gracefully as to not spam more error logs {stop, normal, State} catch throw:{error, _} = Error -> ?THROTTLE_ERROR(SessId, "Protocol upgrade failed due to ~p", [Error]), {stop, normal, State}; Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unexpected error during protocol upgrade", [], Class, Reason, Stacktrace ), {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{ status = performing_handshake, % outgoing session id is set when starting connection while incoming only % after successful handshake session_id = OutgoingSessIdOrUndefined, socket = Socket, ok = Ok } = State) -> try handle_handshake(State, Data) of {ok, #state{session_id = SessId} = State1} -> ok = session_connections:register(SessId, self()), State2 = State1#state{status = ready}, activate_socket(State2, false), {noreply, State2, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> % Concrete errors were already logged in 'handle_handshake' so % terminate gracefully as to not spam more error logs {stop, normal, State} catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( OutgoingSessIdOrUndefined, "Unexpected error while performing handshake", [], Class, Reason, Stacktrace ), {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{status = ready, socket = Socket, ok = Ok} = State) -> case handle_message(State, Data) of {ok, NewState} -> activate_socket(NewState, false), {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> % Concrete errors were already logged in 'handle_message' so % terminate gracefully as to not spam more error logs {stop, normal, State} end; handle_info({Error, Socket, Reason}, State = #state{error = Error}) -> ?warning("Connection ~p error: ~p", [Socket, Reason]), {stop, Reason, State}; handle_info({Closed, _}, State = #state{closed = Closed}) -> {stop, normal, State}; handle_info(timeout, State = #state{socket = Socket}) -> ?warning("Connection ~p timeout", [Socket]), {stop, timeout, State}; handle_info(Info, State) -> ?log_bad_request(Info), {noreply, State, ?PROTO_CONNECTION_TIMEOUT}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% @end %%-------------------------------------------------------------------- -spec terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()), State :: state()) -> term(). terminate(Reason, #state{session_id = SessId, socket = Socket} = State) -> ?log_terminate(Reason, State), case SessId of undefined -> ok; _ -> session_connections:deregister(SessId, self()) end, ssl:close(Socket), State. %%-------------------------------------------------------------------- @private %% @doc %% Converts process state when code is changed. %% @end %%-------------------------------------------------------------------- -spec code_change(OldVsn :: term() | {down, term()}, State :: state(), Extra :: term()) -> {ok, NewState :: state()} | error(). code_change(_OldVsn, State, _Extra) -> {ok, State}. %% ==================================================================== %% cowboy_sub_protocol callbacks %% ==================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Called by cowboy on receiving request on ?CLIENT_PROTOCOL_PATH path. %% Causes the upgrade callback to be called. %% @end %%-------------------------------------------------------------------- -spec init(cowboy_req:req(), any()) -> {?MODULE, cowboy_req:req(), any()}. init(Req, Opts) -> {?MODULE, Req, Opts}. %%-------------------------------------------------------------------- @private %% @doc Initiates protocol switch from http to ? CLIENT_PROTOCOL_UPGRADE_NAME %% if received request is proper upgrade request. Otherwise responds with either 426 or 400 . %% @end %%-------------------------------------------------------------------- -spec upgrade(cowboy_req:req(), cowboy_middleware:env(), module(), any()) -> {ok, cowboy_req:req(), cowboy_middleware:env()} | {stop, cowboy_req:req()}. upgrade(Req, Env, Handler, HandlerState) -> upgrade(Req, Env, Handler, HandlerState, #{}). -spec upgrade(cowboy_req:req(), cowboy_middleware:env(), module(), any(), any()) -> {ok, cowboy_req:req(), cowboy_middleware:env()} | {stop, cowboy_req:req()}. upgrade(Req, Env, _Handler, HandlerOpts, _Opts) -> try connection_utils:process_protocol_upgrade_request(Req) of ok -> Headers = cowboy_req:response_headers(#{ ?HDR_CONNECTION => <<"Upgrade">>, ?HDR_UPGRADE => <<?CLIENT_PROTOCOL_UPGRADE_NAME>> }, Req), #{pid := Pid, streamid := StreamID} = Req, Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, HandlerOpts}}, {ok, Req, Env}; {error, upgrade_required} -> NewReq = cowboy_req:reply(?HTTP_426_UPGRADE_REQUIRED, #{ ?HDR_CONNECTION => <<"Upgrade">>, ?HDR_UPGRADE => <<?CLIENT_PROTOCOL_UPGRADE_NAME>> }, Req), {stop, NewReq} catch Type:Reason -> ?debug("Invalid protocol upgrade request - ~p:~p", [Type, Reason]), cowboy_req:reply(?HTTP_400_BAD_REQUEST, Req), {stop, Req} end. %%-------------------------------------------------------------------- @private %% @doc %% Called after successful upgrade. %% Takes over connection process and changes it to gen_server. %% @end %%-------------------------------------------------------------------- -spec takeover(pid(), ranch:ref(), ssl:sslsocket(), module(), any(), binary(), any()) -> no_return(). takeover(_Parent, Ref, Socket, Transport, _Opts, _Buffer, _HandlerState) -> % Remove connection from the overall connections count so it will not be % included in limiting the number of e.g. REST connections. ranch:remove_connection(Ref), {ok, {IpAddress, _Port}} = ssl:peername(Socket), {Ok, Closed, Error, _} = Transport:messages(), State = #state{ socket = Socket, socket_mode = ?DEFAULT_SOCKET_MODE, transport = Transport, ok = Ok, closed = Closed, error = Error, peer_ip = IpAddress, type = incoming, status = performing_handshake, verify_msg = ?DEFAULT_VERIFY_MSG_FLAG }, ok = Transport:setopts(Socket, [binary, {packet, ?PACKET_VALUE}]), activate_socket(State, true), gen_server2:enter_loop(?MODULE, [], State, ?PROTO_CONNECTION_TIMEOUT). %% ====================================================================== %% Functions used when initialising outgoing connection to peer provider %% ====================================================================== %%-------------------------------------------------------------------- %% @doc %% Initializes an outgoing connection to peer provider. %% @end %%-------------------------------------------------------------------- -spec connect_with_provider(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer(), ConnManager :: pid() ) -> no_return(). connect_with_provider(ProviderId, SessId, Domain, Host, Port, Transport, Timeout, ConnManager ) -> DomainAndIpInfo = case Domain of Host -> str_utils:format("@ ~s:~b", [Host, Port]); _ -> str_utils:format("@ ~s:~b (~s)", [Host, Port, Domain]) end, ?debug("Connecting to provider ~ts ~s", [ provider_logic:to_printable(ProviderId), DomainAndIpInfo ]), try State = open_socket_to_provider( SessId, ProviderId, Domain, Host, Port, Transport, Timeout, ConnManager ), activate_socket(State, true), self() ! {upgrade_protocol, Host}, ok = proc_lib:init_ack({ok, self()}), process_flag(trap_exit, true), gen_server2:enter_loop(?MODULE, [], State, ?PROTO_CONNECTION_TIMEOUT) catch _:Reason -> exit(Reason) end. @private -spec open_socket_to_provider(session:id(), od_provider:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer(), ConnManager :: pid() ) -> state() | no_return(). open_socket_to_provider(SessId, ProviderId, Domain, Host, Port, Transport, Timeout, ConnManager ) -> SslOpts = provider_logic:provider_connection_ssl_opts(Domain), ConnectOpts = secure_ssl_opts:expand(SslOpts), {ok, Socket} = Transport:connect( binary_to_list(Host), Port, ConnectOpts, Timeout ), {ok, {IpAddress, _Port}} = ssl:peername(Socket), {Ok, Closed, Error, _} = Transport:messages(), #state{ socket = Socket, socket_mode = ?DEFAULT_SOCKET_MODE, transport = Transport, ok = Ok, closed = Closed, error = Error, type = outgoing, status = upgrading_protocol, session_id = SessId, peer_id = ProviderId, peer_ip = IpAddress, verify_msg = ?DEFAULT_VERIFY_MSG_FLAG, connection_manager = ConnManager, rib = router:build_rib(SessId) }. %%%=================================================================== Internal functions %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc Verifies protocol upgrade response and sends handshake request . %% @end %%-------------------------------------------------------------------- -spec handle_protocol_upgrade_response(state(), Data :: binary()) -> {ok, state()} | error(). handle_protocol_upgrade_response(#state{session_id = SessId} = State, Data) -> case connection_utils:verify_protocol_upgrade_response(Data) of false -> ?THROTTLE_ERROR(SessId, "Received invalid protocol upgrade response: ~p", [Data]), {error, invalid_protocol_upgrade_response}; true -> #state{ socket = Socket, transport = Transport, peer_id = ProviderId } = State, {ok, MsgId} = clproto_message_id:generate(self()), Token = ?check(provider_auth:acquire_identity_token_for_consumer( ?SUB(?ONEPROVIDER, ProviderId) )), ClientMsg = #client_message{ message_id = MsgId, message_body = #provider_handshake_request{ provider_id = oneprovider:get_id(), token = Token } }, ok = Transport:setopts(Socket, [binary, {packet, ?PACKET_VALUE}]), send_client_message(State, ClientMsg) end. @private -spec handle_handshake(state(), binary()) -> {ok, state()} | error(). handle_handshake(#state{type = incoming} = State, Data) -> handle_handshake_request(State, Data); handle_handshake(#state{type = outgoing} = State, Data) -> handle_handshake_response(State, Data). @private -spec handle_handshake_request(state(), binary()) -> {ok, state()} | error(). handle_handshake_request(#state{peer_ip = IpAddress} = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_client_message(Data, undefined), {PeerId, SessId} = connection_auth:handle_handshake( Msg#client_message.message_body, IpAddress ), NewState = State#state{ peer_id = PeerId, session_id = SessId, rib = router:build_rib(SessId) }, send_server_message(NewState, #server_message{ message_body = #handshake_response{status = 'OK'} }) catch Type:Reason -> ?debug("Invalid handshake request - ~p:~p", [Type, Reason]), ErrorMsg = connection_auth:get_handshake_error_msg(Reason), send_server_message(State, ErrorMsg), {error, handshake_failed} end. @private -spec handle_handshake_response(state(), binary()) -> {ok, state()} | error(). handle_handshake_response(#state{ session_id = SessId, peer_id = ProviderId, connection_manager = ConnManager } = State, Data) -> try clproto_serializer:deserialize_server_message(Data, SessId) of {ok, #server_message{message_body = #handshake_response{status = 'OK'}}} -> ?info("Successfully connected to provider ~ts", [ provider_logic:to_printable(ProviderId) ]), outgoing_connection_manager:report_successful_handshake(ConnManager), {ok, State}; {ok, #server_message{message_body = #handshake_response{status = Error}}} -> ?THROTTLE_ERROR( SessId, "Handshake refused by provider ~ts due to ~p, closing connection.", [provider_logic:to_printable(ProviderId), Error] ), {error, handshake_failed}; _ -> ?THROTTLE_ERROR( SessId, "Received invalid handshake response from provider ~ts, closing connection.", [provider_logic:to_printable(ProviderId)] ), {error, handshake_failed} catch _:Error -> ?THROTTLE_ERROR(SessId, "Handshake response from Provider ~ts decoding error: ~p", [ provider_logic:to_printable(ProviderId), Error ]), {error, handshake_failed} end. @private -spec handle_message(state(), binary()) -> {ok, state()} | error(). handle_message(#state{type = incoming} = State, Data) -> handle_client_message(State, Data); handle_message(#state{type = outgoing} = State, Data) -> handle_server_message(State, Data). @private -spec handle_client_message(state(), binary()) -> {ok, state()} | error(). handle_client_message(State, ?CLIENT_KEEPALIVE_MSG) -> {ok, State}; handle_client_message(#state{ peer_id = PeerId, peer_ip = PeerIp, session_id = SessId } = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_client_message(Data, SessId), case connection_utils:maybe_create_proxied_session(PeerId, PeerIp, Msg) of ok -> route_message(State, Msg); Error -> ?THROTTLE_ERROR(SessId, "Failed to create proxied session for ~p due to: ~p", [ clproto_utils:msg_to_string(Msg), Error ]), % Respond with eacces error if request has msg_id % (msg_id means that peer awaits answer) case Msg#client_message.message_id of undefined -> {ok, State}; _ -> AccessErrorMsg = #server_message{ message_id = Msg#client_message.message_id, message_body = #status{code = ?EACCES} }, send_response(State, AccessErrorMsg) end end catch throw:{translation_failed, Reason, undefined} -> ?THROTTLE_ERROR(SessId, "Client message decoding error - ~p", [Reason]), {ok, State}; throw:{translation_failed, Reason, MsgId} -> ?THROTTLE_ERROR(SessId, "Client message decoding error - ~p", [Reason]), InvalidArgErrorMsg = #server_message{ message_id = MsgId, message_body = #status{code = ?EINVAL} }, send_response(State, InvalidArgErrorMsg); Type:Reason -> ?THROTTLE_ERROR(SessId, "Client message handling error - ~p:~p", [Type, Reason]), {ok, State} end. @private -spec handle_server_message(state(), binary()) -> {ok, state()} | error(). handle_server_message(#state{session_id = SessId} = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_server_message(Data, SessId), route_message(State, Msg) catch Type:Error -> ?THROTTLE_ERROR(SessId, "Server message handling error - ~p:~p", [Type, Error]), {ok, State} end. @private -spec route_message(state(), communicator:message()) -> {ok, state()} | error(). route_message(#state{session_id = SessId, rib = RIB} = State, Msg) -> case router:route_message(Msg, RIB) of ok -> {ok, State}; {ok, ServerMsg} -> send_response(State, ServerMsg); {error, Reason} -> ?THROTTLE_ERROR(SessId, "Message ~s handling error: ~p", [ clproto_utils:msg_to_string(Msg), Reason ]), {ok, State} end. @private -spec send_response(state(), communicator:server_message()) -> {ok, state()} | error(). send_response(#state{session_id = SessId} = State, ServerMsg) -> case send_server_message(State, ServerMsg) of {ok, _NewState} = Ans -> Ans; % Serialization errors should not break ready connection {error, serialization_failed} -> {ok, State}; Error -> % Remove this connection from the connections pool and try to send % msg via other connections of this session. % Removal from pool is necessary to avoid deadlock when some other connection terminates as well and tries to send msg via this one % while this one tries to send via the other one. session_connections:deregister(SessId, self()), connection_api:send(SessId, ServerMsg, [self()], true), Error end. @private -spec send_message(state(), communicator:message()) -> {ok, state()} | error(). send_message(#state{type = outgoing} = State, #client_message{} = Msg) -> send_client_message(State, Msg); send_message(#state{type = incoming} = State, #server_message{} = Msg) -> send_server_message(State, Msg); send_message(#state{type = ConnType}, Msg) -> ?warning("Attempt to send msg ~s via wrong connection ~p", [ clproto_utils:msg_to_string(Msg), ConnType ]), {error, sending_msg_via_wrong_conn_type}. @private -spec send_client_message(state(), communicator:client_message()) -> {ok, state()} | error(). send_client_message(#state{ session_id = SessId, verify_msg = VerifyMsg } = State, ClientMsg) -> try {ok, Data} = clproto_serializer:serialize_client_message( ClientMsg, VerifyMsg ), socket_send(State, Data) catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unable to serialize client_message ~s", [clproto_utils:msg_to_string(ClientMsg)], Class, Reason, Stacktrace ), {error, serialization_failed} end. @private -spec send_server_message(state(), communicator:server_message()) -> {ok, state()} | error(). send_server_message(#state{ session_id = SessId, verify_msg = VerifyMsg } = State, ServerMsg) -> try {ok, Data} = clproto_serializer:serialize_server_message( ServerMsg, VerifyMsg ), socket_send(State, Data) catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unable to serialize server_message ~s", [clproto_utils:msg_to_string(ServerMsg)], Class, Reason, Stacktrace ), {error, serialization_failed} end. @private -spec socket_send(state(), Data :: binary()) -> {ok, state()} | error(). socket_send(#state{ session_id = SessId, transport = Transport, socket = Socket } = State, Data) -> case Transport:send(Socket, Data) of ok -> {ok, State}; {error, Reason} = Error -> ?THROTTLE_ERROR(SessId, "Unable to send message via socket ~p due to: ~p", [ Socket, Reason ]), Error end. %%-------------------------------------------------------------------- @private %% @doc %% If socket_mode is set to active_always then set it as such only during %% first activation and do nothing for latter ones. It will cause every message received on socket to be send to connection process as erlang message . %% Otherwise (active_once) activates socket so that only next received packet will be send to process as erlang message . %% @end %%-------------------------------------------------------------------- -spec activate_socket(state(), IsFirstActivation :: boolean()) -> ok. activate_socket(#state{ socket_mode = active_always, transport = Transport, socket = Socket }, true) -> ok = Transport:setopts(Socket, [{active, true}]); activate_socket(#state{socket_mode = active_always}, false) -> ok; activate_socket(#state{transport = Transport, socket = Socket}, _) -> ok = Transport:setopts(Socket, [{active, once}]). @private -spec call_connection_process(ConnPid :: pid(), term()) -> ok | error(). call_connection_process(ConnPid, Msg) -> try gen_server2:call(ConnPid, Msg, ?DEFAULT_REQUEST_TIMEOUT) catch exit:{noproc, _} -> ?debug("Connection process ~p does not exist", [ConnPid]), {error, no_connection}; exit:{{nodedown, Node}, _} -> ?debug("Node ~p with connection process ~p is down", [Node, ConnPid]), {error, no_connection}; exit:{normal, _} -> ?debug("Exit of connection process ~p for message ~s", [ ConnPid, maybe_stringify_msg(Msg) ]), {error, no_connection}; exit:{timeout, _} -> ?debug("Timeout of connection process ~p for message ~s", [ ConnPid, maybe_stringify_msg(Msg) ]), ?ERROR_TIMEOUT; Type:Reason -> ?error("Connection ~p cannot send msg ~s due to ~p:~p", [ ConnPid, maybe_stringify_msg(Msg), Type, Reason ]), {error, Reason} end. @private -spec maybe_stringify_msg(term()) -> term() | string(). maybe_stringify_msg({send_msg, Msg}) -> clproto_utils:msg_to_string(Msg); maybe_stringify_msg(Msg) -> Msg.
null
https://raw.githubusercontent.com/onedata/op-worker/a1970e588b702b959c379e21d89139445a56235c/src/modules/communication/connection/connection.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc This module handles communication using clproto binary protocol. - incoming - when it is initiated in response to peer (provider or client) request. It awaits client_messages, handles them and responds with server_messages, - outgoing - when this provider initiates it in order to connect to peer. ?CLIENT_PROTOCOL_PATH is send to other provider. If confirmation response is received, meaning that protocol using binary protocol can start. This type of connection can send only client_messages and receive server_messages. Beside type, connection has also one of the following statuses: - upgrading_protocol - valid only for outgoing connection. This status indicates that protocol upgrade request has been sent and response is awaited, - performing_handshake - indicates that connection either awaits authentication request (incoming connection) or response (outgoing connection), - ready - indicates that connection is in operational mode, so that it can send and receive messages. More detailed transitions between statuses for each connection type and message flow is depicted on diagram below. INCOMING | OUTGOING | | Provider B | | | | | v HTTP listener <------ upgrade ------ | init | | request +------------+ | | | | | | v | v | init | -------- upgrade ------> | upgrading_protocol | +----------+ response +--------------------+ | | | | | | | | v | | | | | | | | | | v | +--------- response ------> | performing_handshake | | | +----------------------+ | | | | | | v | v +-------+ <-------- n: client_message --------- +-------+ | ready | | | ready | +-------+ -------- n+1: server_message -------> +-------+ | In case of errors during init, upgrading_protocol or performing_handshake connection is immediately terminated. On the other hand, when connection is in ready status, every kind of error is logged, but only socket errors terminates it. @end ------------------------------------------------------------------- transport messages connection state routing information base - structure necessary for routing. reads N bytes to get length of your data, allocates a buffer to hold it and reads data into buffer after getting each tcp packet. API Private API cowboy_sub_protocol callbacks gen_server callbacks =================================================================== API =================================================================== -------------------------------------------------------------------- @doc @equiv start_link(ProviderId, SessId, Domain, Host, Port, ranch_ssl, timer:seconds(5)). @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Starts an outgoing connection to peer provider. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Sends msg for specified connection to shutdown itself. @end -------------------------------------------------------------------- ------------------------------------------------------------------- @doc Tries to send a message and provides feedback about success or eventual errors while serializing/sending. @end ------------------------------------------------------------------- ------------------------------------------------------------------- @doc Schedules keepalive message to be sent. @end ------------------------------------------------------------------- ------------------------------------------------------------------- @doc Informs connection process that it should rebuild it's rib as it may be obsolete (e.g. after node death). @end ------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc This function is never called. We only define it so that we can use the -behaviour(gen_server) attribute. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handles call messages. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handles cast messages. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handles all non call/cast messages. @end -------------------------------------------------------------------- Concrete errors were already logged in 'handle_protocol_upgrade_response' so terminate gracefully as to not spam more error logs outgoing session id is set when starting connection while incoming only after successful handshake Concrete errors were already logged in 'handle_handshake' so terminate gracefully as to not spam more error logs Concrete errors were already logged in 'handle_message' so terminate gracefully as to not spam more error logs -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Converts process state when code is changed. @end -------------------------------------------------------------------- ==================================================================== cowboy_sub_protocol callbacks ==================================================================== -------------------------------------------------------------------- @doc Called by cowboy on receiving request on ?CLIENT_PROTOCOL_PATH path. Causes the upgrade callback to be called. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc if received request is proper upgrade request. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Called after successful upgrade. Takes over connection process and changes it to gen_server. @end -------------------------------------------------------------------- Remove connection from the overall connections count so it will not be included in limiting the number of e.g. REST connections. ====================================================================== Functions used when initialising outgoing connection to peer provider ====================================================================== -------------------------------------------------------------------- @doc Initializes an outgoing connection to peer provider. @end -------------------------------------------------------------------- =================================================================== =================================================================== -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- Respond with eacces error if request has msg_id (msg_id means that peer awaits answer) Serialization errors should not break ready connection Remove this connection from the connections pool and try to send msg via other connections of this session. Removal from pool is necessary to avoid deadlock when some other while this one tries to send via the other one. -------------------------------------------------------------------- @doc If socket_mode is set to active_always then set it as such only during first activation and do nothing for latter ones. It will cause every message Otherwise (active_once) activates socket so that only next received packet @end --------------------------------------------------------------------
@author ( C ) 2019 - 2020 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . Created connection can be one of the two possible types : In order to do so , first http protocol upgrade request on upgrade from http to clproto succeeded , then communication | 0 : start_link Provider A 1 : protocol + ------------+ 1.5 | 1.5 + ----------+ 2 : protocol + --------------------+ 2.5 | | | + ----------------------+ 3 : handshake | | | performing_handshake | < ------ request ---------+ | + ----------------------+ | 3.5 | | 4 : handshake + ----------------------+ 4.5 | 4.5 -module(connection). -author("Bartosz Walkowicz"). -behaviour(gen_server). -behaviour(cowboy_sub_protocol). -include("timeouts.hrl"). -include("http/gui_paths.hrl"). -include("http/rest.hrl"). -include("global_definitions.hrl"). -include("proto/common/handshake_messages.hrl"). -include("proto/oneclient/server_messages.hrl"). -include("proto/oneclient/client_messages.hrl"). -include("proto/oneclient/common_messages.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("middleware/middleware.hrl"). -include_lib("ctool/include/aai/aai.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("ctool/include/errors.hrl"). -include_lib("ctool/include/http/headers.hrl"). -record(state, { socket :: ssl:sslsocket(), socket_mode = active_once :: active_always | active_once, transport :: module(), ok :: atom(), closed :: atom(), error :: atom(), type :: incoming | outgoing, status :: upgrading_protocol | performing_handshake | ready, session_id = undefined :: undefined | session:id(), peer_id = undefined :: undefined | od_provider:id() | od_user:id(), peer_ip :: inet:ip4_address(), verify_msg = true :: boolean(), connection_manager = undefined :: undefined | pid(), rib :: router:rib() | undefined }). -type state() :: #state{}. -type error() :: {error, Reason :: term()}. Default value for { packet , N } socket option . When specified , erlang first Then it sends the buffer as one msg to your process . -define(PACKET_VALUE, 4). -define(DEFAULT_SOCKET_MODE, op_worker:get_env(default_socket_mode, active_once) ). -define(DEFAULT_VERIFY_MSG_FLAG, op_worker:get_env(verify_msg_before_encoding, true) ). -export([start_link/5, start_link/7, close/1]). -export([send_msg/2, send_keepalive/1]). -export([rebuild_rib/1]). -export([find_outgoing_session/1]). -export([connect_with_provider/8]). -export([init/2, upgrade/4, upgrade/5, takeover/7]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). -define(REBUILD_RIB_MSG, rebuild_rib). 5 minutes -define(THROTTLE_ERROR(__SESSION_ID, __FORMAT, __ARGS), begin ?debug(__FORMAT, __ARGS), utils:throttle({?MODULE, __SESSION_ID, ?LINE}, ?CONNECTION_AWAIT_LOG_INTERVAL, fun() -> ?error(__FORMAT, __ARGS) end) end ). -define(THROTTLE_ERROR_EXCEPTION(__SESSION_ID, __FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE), begin ?debug_exception(__FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE), utils:throttle({?MODULE, __SESSION_ID, ?LINE}, ?CONNECTION_AWAIT_LOG_INTERVAL, fun() -> ?error_exception(__FORMAT, __ARGS, __CLASS, __REASON, __STACKTRACE) end) end ). -spec start_link(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer()) -> {ok, pid()} | error(). start_link(ProviderId, SessId, Domain, Host, Port) -> start_link(ProviderId, SessId, Domain, Host, Port, ranch_ssl, timer:seconds(5) ). -spec start_link(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer()) -> {ok, pid()} | error(). start_link(ProviderId, SessId, Domain, Host, Port, Transport, Timeout) -> ConnManager = self(), proc_lib:start_link(?MODULE, connect_with_provider, [ ProviderId, SessId, Domain, Host, Port, Transport, Timeout, ConnManager ]). close(Pid) -> gen_server2:cast(Pid, disconnect). -spec send_msg(pid(), communicator:message()) -> ok | error(). send_msg(Pid, Msg) -> call_connection_process(Pid, {send_msg, Msg}). -spec send_keepalive(pid()) -> ok. send_keepalive(Pid) -> gen_server2:cast(Pid, send_keepalive). -spec rebuild_rib(pid()) -> ok | error(). rebuild_rib(Pid) -> call_connection_process(Pid, ?REBUILD_RIB_MSG). -spec find_outgoing_session(oneprovider:id()) -> {ok, session:id()} | error. find_outgoing_session(ProviderId) -> SessionId = session_utils:get_provider_session_id(outgoing, ProviderId), case session:exists(SessionId) of true -> {ok, SessionId}; false -> error end. @private -spec init([]) -> {ok, undefined}. init([]) -> {ok, undefined}. @private -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: state()) -> {reply, Reply :: term(), NewState :: state()} | {reply, Reply :: term(), NewState :: state(), timeout() | hibernate} | {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), Reply :: term(), NewState :: state()} | {stop, Reason :: term(), NewState :: state()}. handle_call({send_msg, Msg}, _From, #state{status = ready} = State) -> case send_message(State, Msg) of {ok, NewState} -> {reply, ok, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, serialization_failed} = SerializationError -> {reply, SerializationError, State, ?PROTO_CONNECTION_TIMEOUT}; {error, sending_msg_via_wrong_conn_type} = WrongConnError -> {reply, WrongConnError, State, ?PROTO_CONNECTION_TIMEOUT}; Error -> {stop, Error, Error, State} end; handle_call({send_msg, _Msg}, _From, #state{status = Status, socket = Socket} = State) -> ?warning("Attempt to send msg via not ready connection ~p", [Socket]), {reply, {error, Status}, State, ?PROTO_CONNECTION_TIMEOUT}; handle_call(?REBUILD_RIB_MSG, _From, #state{session_id = SessId} = State) -> {reply, ok, State#state{rib = router:build_rib(SessId)}, ?PROTO_CONNECTION_TIMEOUT}; handle_call(Request, _From, State) -> ?log_bad_request(Request), {reply, {error, wrong_request}, State, ?PROTO_CONNECTION_TIMEOUT}. @private -spec handle_cast(Request :: term(), State :: state()) -> {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. handle_cast(send_keepalive, State) -> case socket_send(State, ?CLIENT_KEEPALIVE_MSG) of {ok, NewState} -> {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; Error -> {stop, Error, State} end; handle_cast(disconnect, State) -> {stop, normal, State}; handle_cast(Request, State) -> ?log_bad_request(Request), {noreply, State, ?PROTO_CONNECTION_TIMEOUT}. @private -spec handle_info(Info :: timeout() | {Ok :: atom(), Socket :: ssl:sslsocket(), Data :: binary()} | term(), State :: state()) -> {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. handle_info({upgrade_protocol, Hostname}, State) -> UpgradeReq = connection_utils:protocol_upgrade_request(Hostname), case socket_send(State, UpgradeReq) of {ok, NewState} -> {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{ status = upgrading_protocol, session_id = SessId, socket = Socket, ok = Ok } = State) -> try handle_protocol_upgrade_response(State, Data) of {ok, State1} -> State2 = State1#state{status = performing_handshake}, activate_socket(State2, false), {noreply, State2, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> {stop, normal, State} catch throw:{error, _} = Error -> ?THROTTLE_ERROR(SessId, "Protocol upgrade failed due to ~p", [Error]), {stop, normal, State}; Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unexpected error during protocol upgrade", [], Class, Reason, Stacktrace ), {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{ status = performing_handshake, session_id = OutgoingSessIdOrUndefined, socket = Socket, ok = Ok } = State) -> try handle_handshake(State, Data) of {ok, #state{session_id = SessId} = State1} -> ok = session_connections:register(SessId, self()), State2 = State1#state{status = ready}, activate_socket(State2, false), {noreply, State2, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> {stop, normal, State} catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( OutgoingSessIdOrUndefined, "Unexpected error while performing handshake", [], Class, Reason, Stacktrace ), {stop, normal, State} end; handle_info({Ok, Socket, Data}, #state{status = ready, socket = Socket, ok = Ok} = State) -> case handle_message(State, Data) of {ok, NewState} -> activate_socket(NewState, false), {noreply, NewState, ?PROTO_CONNECTION_TIMEOUT}; {error, _Reason} -> {stop, normal, State} end; handle_info({Error, Socket, Reason}, State = #state{error = Error}) -> ?warning("Connection ~p error: ~p", [Socket, Reason]), {stop, Reason, State}; handle_info({Closed, _}, State = #state{closed = Closed}) -> {stop, normal, State}; handle_info(timeout, State = #state{socket = Socket}) -> ?warning("Connection ~p timeout", [Socket]), {stop, timeout, State}; handle_info(Info, State) -> ?log_bad_request(Info), {noreply, State, ?PROTO_CONNECTION_TIMEOUT}. @private with . The return value is ignored . -spec terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()), State :: state()) -> term(). terminate(Reason, #state{session_id = SessId, socket = Socket} = State) -> ?log_terminate(Reason, State), case SessId of undefined -> ok; _ -> session_connections:deregister(SessId, self()) end, ssl:close(Socket), State. @private -spec code_change(OldVsn :: term() | {down, term()}, State :: state(), Extra :: term()) -> {ok, NewState :: state()} | error(). code_change(_OldVsn, State, _Extra) -> {ok, State}. @private -spec init(cowboy_req:req(), any()) -> {?MODULE, cowboy_req:req(), any()}. init(Req, Opts) -> {?MODULE, Req, Opts}. @private Initiates protocol switch from http to ? CLIENT_PROTOCOL_UPGRADE_NAME Otherwise responds with either 426 or 400 . -spec upgrade(cowboy_req:req(), cowboy_middleware:env(), module(), any()) -> {ok, cowboy_req:req(), cowboy_middleware:env()} | {stop, cowboy_req:req()}. upgrade(Req, Env, Handler, HandlerState) -> upgrade(Req, Env, Handler, HandlerState, #{}). -spec upgrade(cowboy_req:req(), cowboy_middleware:env(), module(), any(), any()) -> {ok, cowboy_req:req(), cowboy_middleware:env()} | {stop, cowboy_req:req()}. upgrade(Req, Env, _Handler, HandlerOpts, _Opts) -> try connection_utils:process_protocol_upgrade_request(Req) of ok -> Headers = cowboy_req:response_headers(#{ ?HDR_CONNECTION => <<"Upgrade">>, ?HDR_UPGRADE => <<?CLIENT_PROTOCOL_UPGRADE_NAME>> }, Req), #{pid := Pid, streamid := StreamID} = Req, Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, HandlerOpts}}, {ok, Req, Env}; {error, upgrade_required} -> NewReq = cowboy_req:reply(?HTTP_426_UPGRADE_REQUIRED, #{ ?HDR_CONNECTION => <<"Upgrade">>, ?HDR_UPGRADE => <<?CLIENT_PROTOCOL_UPGRADE_NAME>> }, Req), {stop, NewReq} catch Type:Reason -> ?debug("Invalid protocol upgrade request - ~p:~p", [Type, Reason]), cowboy_req:reply(?HTTP_400_BAD_REQUEST, Req), {stop, Req} end. @private -spec takeover(pid(), ranch:ref(), ssl:sslsocket(), module(), any(), binary(), any()) -> no_return(). takeover(_Parent, Ref, Socket, Transport, _Opts, _Buffer, _HandlerState) -> ranch:remove_connection(Ref), {ok, {IpAddress, _Port}} = ssl:peername(Socket), {Ok, Closed, Error, _} = Transport:messages(), State = #state{ socket = Socket, socket_mode = ?DEFAULT_SOCKET_MODE, transport = Transport, ok = Ok, closed = Closed, error = Error, peer_ip = IpAddress, type = incoming, status = performing_handshake, verify_msg = ?DEFAULT_VERIFY_MSG_FLAG }, ok = Transport:setopts(Socket, [binary, {packet, ?PACKET_VALUE}]), activate_socket(State, true), gen_server2:enter_loop(?MODULE, [], State, ?PROTO_CONNECTION_TIMEOUT). -spec connect_with_provider(od_provider:id(), session:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer(), ConnManager :: pid() ) -> no_return(). connect_with_provider(ProviderId, SessId, Domain, Host, Port, Transport, Timeout, ConnManager ) -> DomainAndIpInfo = case Domain of Host -> str_utils:format("@ ~s:~b", [Host, Port]); _ -> str_utils:format("@ ~s:~b (~s)", [Host, Port, Domain]) end, ?debug("Connecting to provider ~ts ~s", [ provider_logic:to_printable(ProviderId), DomainAndIpInfo ]), try State = open_socket_to_provider( SessId, ProviderId, Domain, Host, Port, Transport, Timeout, ConnManager ), activate_socket(State, true), self() ! {upgrade_protocol, Host}, ok = proc_lib:init_ack({ok, self()}), process_flag(trap_exit, true), gen_server2:enter_loop(?MODULE, [], State, ?PROTO_CONNECTION_TIMEOUT) catch _:Reason -> exit(Reason) end. @private -spec open_socket_to_provider(session:id(), od_provider:id(), Domain :: binary(), Host :: binary(), Port :: non_neg_integer(), Transport :: atom(), Timeout :: non_neg_integer(), ConnManager :: pid() ) -> state() | no_return(). open_socket_to_provider(SessId, ProviderId, Domain, Host, Port, Transport, Timeout, ConnManager ) -> SslOpts = provider_logic:provider_connection_ssl_opts(Domain), ConnectOpts = secure_ssl_opts:expand(SslOpts), {ok, Socket} = Transport:connect( binary_to_list(Host), Port, ConnectOpts, Timeout ), {ok, {IpAddress, _Port}} = ssl:peername(Socket), {Ok, Closed, Error, _} = Transport:messages(), #state{ socket = Socket, socket_mode = ?DEFAULT_SOCKET_MODE, transport = Transport, ok = Ok, closed = Closed, error = Error, type = outgoing, status = upgrading_protocol, session_id = SessId, peer_id = ProviderId, peer_ip = IpAddress, verify_msg = ?DEFAULT_VERIFY_MSG_FLAG, connection_manager = ConnManager, rib = router:build_rib(SessId) }. Internal functions @private Verifies protocol upgrade response and sends handshake request . -spec handle_protocol_upgrade_response(state(), Data :: binary()) -> {ok, state()} | error(). handle_protocol_upgrade_response(#state{session_id = SessId} = State, Data) -> case connection_utils:verify_protocol_upgrade_response(Data) of false -> ?THROTTLE_ERROR(SessId, "Received invalid protocol upgrade response: ~p", [Data]), {error, invalid_protocol_upgrade_response}; true -> #state{ socket = Socket, transport = Transport, peer_id = ProviderId } = State, {ok, MsgId} = clproto_message_id:generate(self()), Token = ?check(provider_auth:acquire_identity_token_for_consumer( ?SUB(?ONEPROVIDER, ProviderId) )), ClientMsg = #client_message{ message_id = MsgId, message_body = #provider_handshake_request{ provider_id = oneprovider:get_id(), token = Token } }, ok = Transport:setopts(Socket, [binary, {packet, ?PACKET_VALUE}]), send_client_message(State, ClientMsg) end. @private -spec handle_handshake(state(), binary()) -> {ok, state()} | error(). handle_handshake(#state{type = incoming} = State, Data) -> handle_handshake_request(State, Data); handle_handshake(#state{type = outgoing} = State, Data) -> handle_handshake_response(State, Data). @private -spec handle_handshake_request(state(), binary()) -> {ok, state()} | error(). handle_handshake_request(#state{peer_ip = IpAddress} = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_client_message(Data, undefined), {PeerId, SessId} = connection_auth:handle_handshake( Msg#client_message.message_body, IpAddress ), NewState = State#state{ peer_id = PeerId, session_id = SessId, rib = router:build_rib(SessId) }, send_server_message(NewState, #server_message{ message_body = #handshake_response{status = 'OK'} }) catch Type:Reason -> ?debug("Invalid handshake request - ~p:~p", [Type, Reason]), ErrorMsg = connection_auth:get_handshake_error_msg(Reason), send_server_message(State, ErrorMsg), {error, handshake_failed} end. @private -spec handle_handshake_response(state(), binary()) -> {ok, state()} | error(). handle_handshake_response(#state{ session_id = SessId, peer_id = ProviderId, connection_manager = ConnManager } = State, Data) -> try clproto_serializer:deserialize_server_message(Data, SessId) of {ok, #server_message{message_body = #handshake_response{status = 'OK'}}} -> ?info("Successfully connected to provider ~ts", [ provider_logic:to_printable(ProviderId) ]), outgoing_connection_manager:report_successful_handshake(ConnManager), {ok, State}; {ok, #server_message{message_body = #handshake_response{status = Error}}} -> ?THROTTLE_ERROR( SessId, "Handshake refused by provider ~ts due to ~p, closing connection.", [provider_logic:to_printable(ProviderId), Error] ), {error, handshake_failed}; _ -> ?THROTTLE_ERROR( SessId, "Received invalid handshake response from provider ~ts, closing connection.", [provider_logic:to_printable(ProviderId)] ), {error, handshake_failed} catch _:Error -> ?THROTTLE_ERROR(SessId, "Handshake response from Provider ~ts decoding error: ~p", [ provider_logic:to_printable(ProviderId), Error ]), {error, handshake_failed} end. @private -spec handle_message(state(), binary()) -> {ok, state()} | error(). handle_message(#state{type = incoming} = State, Data) -> handle_client_message(State, Data); handle_message(#state{type = outgoing} = State, Data) -> handle_server_message(State, Data). @private -spec handle_client_message(state(), binary()) -> {ok, state()} | error(). handle_client_message(State, ?CLIENT_KEEPALIVE_MSG) -> {ok, State}; handle_client_message(#state{ peer_id = PeerId, peer_ip = PeerIp, session_id = SessId } = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_client_message(Data, SessId), case connection_utils:maybe_create_proxied_session(PeerId, PeerIp, Msg) of ok -> route_message(State, Msg); Error -> ?THROTTLE_ERROR(SessId, "Failed to create proxied session for ~p due to: ~p", [ clproto_utils:msg_to_string(Msg), Error ]), case Msg#client_message.message_id of undefined -> {ok, State}; _ -> AccessErrorMsg = #server_message{ message_id = Msg#client_message.message_id, message_body = #status{code = ?EACCES} }, send_response(State, AccessErrorMsg) end end catch throw:{translation_failed, Reason, undefined} -> ?THROTTLE_ERROR(SessId, "Client message decoding error - ~p", [Reason]), {ok, State}; throw:{translation_failed, Reason, MsgId} -> ?THROTTLE_ERROR(SessId, "Client message decoding error - ~p", [Reason]), InvalidArgErrorMsg = #server_message{ message_id = MsgId, message_body = #status{code = ?EINVAL} }, send_response(State, InvalidArgErrorMsg); Type:Reason -> ?THROTTLE_ERROR(SessId, "Client message handling error - ~p:~p", [Type, Reason]), {ok, State} end. @private -spec handle_server_message(state(), binary()) -> {ok, state()} | error(). handle_server_message(#state{session_id = SessId} = State, Data) -> try {ok, Msg} = clproto_serializer:deserialize_server_message(Data, SessId), route_message(State, Msg) catch Type:Error -> ?THROTTLE_ERROR(SessId, "Server message handling error - ~p:~p", [Type, Error]), {ok, State} end. @private -spec route_message(state(), communicator:message()) -> {ok, state()} | error(). route_message(#state{session_id = SessId, rib = RIB} = State, Msg) -> case router:route_message(Msg, RIB) of ok -> {ok, State}; {ok, ServerMsg} -> send_response(State, ServerMsg); {error, Reason} -> ?THROTTLE_ERROR(SessId, "Message ~s handling error: ~p", [ clproto_utils:msg_to_string(Msg), Reason ]), {ok, State} end. @private -spec send_response(state(), communicator:server_message()) -> {ok, state()} | error(). send_response(#state{session_id = SessId} = State, ServerMsg) -> case send_server_message(State, ServerMsg) of {ok, _NewState} = Ans -> Ans; {error, serialization_failed} -> {ok, State}; Error -> connection terminates as well and tries to send msg via this one session_connections:deregister(SessId, self()), connection_api:send(SessId, ServerMsg, [self()], true), Error end. @private -spec send_message(state(), communicator:message()) -> {ok, state()} | error(). send_message(#state{type = outgoing} = State, #client_message{} = Msg) -> send_client_message(State, Msg); send_message(#state{type = incoming} = State, #server_message{} = Msg) -> send_server_message(State, Msg); send_message(#state{type = ConnType}, Msg) -> ?warning("Attempt to send msg ~s via wrong connection ~p", [ clproto_utils:msg_to_string(Msg), ConnType ]), {error, sending_msg_via_wrong_conn_type}. @private -spec send_client_message(state(), communicator:client_message()) -> {ok, state()} | error(). send_client_message(#state{ session_id = SessId, verify_msg = VerifyMsg } = State, ClientMsg) -> try {ok, Data} = clproto_serializer:serialize_client_message( ClientMsg, VerifyMsg ), socket_send(State, Data) catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unable to serialize client_message ~s", [clproto_utils:msg_to_string(ClientMsg)], Class, Reason, Stacktrace ), {error, serialization_failed} end. @private -spec send_server_message(state(), communicator:server_message()) -> {ok, state()} | error(). send_server_message(#state{ session_id = SessId, verify_msg = VerifyMsg } = State, ServerMsg) -> try {ok, Data} = clproto_serializer:serialize_server_message( ServerMsg, VerifyMsg ), socket_send(State, Data) catch Class:Reason:Stacktrace -> ?THROTTLE_ERROR_EXCEPTION( SessId, "Unable to serialize server_message ~s", [clproto_utils:msg_to_string(ServerMsg)], Class, Reason, Stacktrace ), {error, serialization_failed} end. @private -spec socket_send(state(), Data :: binary()) -> {ok, state()} | error(). socket_send(#state{ session_id = SessId, transport = Transport, socket = Socket } = State, Data) -> case Transport:send(Socket, Data) of ok -> {ok, State}; {error, Reason} = Error -> ?THROTTLE_ERROR(SessId, "Unable to send message via socket ~p due to: ~p", [ Socket, Reason ]), Error end. @private received on socket to be send to connection process as erlang message . will be send to process as erlang message . -spec activate_socket(state(), IsFirstActivation :: boolean()) -> ok. activate_socket(#state{ socket_mode = active_always, transport = Transport, socket = Socket }, true) -> ok = Transport:setopts(Socket, [{active, true}]); activate_socket(#state{socket_mode = active_always}, false) -> ok; activate_socket(#state{transport = Transport, socket = Socket}, _) -> ok = Transport:setopts(Socket, [{active, once}]). @private -spec call_connection_process(ConnPid :: pid(), term()) -> ok | error(). call_connection_process(ConnPid, Msg) -> try gen_server2:call(ConnPid, Msg, ?DEFAULT_REQUEST_TIMEOUT) catch exit:{noproc, _} -> ?debug("Connection process ~p does not exist", [ConnPid]), {error, no_connection}; exit:{{nodedown, Node}, _} -> ?debug("Node ~p with connection process ~p is down", [Node, ConnPid]), {error, no_connection}; exit:{normal, _} -> ?debug("Exit of connection process ~p for message ~s", [ ConnPid, maybe_stringify_msg(Msg) ]), {error, no_connection}; exit:{timeout, _} -> ?debug("Timeout of connection process ~p for message ~s", [ ConnPid, maybe_stringify_msg(Msg) ]), ?ERROR_TIMEOUT; Type:Reason -> ?error("Connection ~p cannot send msg ~s due to ~p:~p", [ ConnPid, maybe_stringify_msg(Msg), Type, Reason ]), {error, Reason} end. @private -spec maybe_stringify_msg(term()) -> term() | string(). maybe_stringify_msg({send_msg, Msg}) -> clproto_utils:msg_to_string(Msg); maybe_stringify_msg(Msg) -> Msg.
905cf40084aac237a50535144bfb7a22a8e831d9437c949919ed1547bf5d59c8
acieroid/scala-am
super-list-merge-n.scm
(define (super-merge-n lsts n) (define (geef-n+rest lst n) (cond ((or (= 0 n) (null? lst)) (cons '() lst)) (else (let* ((res (geef-n+rest (cdr lst) (- n 1))) (first (car res)) (rest (cdr res))) (cons (cons (car lst) first) rest))))) (if (null? lsts) '() (let* ((g-n+rest (geef-n+rest (car lsts) n)) (first (car g-n+rest)) (rest (cdr g-n+rest))) (append first (super-merge-n (append (cdr lsts) (if (null? rest) rest (list rest))) n))))) (equal? (super-merge-n '((a b c d e f) (g h i j k) (l m n o p q) (r s t u v w)) 3) '(a b c g h i l m n r s t d e f j k o p q u v w))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/scp1/super-list-merge-n.scm
scheme
(define (super-merge-n lsts n) (define (geef-n+rest lst n) (cond ((or (= 0 n) (null? lst)) (cons '() lst)) (else (let* ((res (geef-n+rest (cdr lst) (- n 1))) (first (car res)) (rest (cdr res))) (cons (cons (car lst) first) rest))))) (if (null? lsts) '() (let* ((g-n+rest (geef-n+rest (car lsts) n)) (first (car g-n+rest)) (rest (cdr g-n+rest))) (append first (super-merge-n (append (cdr lsts) (if (null? rest) rest (list rest))) n))))) (equal? (super-merge-n '((a b c d e f) (g h i j k) (l m n o p q) (r s t u v w)) 3) '(a b c g h i l m n r s t d e f j k o p q u v w))
8099b63fa6108fe32ebf4b0a085ca669adb48805bd5984546f8bfecd5626819c
racket/db
dbsystem.rkt
#lang racket/base (require racket/class racket/match db/private/generic/interfaces db/private/generic/common db/private/generic/sql-data "../../util/private/geometry.rkt" (only-in "message.rkt" length-code->bytes field-dvec->typeid field-dvec->flags)) (provide dbsystem classify-my-sql) (define mysql-dbsystem% (class* dbsystem-base% (dbsystem<%>) (define/public (get-short-name) 'mysql) (define/override (get-type-list) type-list) (define/public (has-support? option) (case option ((real-infinities) #f) ((numeric-infinities) #f) (else #f))) (define/public (get-parameter-handlers param-typeids) All params sent as binary data , so handled in message.rkt ;; Just need to check params for legal values here ;; FIXME: for now, only possible param type is var-string; ;; when that changes, will need to refine check-param. (map (lambda (param-typid) check-param) param-typeids)) (define/public (field-dvecs->typeids dvecs) (map field-dvec->typeid dvecs)) (define/public (describe-params typeids) (for/list ([_typeid (in-list typeids)]) '(#t any #f))) (define/public (describe-fields dvecs) (for/list ([dvec (in-list dvecs)]) (let ([r (describe-typeid (field-dvec->typeid dvec))]) (match r [(list supported? type typeid) (let* ([binary? (memq 'binary (field-dvec->flags dvec))] [type* (case type ((tinyblob) (if binary? type 'tinytext)) ((blob) (if binary? type 'text)) ((mediumblob) (if binary? type 'mediumtext)) ((longblob) (if binary? type 'longtext)) ((var-string) (if binary? 'var-binary type)) (else type))]) (if (eq? type* type) r (list supported? type* typeid)))])))) (super-new))) (define dbsystem (new mysql-dbsystem%)) ;; ======================================== (define DATE-YEAR-MIN 0) (define DATE-YEAR-MAX 9999) A CheckedParam is ( cons type - symbol bytes - or - value ) Three variants , depending on the stage of parameter processing : ;; - v1, after check-param: All variable-length values are converted ;; to bytes here, so that connection can decide what to send in long ;; data packets. ;; - v2, after by connection sends long data: Payloads already sent as long - data are replaced by # f. ;; check-param : Symbol Any -> CheckParam-v1 ;; Note: not applied to sql-null parameters. (define (check-param fsym param) (cond [(string? param) (cons 'var-string (string->bytes/utf-8 param))] [(bytes? param) (cons 'blob param)] [(int64? param) (cons 'longlong param)] [(rational? param) (cons 'double param)] [(or (sql-time? param) (sql-day-time-interval? param)) (cons 'time param)] [(sql-bits? param) (let-values ([(len bs start) (align-sql-bits param 'right)]) (cons 'bit (bytes-append (length-code->bytes (- (bytes-length bs) start)) bs)))] [(geometry2d? param) (cons 'geometry (geometry->bytes 'mysql-geometry->bytes param #:big-endian? #f #:srid? #t))] [(sql-date? param) (unless (<= DATE-YEAR-MIN (sql-date-year param) DATE-YEAR-MAX) (error/no-convert fsym "MySQL" "DATE" param "year out of range")) ;; Other ranges checked by sql-date contract at db/base.rkt (cons 'date param)] [(sql-timestamp? param) (unless (<= DATE-YEAR-MIN (sql-timestamp-year param) DATE-YEAR-MAX) (error/no-convert fsym "MySQL" "DATETIME" param "year out of range")) ;; See comment above for sql-date (cons 'timestamp param)] [else (error/no-convert fsym "MySQL" "parameter" param)])) ;; ======================================== ;; SQL "parsing" ;; We care about: ;; - determining whether commands must be prepared (to use binary data) ;; see -api-prepared-statements.html ;; - determining what statements are safe for the statement cache ;; - detecting commands that affect transaction status (maybe implicitly) ;; see -commit.html classify - my - sql : string [ nat ] - > (define classify-my-sql (make-sql-classifier #:hash-comments? #t '(;; Must be prepared ("SELECT" select) ("SHOW" show) ;; Do not invalidate statement cache ("INSERT" insert) ("DELETE" delete) ("UPDATE" update) ;; Explicit transaction commands ("ROLLBACK WORK TO" rollback-savepoint) ("ROLLBACK TO" rollback-savepoint) ("RELEASE SAVEPOINT" release-savepoint) ("SAVEPOINT" savepoint) ("START TRANSACTION" start) ("BEGIN" start) ("COMMIT" commit) ("ROLLBACK" rollback) ;; Note: after ROLLBACK TO, etc ("SET autocommit" set-autocommit) ;; trouble ;; Note: commit/rollback may immediately start new transaction ;; Implicit commit ("ALTER" implicit-commit) ("CREATE" implicit-commit) ("DROP" implicit-commit) ("RENAME" implicit-commit) ("TRUNCATE" implicit-commit) ("LOAD" implicit-commit) ("LOCK TABLES" implicit-commit) ("UNLOCK TABLES" implicit-commit)))) ;; ======================================== (define-type-table (type-list* typeid->type describe-typeid) (newdecimal decimal 0) (tiny tinyint 0) (short smallint 0) (int24 mediumint 0) (long integer 0) (longlong bigint 0) (float real 0) (double double 0) (newdate date 0) (time time 0) (datetime datetime 0) (varchar varchar 0) (string character 0) (var-string var-string 0) (tiny-blob tinyblob 0) (medium-blob mediumblob 0) (long-blob longblob 0) (blob blob 0) (bit bit 0) (geometry geometry 0)) (define type-list (append (map (lambda (t) (list t 0)) '(tinytext text mediumtext longtext var-binary)) type-list*)) ;; decimal, date typeids not used (?)
null
https://raw.githubusercontent.com/racket/db/0336d2522a613e76ebf60705cea3be4c237c447e/db-lib/db/private/mysql/dbsystem.rkt
racket
Just need to check params for legal values here FIXME: for now, only possible param type is var-string; when that changes, will need to refine check-param. ======================================== - v1, after check-param: All variable-length values are converted to bytes here, so that connection can decide what to send in long data packets. - v2, after by connection sends long data: Payloads already sent as check-param : Symbol Any -> CheckParam-v1 Note: not applied to sql-null parameters. Other ranges checked by sql-date contract at db/base.rkt See comment above for sql-date ======================================== SQL "parsing" We care about: - determining whether commands must be prepared (to use binary data) see -api-prepared-statements.html - determining what statements are safe for the statement cache - detecting commands that affect transaction status (maybe implicitly) see -commit.html Must be prepared Do not invalidate statement cache Explicit transaction commands Note: after ROLLBACK TO, etc trouble Note: commit/rollback may immediately start new transaction Implicit commit ======================================== decimal, date typeids not used (?)
#lang racket/base (require racket/class racket/match db/private/generic/interfaces db/private/generic/common db/private/generic/sql-data "../../util/private/geometry.rkt" (only-in "message.rkt" length-code->bytes field-dvec->typeid field-dvec->flags)) (provide dbsystem classify-my-sql) (define mysql-dbsystem% (class* dbsystem-base% (dbsystem<%>) (define/public (get-short-name) 'mysql) (define/override (get-type-list) type-list) (define/public (has-support? option) (case option ((real-infinities) #f) ((numeric-infinities) #f) (else #f))) (define/public (get-parameter-handlers param-typeids) All params sent as binary data , so handled in message.rkt (map (lambda (param-typid) check-param) param-typeids)) (define/public (field-dvecs->typeids dvecs) (map field-dvec->typeid dvecs)) (define/public (describe-params typeids) (for/list ([_typeid (in-list typeids)]) '(#t any #f))) (define/public (describe-fields dvecs) (for/list ([dvec (in-list dvecs)]) (let ([r (describe-typeid (field-dvec->typeid dvec))]) (match r [(list supported? type typeid) (let* ([binary? (memq 'binary (field-dvec->flags dvec))] [type* (case type ((tinyblob) (if binary? type 'tinytext)) ((blob) (if binary? type 'text)) ((mediumblob) (if binary? type 'mediumtext)) ((longblob) (if binary? type 'longtext)) ((var-string) (if binary? 'var-binary type)) (else type))]) (if (eq? type* type) r (list supported? type* typeid)))])))) (super-new))) (define dbsystem (new mysql-dbsystem%)) (define DATE-YEAR-MIN 0) (define DATE-YEAR-MAX 9999) A CheckedParam is ( cons type - symbol bytes - or - value ) Three variants , depending on the stage of parameter processing : long - data are replaced by # f. (define (check-param fsym param) (cond [(string? param) (cons 'var-string (string->bytes/utf-8 param))] [(bytes? param) (cons 'blob param)] [(int64? param) (cons 'longlong param)] [(rational? param) (cons 'double param)] [(or (sql-time? param) (sql-day-time-interval? param)) (cons 'time param)] [(sql-bits? param) (let-values ([(len bs start) (align-sql-bits param 'right)]) (cons 'bit (bytes-append (length-code->bytes (- (bytes-length bs) start)) bs)))] [(geometry2d? param) (cons 'geometry (geometry->bytes 'mysql-geometry->bytes param #:big-endian? #f #:srid? #t))] [(sql-date? param) (unless (<= DATE-YEAR-MIN (sql-date-year param) DATE-YEAR-MAX) (error/no-convert fsym "MySQL" "DATE" param "year out of range")) (cons 'date param)] [(sql-timestamp? param) (unless (<= DATE-YEAR-MIN (sql-timestamp-year param) DATE-YEAR-MAX) (error/no-convert fsym "MySQL" "DATETIME" param "year out of range")) (cons 'timestamp param)] [else (error/no-convert fsym "MySQL" "parameter" param)])) classify - my - sql : string [ nat ] - > (define classify-my-sql (make-sql-classifier #:hash-comments? #t ("SELECT" select) ("SHOW" show) ("INSERT" insert) ("DELETE" delete) ("UPDATE" update) ("ROLLBACK WORK TO" rollback-savepoint) ("ROLLBACK TO" rollback-savepoint) ("RELEASE SAVEPOINT" release-savepoint) ("SAVEPOINT" savepoint) ("START TRANSACTION" start) ("BEGIN" start) ("COMMIT" commit) ("ALTER" implicit-commit) ("CREATE" implicit-commit) ("DROP" implicit-commit) ("RENAME" implicit-commit) ("TRUNCATE" implicit-commit) ("LOAD" implicit-commit) ("LOCK TABLES" implicit-commit) ("UNLOCK TABLES" implicit-commit)))) (define-type-table (type-list* typeid->type describe-typeid) (newdecimal decimal 0) (tiny tinyint 0) (short smallint 0) (int24 mediumint 0) (long integer 0) (longlong bigint 0) (float real 0) (double double 0) (newdate date 0) (time time 0) (datetime datetime 0) (varchar varchar 0) (string character 0) (var-string var-string 0) (tiny-blob tinyblob 0) (medium-blob mediumblob 0) (long-blob longblob 0) (blob blob 0) (bit bit 0) (geometry geometry 0)) (define type-list (append (map (lambda (t) (list t 0)) '(tinytext text mediumtext longtext var-binary)) type-list*))
4795aa7c5ddc28e8c719b9a4aabd3800d3bbf34857aa2a5bf260411ef1d5898d
nbloomf/webdriver-w3c
WebDriver.hs
| Module : Web . Api . WebDriver Description : A monad for expressing WebDriver interactions . Copyright : 2018 , Automattic , Inc. License : GPL-3 Maintainer : ( ) Stability : experimental Portability : POSIX Module : Web.Api.WebDriver Description : A monad for expressing WebDriver interactions. Copyright : 2018, Automattic, Inc. License : GPL-3 Maintainer : Nathan Bloomfield () Stability : experimental Portability : POSIX -} module Web.Api.WebDriver ( module Web.Api.WebDriver.Assert , module Web.Api.WebDriver.Classes , module Web.Api.WebDriver.Endpoints , module Web.Api.WebDriver.Helpers , module Web.Api.WebDriver.Monad , module Web.Api.WebDriver.Types , module Web.Api.WebDriver.Types.Keyboard , module Web.Api.WebDriver.Uri ) where import Web.Api.WebDriver.Assert import Web.Api.WebDriver.Classes import Web.Api.WebDriver.Endpoints import Web.Api.WebDriver.Helpers import Web.Api.WebDriver.Monad import Web.Api.WebDriver.Types import Web.Api.WebDriver.Types.Keyboard import Web.Api.WebDriver.Uri
null
https://raw.githubusercontent.com/nbloomf/webdriver-w3c/bfd974fde80847e77820db30ceeab4b6c50edaa5/src/Web/Api/WebDriver.hs
haskell
| Module : Web . Api . WebDriver Description : A monad for expressing WebDriver interactions . Copyright : 2018 , Automattic , Inc. License : GPL-3 Maintainer : ( ) Stability : experimental Portability : POSIX Module : Web.Api.WebDriver Description : A monad for expressing WebDriver interactions. Copyright : 2018, Automattic, Inc. License : GPL-3 Maintainer : Nathan Bloomfield () Stability : experimental Portability : POSIX -} module Web.Api.WebDriver ( module Web.Api.WebDriver.Assert , module Web.Api.WebDriver.Classes , module Web.Api.WebDriver.Endpoints , module Web.Api.WebDriver.Helpers , module Web.Api.WebDriver.Monad , module Web.Api.WebDriver.Types , module Web.Api.WebDriver.Types.Keyboard , module Web.Api.WebDriver.Uri ) where import Web.Api.WebDriver.Assert import Web.Api.WebDriver.Classes import Web.Api.WebDriver.Endpoints import Web.Api.WebDriver.Helpers import Web.Api.WebDriver.Monad import Web.Api.WebDriver.Types import Web.Api.WebDriver.Types.Keyboard import Web.Api.WebDriver.Uri
b7094f321fc6c06619bab458fa5ae638d6601e3819868dbae24337385af123ce
haskell/haskell-language-server
DestructSpec.hs
{-# LANGUAGE OverloadedStrings #-} module CodeAction.DestructSpec where import Wingman.Types import Test.Hspec import Utils spec :: Spec spec = do let destructTest = goldenTest Destruct describe "golden" $ do destructTest "gadt" 7 17 "GoldenGADTDestruct" destructTest "gadt" 8 17 "GoldenGADTDestructCoercion" destructTest "a" 7 25 "SplitPattern" destructTest "a" 6 18 "DestructPun" destructTest "fp" 31 14 "DestructCthulhu" destructTest "b" 7 10 "DestructTyFam" destructTest "b" 7 10 "DestructDataFam" destructTest "b" 17 10 "DestructTyToDataFam" destructTest "t" 6 10 "DestructInt" describe "layout" $ do destructTest "b" 4 3 "LayoutBind" destructTest "b" 2 15 "LayoutDollarApp" destructTest "b" 2 18 "LayoutOpApp" destructTest "b" 2 14 "LayoutLam" destructTest "x" 11 15 "LayoutSplitWhere" destructTest "x" 3 12 "LayoutSplitClass" destructTest "b" 3 9 "LayoutSplitGuard" destructTest "b" 4 13 "LayoutSplitLet" destructTest "a" 4 7 "LayoutSplitIn" destructTest "a" 4 31 "LayoutSplitViewPat" destructTest "a" 7 17 "LayoutSplitPattern" destructTest "a" 8 26 "LayoutSplitPatSyn" describe "providers" $ do mkTest "Produces destruct and homomorphism code actions" "T2" 2 21 [ (id, Destruct, "eab") , (id, Homomorphism, "eab") , (not, DestructPun, "eab") ] mkTest "Won't suggest homomorphism on the wrong type" "T2" 8 8 [ (not, Homomorphism, "global") ] mkTest "Produces (homomorphic) lambdacase code actions" "T3" 4 24 [ (id, HomomorphismLambdaCase, "") , (id, DestructLambdaCase, "") ] mkTest "Produces lambdacase code actions" "T3" 7 13 [ (id, DestructLambdaCase, "") ] mkTest "Doesn't suggest lambdacase without -XLambdaCase" "T2" 11 25 [ (not, DestructLambdaCase, "") ] mkTest "Doesn't suggest destruct if already destructed" "ProvideAlreadyDestructed" 6 18 [ (not, Destruct, "x") ] mkTest "...but does suggest destruct if destructed in a different branch" "ProvideAlreadyDestructed" 9 7 [ (id, Destruct, "x") ] mkTest "Doesn't suggest destruct on class methods" "ProvideLocalHyOnly" 2 12 [ (not, Destruct, "mempty") ] mkTest "Suggests homomorphism if the domain is bigger than the codomain" "ProviderHomomorphism" 12 13 [ (id, Homomorphism, "g") ] mkTest "Doesn't suggest homomorphism if the domain is smaller than the codomain" "ProviderHomomorphism" 15 14 [ (not, Homomorphism, "g") , (id, Destruct, "g") ] mkTest "Suggests lambda homomorphism if the domain is bigger than the codomain" "ProviderHomomorphism" 18 14 [ (id, HomomorphismLambdaCase, "") ] mkTest "Doesn't suggest lambda homomorphism if the domain is smaller than the codomain" "ProviderHomomorphism" 21 15 [ (not, HomomorphismLambdaCase, "") , (id, DestructLambdaCase, "") ] -- test layouts that maintain user-written fixities destructTest "b" 3 13 "LayoutInfixKeep" destructTest "b" 2 12 "LayoutPrefixKeep"
null
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/CodeAction/DestructSpec.hs
haskell
# LANGUAGE OverloadedStrings # test layouts that maintain user-written fixities
module CodeAction.DestructSpec where import Wingman.Types import Test.Hspec import Utils spec :: Spec spec = do let destructTest = goldenTest Destruct describe "golden" $ do destructTest "gadt" 7 17 "GoldenGADTDestruct" destructTest "gadt" 8 17 "GoldenGADTDestructCoercion" destructTest "a" 7 25 "SplitPattern" destructTest "a" 6 18 "DestructPun" destructTest "fp" 31 14 "DestructCthulhu" destructTest "b" 7 10 "DestructTyFam" destructTest "b" 7 10 "DestructDataFam" destructTest "b" 17 10 "DestructTyToDataFam" destructTest "t" 6 10 "DestructInt" describe "layout" $ do destructTest "b" 4 3 "LayoutBind" destructTest "b" 2 15 "LayoutDollarApp" destructTest "b" 2 18 "LayoutOpApp" destructTest "b" 2 14 "LayoutLam" destructTest "x" 11 15 "LayoutSplitWhere" destructTest "x" 3 12 "LayoutSplitClass" destructTest "b" 3 9 "LayoutSplitGuard" destructTest "b" 4 13 "LayoutSplitLet" destructTest "a" 4 7 "LayoutSplitIn" destructTest "a" 4 31 "LayoutSplitViewPat" destructTest "a" 7 17 "LayoutSplitPattern" destructTest "a" 8 26 "LayoutSplitPatSyn" describe "providers" $ do mkTest "Produces destruct and homomorphism code actions" "T2" 2 21 [ (id, Destruct, "eab") , (id, Homomorphism, "eab") , (not, DestructPun, "eab") ] mkTest "Won't suggest homomorphism on the wrong type" "T2" 8 8 [ (not, Homomorphism, "global") ] mkTest "Produces (homomorphic) lambdacase code actions" "T3" 4 24 [ (id, HomomorphismLambdaCase, "") , (id, DestructLambdaCase, "") ] mkTest "Produces lambdacase code actions" "T3" 7 13 [ (id, DestructLambdaCase, "") ] mkTest "Doesn't suggest lambdacase without -XLambdaCase" "T2" 11 25 [ (not, DestructLambdaCase, "") ] mkTest "Doesn't suggest destruct if already destructed" "ProvideAlreadyDestructed" 6 18 [ (not, Destruct, "x") ] mkTest "...but does suggest destruct if destructed in a different branch" "ProvideAlreadyDestructed" 9 7 [ (id, Destruct, "x") ] mkTest "Doesn't suggest destruct on class methods" "ProvideLocalHyOnly" 2 12 [ (not, Destruct, "mempty") ] mkTest "Suggests homomorphism if the domain is bigger than the codomain" "ProviderHomomorphism" 12 13 [ (id, Homomorphism, "g") ] mkTest "Doesn't suggest homomorphism if the domain is smaller than the codomain" "ProviderHomomorphism" 15 14 [ (not, Homomorphism, "g") , (id, Destruct, "g") ] mkTest "Suggests lambda homomorphism if the domain is bigger than the codomain" "ProviderHomomorphism" 18 14 [ (id, HomomorphismLambdaCase, "") ] mkTest "Doesn't suggest lambda homomorphism if the domain is smaller than the codomain" "ProviderHomomorphism" 21 15 [ (not, HomomorphismLambdaCase, "") , (id, DestructLambdaCase, "") ] destructTest "b" 3 13 "LayoutInfixKeep" destructTest "b" 2 12 "LayoutPrefixKeep"
95f2f2d670007d0efe783f8e795c66bd606ba34f8cf3338128e16e7f3ab70ebd
haskell-repa/repa
Target.hs
module Data.Repa.Array.Internals.Target ( Target (..), TargetI , empty, singleton , fromList, fromListInto , mapMaybeS, mapEitherS , generateMaybeS, generateEitherS , unfoldEitherOfLengthIO) where import Data.Repa.Array.Generic.Index as A import Data.Repa.Array.Internals.Bulk as A import System.IO.Unsafe import Control.Monad import qualified Data.Vector.Fusion.Stream.Monadic as S import Prelude hiding (length) import qualified Prelude as P #include "repa-array.h" Target --------------------------------------------------------------------- -- | Class of manifest array representations that can be constructed -- in a random-access manner. -- class Layout l => Target l a where -- | Mutable buffer for some array representation. data Buffer l a -- | Allocate a new mutable buffer for the given layout. -- -- UNSAFE: The integer must be positive, but this is not checked. unsafeNewBuffer :: l -> IO (Buffer l a) -- | Read an element from the mutable buffer. -- -- UNSAFE: The index bounds are not checked. unsafeReadBuffer :: Buffer l a -> Int -> IO a -- | Write an element into the mutable buffer. -- -- UNSAFE: The index bounds are not checked. unsafeWriteBuffer :: Buffer l a -> Int -> a -> IO () -- | O(n). Copy the contents of a buffer that is larger by the given -- number of elements. -- -- UNSAFE: The integer must be positive, but this is not checked. unsafeGrowBuffer :: Buffer l a -> Int -> IO (Buffer l a) -- | O(1). Yield a slice of the buffer without copying. -- -- UNSAFE: The given starting position and length must be within the bounds -- of the of the source buffer, but this is not checked. unsafeSliceBuffer :: Int -> Int -> Buffer l a -> IO (Buffer l a) | O(1 ) . Freeze a mutable buffer into an immutable array . -- -- UNSAFE: If the buffer is mutated further then the result of reading from -- the returned array will be non-deterministic. unsafeFreezeBuffer :: Buffer l a -> IO (Array l a) | O(1 ) . an Array into a mutable buffer . -- -- UNSAFE: The Array is no longer safe to use. unsafeThawBuffer :: Array l a -> IO (Buffer l a) -- | Ensure the array is still live at this point. -- Sometimes needed when the mutable buffer is a ForeignPtr with a finalizer. touchBuffer :: Buffer l a -> IO () -- | O(1). Get the layout from a Buffer. bufferLayout :: Buffer l a -> l -- | Constraint synonym that requires an integer index space. type TargetI l a = (Target l a, Index l ~ Int) ------------------------------------------------------------------------------- -- | O(1). An empty array of the given layout. empty :: TargetI l a => Name l -> Array l a empty nDst = unsafePerformIO $ do let lDst = create nDst 0 buf <- unsafeNewBuffer lDst unsafeFreezeBuffer buf # INLINE_ARRAY empty # -- | O(1). Create a new empty array containing a single element. singleton :: TargetI l a => Name l -> a -> Array l a singleton nDst x = unsafePerformIO $ do let lDst = create nDst 1 buf <- unsafeNewBuffer lDst unsafeWriteBuffer buf 0 x unsafeFreezeBuffer buf # INLINE_ARRAY singleton # -- | O(length src). Construct a linear array from a list of elements. fromList :: TargetI l a => Name l -> [a] -> Array l a fromList nDst xx = let len = P.length xx lDst = create nDst len Just arr = fromListInto lDst xx in arr # NOINLINE fromList # -- | O(length src). Construct an array from a list of elements, -- and give it the provided layout. -- -- The `length` of the provided shape must match the length of the list, -- else `Nothing`. -- fromListInto :: Target l a => l -> [a] -> Maybe (Array l a) fromListInto lDst xx = unsafePerformIO $ do let !len = P.length xx if len /= size (extent lDst) then return Nothing else do !buf <- unsafeNewBuffer lDst zipWithM_ (unsafeWriteBuffer buf) [0..] xx arr <- unsafeFreezeBuffer buf return $ Just arr # NOINLINE fromListInto # ------------------------------------------------------------------------------- -- | Apply a function to every element of an array, -- if any application returns `Nothing`, then `Nothing` for the whole result. mapMaybeS :: (BulkI lSrc a, TargetI lDst b) => Name lDst -> (a -> Maybe b) -> Array lSrc a -> Maybe (Array lDst b) mapMaybeS !nDst f arr = generateMaybeS nDst (length arr) get_maybeS where get_maybeS ix = f (index arr ix) {-# INLINE get_maybeS #-} # INLINE_ARRAY mapMaybeS # -- | Apply a function to every element of an array, -- if any application returns `Left`, then `Left` for the whole result. mapEitherS :: (BulkI lSrc a, TargetI lDst b) => Name lDst -> (a -> Either err b) -> Array lSrc a -> Either err (Array lDst b) mapEitherS !nDst f arr = generateEitherS nDst (length arr) get_eitherS where get_eitherS ix = f (index arr ix) # INLINE get_eitherS # {-# INLINE_ARRAY mapEitherS #-} ------------------------------------------------------------------------------- -- | Generate an array of the given length by applying a function to -- every index, sequentially. If any element returns `Nothing`, -- then `Nothing` for the whole array. generateMaybeS :: TargetI l a => Name l -> Int -> (Int -> Maybe a) -> Maybe (Array l a) generateMaybeS !nDst !len get = unsafePerformIO $ do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_generateMaybeS !ix | ix >= len = return ix | otherwise = case get ix of Nothing -> return ix Just x -> do unsafeWriteBuffer buf ix $! x fill_generateMaybeS (ix + 1) # INLINE fill_generateMaybeS # !pos <- fill_generateMaybeS 0 if pos < len then return Nothing else fmap Just $! unsafeFreezeBuffer buf {-# INLINE_ARRAY generateMaybeS #-} -- | Generate an array of the given length by applying a function to -- every index, sequentially. If any element returns `Left`, -- then `Left` for the whole array. generateEitherS :: TargetI l a => Name l -> Int -> (Int -> Either err a) -> Either err (Array l a) generateEitherS !nDst !len get = unsafePerformIO $ do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_generateEitherS !ix | ix >= len = return Nothing | otherwise = case get ix of Left err -> return $ Just err Right x -> do unsafeWriteBuffer buf ix $! x fill_generateEitherS (ix + 1) # INLINE fill_generateEitherS # !mErr <- fill_generateEitherS 0 case mErr of Just err -> return $ Left err Nothing -> fmap Right $! unsafeFreezeBuffer buf {-# INLINE_ARRAY generateEitherS #-} --------------------------------------------------------------------------------------------------- -- | Unfold a new array using the given length and worker function. -- -- This is like `generateEither`, except that an accumulator is -- threaded sequentially through the elements. -- unfoldEitherOfLengthIO :: TargetI l a => Name l -- ^ Destination format. -> Int -- ^ Length of array. -> (Int -> acc -> IO (Either err (acc, a))) -- ^ Worker function. -> acc -- ^ Starting accumluator -> IO (Either err (acc, Array l a)) unfoldEitherOfLengthIO nDst len get acc0 = do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_unfoldEither !sPEC !acc !ix | ix >= len = return $ Right acc | otherwise = get ix acc >>= \r -> case r of Left err -> return $ Left err Right (acc', x) -> do unsafeWriteBuffer buf ix $! x fill_unfoldEither sPEC acc' (ix + 1) {-# INLINE_INNER fill_unfoldEither #-} eErr <- fill_unfoldEither S.SPEC acc0 0 case eErr of Left err -> return $ Left err Right acc -> do arr <- unsafeFreezeBuffer buf return $ Right (acc, arr) # INLINE_ARRAY unfoldEitherOfLengthIO #
null
https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-array/Data/Repa/Array/Internals/Target.hs
haskell
------------------------------------------------------------------- | Class of manifest array representations that can be constructed in a random-access manner. | Mutable buffer for some array representation. | Allocate a new mutable buffer for the given layout. UNSAFE: The integer must be positive, but this is not checked. | Read an element from the mutable buffer. UNSAFE: The index bounds are not checked. | Write an element into the mutable buffer. UNSAFE: The index bounds are not checked. | O(n). Copy the contents of a buffer that is larger by the given number of elements. UNSAFE: The integer must be positive, but this is not checked. | O(1). Yield a slice of the buffer without copying. UNSAFE: The given starting position and length must be within the bounds of the of the source buffer, but this is not checked. UNSAFE: If the buffer is mutated further then the result of reading from the returned array will be non-deterministic. UNSAFE: The Array is no longer safe to use. | Ensure the array is still live at this point. Sometimes needed when the mutable buffer is a ForeignPtr with a finalizer. | O(1). Get the layout from a Buffer. | Constraint synonym that requires an integer index space. ----------------------------------------------------------------------------- | O(1). An empty array of the given layout. | O(1). Create a new empty array containing a single element. | O(length src). Construct a linear array from a list of elements. | O(length src). Construct an array from a list of elements, and give it the provided layout. The `length` of the provided shape must match the length of the list, else `Nothing`. ----------------------------------------------------------------------------- | Apply a function to every element of an array, if any application returns `Nothing`, then `Nothing` for the whole result. # INLINE get_maybeS # | Apply a function to every element of an array, if any application returns `Left`, then `Left` for the whole result. # INLINE_ARRAY mapEitherS # ----------------------------------------------------------------------------- | Generate an array of the given length by applying a function to every index, sequentially. If any element returns `Nothing`, then `Nothing` for the whole array. # INLINE_ARRAY generateMaybeS # | Generate an array of the given length by applying a function to every index, sequentially. If any element returns `Left`, then `Left` for the whole array. # INLINE_ARRAY generateEitherS # ------------------------------------------------------------------------------------------------- | Unfold a new array using the given length and worker function. This is like `generateEither`, except that an accumulator is threaded sequentially through the elements. ^ Destination format. ^ Length of array. ^ Worker function. ^ Starting accumluator # INLINE_INNER fill_unfoldEither #
module Data.Repa.Array.Internals.Target ( Target (..), TargetI , empty, singleton , fromList, fromListInto , mapMaybeS, mapEitherS , generateMaybeS, generateEitherS , unfoldEitherOfLengthIO) where import Data.Repa.Array.Generic.Index as A import Data.Repa.Array.Internals.Bulk as A import System.IO.Unsafe import Control.Monad import qualified Data.Vector.Fusion.Stream.Monadic as S import Prelude hiding (length) import qualified Prelude as P #include "repa-array.h" class Layout l => Target l a where data Buffer l a unsafeNewBuffer :: l -> IO (Buffer l a) unsafeReadBuffer :: Buffer l a -> Int -> IO a unsafeWriteBuffer :: Buffer l a -> Int -> a -> IO () unsafeGrowBuffer :: Buffer l a -> Int -> IO (Buffer l a) unsafeSliceBuffer :: Int -> Int -> Buffer l a -> IO (Buffer l a) | O(1 ) . Freeze a mutable buffer into an immutable array . unsafeFreezeBuffer :: Buffer l a -> IO (Array l a) | O(1 ) . an Array into a mutable buffer . unsafeThawBuffer :: Array l a -> IO (Buffer l a) touchBuffer :: Buffer l a -> IO () bufferLayout :: Buffer l a -> l type TargetI l a = (Target l a, Index l ~ Int) empty :: TargetI l a => Name l -> Array l a empty nDst = unsafePerformIO $ do let lDst = create nDst 0 buf <- unsafeNewBuffer lDst unsafeFreezeBuffer buf # INLINE_ARRAY empty # singleton :: TargetI l a => Name l -> a -> Array l a singleton nDst x = unsafePerformIO $ do let lDst = create nDst 1 buf <- unsafeNewBuffer lDst unsafeWriteBuffer buf 0 x unsafeFreezeBuffer buf # INLINE_ARRAY singleton # fromList :: TargetI l a => Name l -> [a] -> Array l a fromList nDst xx = let len = P.length xx lDst = create nDst len Just arr = fromListInto lDst xx in arr # NOINLINE fromList # fromListInto :: Target l a => l -> [a] -> Maybe (Array l a) fromListInto lDst xx = unsafePerformIO $ do let !len = P.length xx if len /= size (extent lDst) then return Nothing else do !buf <- unsafeNewBuffer lDst zipWithM_ (unsafeWriteBuffer buf) [0..] xx arr <- unsafeFreezeBuffer buf return $ Just arr # NOINLINE fromListInto # mapMaybeS :: (BulkI lSrc a, TargetI lDst b) => Name lDst -> (a -> Maybe b) -> Array lSrc a -> Maybe (Array lDst b) mapMaybeS !nDst f arr = generateMaybeS nDst (length arr) get_maybeS where get_maybeS ix = f (index arr ix) # INLINE_ARRAY mapMaybeS # mapEitherS :: (BulkI lSrc a, TargetI lDst b) => Name lDst -> (a -> Either err b) -> Array lSrc a -> Either err (Array lDst b) mapEitherS !nDst f arr = generateEitherS nDst (length arr) get_eitherS where get_eitherS ix = f (index arr ix) # INLINE get_eitherS # generateMaybeS :: TargetI l a => Name l -> Int -> (Int -> Maybe a) -> Maybe (Array l a) generateMaybeS !nDst !len get = unsafePerformIO $ do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_generateMaybeS !ix | ix >= len = return ix | otherwise = case get ix of Nothing -> return ix Just x -> do unsafeWriteBuffer buf ix $! x fill_generateMaybeS (ix + 1) # INLINE fill_generateMaybeS # !pos <- fill_generateMaybeS 0 if pos < len then return Nothing else fmap Just $! unsafeFreezeBuffer buf generateEitherS :: TargetI l a => Name l -> Int -> (Int -> Either err a) -> Either err (Array l a) generateEitherS !nDst !len get = unsafePerformIO $ do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_generateEitherS !ix | ix >= len = return Nothing | otherwise = case get ix of Left err -> return $ Just err Right x -> do unsafeWriteBuffer buf ix $! x fill_generateEitherS (ix + 1) # INLINE fill_generateEitherS # !mErr <- fill_generateEitherS 0 case mErr of Just err -> return $ Left err Nothing -> fmap Right $! unsafeFreezeBuffer buf unfoldEitherOfLengthIO :: TargetI l a -> IO (Either err (acc, Array l a)) unfoldEitherOfLengthIO nDst len get acc0 = do let lDst = create nDst len !buf <- unsafeNewBuffer lDst let fill_unfoldEither !sPEC !acc !ix | ix >= len = return $ Right acc | otherwise = get ix acc >>= \r -> case r of Left err -> return $ Left err Right (acc', x) -> do unsafeWriteBuffer buf ix $! x fill_unfoldEither sPEC acc' (ix + 1) eErr <- fill_unfoldEither S.SPEC acc0 0 case eErr of Left err -> return $ Left err Right acc -> do arr <- unsafeFreezeBuffer buf return $ Right (acc, arr) # INLINE_ARRAY unfoldEitherOfLengthIO #
17de33b49ff00ee14bc1e56b8a624ed10b6628e7cf9bf71d82841ee722aaf186
russolsen/cloforth
compiler.clj
(ns cloforth.test.compiler (:use [cloforth.compiler :as c]) (:use [cloforth.execute :as x]) (:use [clojure.test]) (:require [cloforth.environment :as env])) (def starting-env (assoc (env/make-env) :counter 0)) (defn inc-counter [env] (update-in env [:counter] inc)) (defn dec-counter [env] (update-in env [:counter] dec)) (deftest execute-one-function (let [env (last (x/execute-program starting-env inc-counter))] (is (map? env)) (is (= 1 (:counter env))))) (deftest execute-one-single-element-vector (let [env (last (x/execute-program starting-env [inc-counter]))] (is (map? env)) (is (= 1 (:counter env))))) (deftest execute-one-two-element-vector (let [env (last (x/execute-program starting-env [inc-counter inc-counter]))] (is (map? env)) (is (= 2 (:counter env)))))
null
https://raw.githubusercontent.com/russolsen/cloforth/226c5f7a648f0923e321bc858518a687e0496cf4/test/cloforth/test/compiler.clj
clojure
(ns cloforth.test.compiler (:use [cloforth.compiler :as c]) (:use [cloforth.execute :as x]) (:use [clojure.test]) (:require [cloforth.environment :as env])) (def starting-env (assoc (env/make-env) :counter 0)) (defn inc-counter [env] (update-in env [:counter] inc)) (defn dec-counter [env] (update-in env [:counter] dec)) (deftest execute-one-function (let [env (last (x/execute-program starting-env inc-counter))] (is (map? env)) (is (= 1 (:counter env))))) (deftest execute-one-single-element-vector (let [env (last (x/execute-program starting-env [inc-counter]))] (is (map? env)) (is (= 1 (:counter env))))) (deftest execute-one-two-element-vector (let [env (last (x/execute-program starting-env [inc-counter inc-counter]))] (is (map? env)) (is (= 2 (:counter env)))))
fb198580a9d1a81b532ef14c1fbef485c471828fb359bd32c1de95809c4912ea
travitch/llvm-analysis
PointsTo.hs
-- | This module defines the interface to points-to analysis in this -- analysis framework. Each points-to analysis returns a result -- object that is an instance of the 'PointsToAnalysis' typeclass; the -- results are intended to be consumed through this interface. -- -- All of the points-to analysis implementations expose a single function: -- -- > runPointsToAnalysis :: (PointsToAnalysis a) => Module -> a -- -- This makes it easy to change the points-to analysis you are using: -- just modify your imports. If you need multiple points-to analyses -- in the same module (for example, to support command-line selectable -- points-to analysis precision), use qualified imports. module LLVM.Analysis.PointsTo ( -- * Classes PointsToAnalysis(..), ) where import LLVM.Analysis -- | The interface to any points-to analysis. class PointsToAnalysis a where mayAlias :: a -> Value -> Value -> Bool ^ Check whether or not two values may alias pointsTo :: a -> Value -> [Value] ^ Return the list of values that a LoadInst may return . May -- return targets for other values too (e.g., say that a Function -- points to itself), but nothing is guaranteed. -- -- Should also give reasonable answers for globals and arguments resolveIndirectCall :: a -> Instruction -> [Value] -- ^ Given a Call instruction, determine its possible callees. The -- default implementation just delegates the called function value -- to 'pointsTo' and . resolveIndirectCall pta i = case i of CallInst { callFunction = f } -> pointsTo pta f InvokeInst { invokeFunction = f } -> pointsTo pta f _ -> []
null
https://raw.githubusercontent.com/travitch/llvm-analysis/090c3484650552e620d02c5ddc7885267e04ac62/src/LLVM/Analysis/PointsTo.hs
haskell
| This module defines the interface to points-to analysis in this analysis framework. Each points-to analysis returns a result object that is an instance of the 'PointsToAnalysis' typeclass; the results are intended to be consumed through this interface. All of the points-to analysis implementations expose a single function: > runPointsToAnalysis :: (PointsToAnalysis a) => Module -> a This makes it easy to change the points-to analysis you are using: just modify your imports. If you need multiple points-to analyses in the same module (for example, to support command-line selectable points-to analysis precision), use qualified imports. * Classes | The interface to any points-to analysis. return targets for other values too (e.g., say that a Function points to itself), but nothing is guaranteed. Should also give reasonable answers for globals and arguments ^ Given a Call instruction, determine its possible callees. The default implementation just delegates the called function value to 'pointsTo' and .
module LLVM.Analysis.PointsTo ( PointsToAnalysis(..), ) where import LLVM.Analysis class PointsToAnalysis a where mayAlias :: a -> Value -> Value -> Bool ^ Check whether or not two values may alias pointsTo :: a -> Value -> [Value] ^ Return the list of values that a LoadInst may return . May resolveIndirectCall :: a -> Instruction -> [Value] resolveIndirectCall pta i = case i of CallInst { callFunction = f } -> pointsTo pta f InvokeInst { invokeFunction = f } -> pointsTo pta f _ -> []
1c9043483192f30ca9eba8d2004f13e17368a83d46078d272b91ef828312909a
open-company/open-company-web
routing.cljs
(ns oc.web.stores.routing (:require [oc.web.lib.utils :as utils] [oc.web.dispatcher :as dispatcher])) (defn- clean-route [route-map] (update route-map :route #(set (map keyword (remove nil? %))))) (defmethod dispatcher/action :routing [db [_ route]] (assoc db dispatcher/router-key (clean-route route))) (defmethod dispatcher/action :show-login-wall [db [_ route]] (assoc db :force-login-wall true)) (defmethod dispatcher/action :route/rewrite [db [_ k v]] (assoc-in db [dispatcher/router-key k] v)) (defmethod dispatcher/action :org-nav-out [db [_ from-org to-org]] (-> db (assoc :orgs-dropdown-visible false) (assoc :mobile-navigation-sidebar false) (dissoc (first dispatcher/cmail-state-key)) (dissoc (first dispatcher/cmail-data-key)) (dissoc dispatcher/foc-menu-key) (dissoc dispatcher/payments-ui-upgraded-banner-key)))
null
https://raw.githubusercontent.com/open-company/open-company-web/700f751b8284d287432ba73007b104f26669be91/src/main/oc/web/stores/routing.cljs
clojure
(ns oc.web.stores.routing (:require [oc.web.lib.utils :as utils] [oc.web.dispatcher :as dispatcher])) (defn- clean-route [route-map] (update route-map :route #(set (map keyword (remove nil? %))))) (defmethod dispatcher/action :routing [db [_ route]] (assoc db dispatcher/router-key (clean-route route))) (defmethod dispatcher/action :show-login-wall [db [_ route]] (assoc db :force-login-wall true)) (defmethod dispatcher/action :route/rewrite [db [_ k v]] (assoc-in db [dispatcher/router-key k] v)) (defmethod dispatcher/action :org-nav-out [db [_ from-org to-org]] (-> db (assoc :orgs-dropdown-visible false) (assoc :mobile-navigation-sidebar false) (dissoc (first dispatcher/cmail-state-key)) (dissoc (first dispatcher/cmail-data-key)) (dissoc dispatcher/foc-menu-key) (dissoc dispatcher/payments-ui-upgraded-banner-key)))
ff7a0c7a3b0ee012b4f5e9be65ccb6079f677fc4a19a777ebcbe09f05a87aaea
snmsts/cl-langserver
tcp.lisp
(in-package :langserver-base) ;;;; TCP Server (defvar *communication-style* (preferred-communication-style)) (defvar *dont-close* nil "Default value of :dont-close argument to start-server and create-server.") (defun start-server (port-file &key (style *communication-style*) (dont-close *dont-close*)) "Start the server and write the listen port number to PORT-FILE. This is the entry point for Emacs." (setup-server 0 (lambda (port) (announce-server-port port-file port)) style dont-close nil)) (defun create-server (&key (port default-server-port) (style *communication-style*) (dont-close *dont-close*) backlog) "Start a langserver server on PORT running in STYLE. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (setup-server port #'simple-announce-function style dont-close backlog)) (defun find-external-format-or-lose (coding-system) (or (find-external-format coding-system) (error "Unsupported coding system: ~s" coding-system))) (defparameter *loopback-interface* "127.0.0.1") (defmacro restart-loop (form &body clauses) "Executes FORM, with restart-case CLAUSES which have a chance to modify FORM's environment before trying again (by returning normally) or giving up (through an explicit transfer of control), all within an implicit block named nil. e.g.: (restart-loop (http-request url) (use-value (new) (setq url new)))" `(loop (restart-case (return ,form) ,@clauses))) (defun socket-quest (port backlog) "Attempt o create a socket on PORT. Add a restart, prompting user to enter a new port if PORT is already taken." (restart-loop (create-socket *loopback-interface* port :backlog backlog) (use-value (&optional (new-port (1+ port))) :report (lambda (stream) (format stream "Try a port other than ~D" port)) :interactive (lambda () (format *query-io* "Enter port (defaults to ~D): " (1+ port)) (finish-output *query-io*) ; necessary for tunnels (ignore-errors (list (parse-integer (read-line *query-io*))))) (setq port new-port)))) (defun setup-server (port announce-fn style dont-close backlog) (init-log-output) (let* ((socket (socket-quest port backlog)) (port (local-port socket))) (funcall announce-fn port) (labels ((serve () (accept-connections socket style dont-close)) (note () (send-to-sentinel `(:add-server ,socket ,port ,(current-thread)))) (serve-loop () (note) (loop do (serve) while dont-close))) (ecase style (:spawn (initialize-multiprocessing (lambda () (start-sentinel) (spawn #'serve-loop :name (format nil "langserver ~s" port))))) ((:fd-handler :sigio) (note) (add-fd-handler socket #'serve)) ((nil) (serve-loop)))) port)) (defun stop-server (port) "Stop server running on PORT." (send-to-sentinel `(:stop-server :port ,port))) (defun restart-server (&key (port default-server-port) (style *communication-style*) (dont-close *dont-close*)) "Stop the server listening on PORT, then start a new Langserver server on PORT running in STYLE. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (stop-server port) (sleep 5) (create-server :port port :style style :dont-close dont-close)) (defun accept-connections (socket style dont-close) (let ((client (unwind-protect (accept-connection socket :external-format nil :buffering t) (unless dont-close (close-socket socket))))) (serve-requests (make-connection socket client style)) (unless dont-close (send-to-sentinel `(:stop-server :socket ,socket))))) (defun serve-requests (connection) "Read and process all requests on connections." (etypecase connection (multithreaded-connection (spawn-threads-for-connection connection)) (singlethreaded-connection (ecase (connection-communication-style connection) ((nil) (simple-serve-requests connection)) (:sigio (install-sigio-handler connection)) (:fd-handler (install-fd-handler connection)))))) (defun stop-serving-requests (connection) (etypecase connection (multithreaded-connection (cleanup-connection-threads connection)) (singlethreaded-connection (ecase (connection-communication-style connection) ((nil)) (:sigio (deinstall-sigio-handler connection)) (:fd-handler (deinstall-fd-handler connection)))))) (defun announce-server-port (file port) (with-open-file (s file :direction :output :if-exists :error :if-does-not-exist :create) (format s "~S~%" port)) (simple-announce-function port)) (defun simple-announce-function (port) (when *langserver-debug-p* (format *log-output* "~&;; langserver started at port: ~D.~%" port) (force-output *log-output*))) ;;;;; Event Decoding/Encoding (defun decode-message (stream) "Read an S-expression from STREAM using the langserver protocol." (log-event "decode-message~%") (without-client-interrupts (handler-bind ((error #'signal-langserver-error)) (handler-case (read-message stream *langserver-io-package*) #|(slynk-reader-error (c) `(:reader-error ,(slynk-reader-error.packet c) ,(slynk-reader-error.cause c)))|# )))) (defun encode-message (message stream) "Write an S-expression to STREAM using the langserver protocol." (log-event "encode-message~%") (without-client-interrupts (handler-bind ((error #'signal-langserver-error)) (write-message message *langserver-io-package* stream))))
null
https://raw.githubusercontent.com/snmsts/cl-langserver/3b1246a5d0bd58459e7a64708f820bf718cf7175/src/tcp.lisp
lisp
TCP Server necessary for tunnels Event Decoding/Encoding (slynk-reader-error (c) `(:reader-error ,(slynk-reader-error.packet c) ,(slynk-reader-error.cause c)))
(in-package :langserver-base) (defvar *communication-style* (preferred-communication-style)) (defvar *dont-close* nil "Default value of :dont-close argument to start-server and create-server.") (defun start-server (port-file &key (style *communication-style*) (dont-close *dont-close*)) "Start the server and write the listen port number to PORT-FILE. This is the entry point for Emacs." (setup-server 0 (lambda (port) (announce-server-port port-file port)) style dont-close nil)) (defun create-server (&key (port default-server-port) (style *communication-style*) (dont-close *dont-close*) backlog) "Start a langserver server on PORT running in STYLE. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (setup-server port #'simple-announce-function style dont-close backlog)) (defun find-external-format-or-lose (coding-system) (or (find-external-format coding-system) (error "Unsupported coding system: ~s" coding-system))) (defparameter *loopback-interface* "127.0.0.1") (defmacro restart-loop (form &body clauses) "Executes FORM, with restart-case CLAUSES which have a chance to modify FORM's environment before trying again (by returning normally) or giving up (through an explicit transfer of control), all within an implicit block named nil. e.g.: (restart-loop (http-request url) (use-value (new) (setq url new)))" `(loop (restart-case (return ,form) ,@clauses))) (defun socket-quest (port backlog) "Attempt o create a socket on PORT. Add a restart, prompting user to enter a new port if PORT is already taken." (restart-loop (create-socket *loopback-interface* port :backlog backlog) (use-value (&optional (new-port (1+ port))) :report (lambda (stream) (format stream "Try a port other than ~D" port)) :interactive (lambda () (format *query-io* "Enter port (defaults to ~D): " (1+ port)) (ignore-errors (list (parse-integer (read-line *query-io*))))) (setq port new-port)))) (defun setup-server (port announce-fn style dont-close backlog) (init-log-output) (let* ((socket (socket-quest port backlog)) (port (local-port socket))) (funcall announce-fn port) (labels ((serve () (accept-connections socket style dont-close)) (note () (send-to-sentinel `(:add-server ,socket ,port ,(current-thread)))) (serve-loop () (note) (loop do (serve) while dont-close))) (ecase style (:spawn (initialize-multiprocessing (lambda () (start-sentinel) (spawn #'serve-loop :name (format nil "langserver ~s" port))))) ((:fd-handler :sigio) (note) (add-fd-handler socket #'serve)) ((nil) (serve-loop)))) port)) (defun stop-server (port) "Stop server running on PORT." (send-to-sentinel `(:stop-server :port ,port))) (defun restart-server (&key (port default-server-port) (style *communication-style*) (dont-close *dont-close*)) "Stop the server listening on PORT, then start a new Langserver server on PORT running in STYLE. If DONT-CLOSE is true then the listen socket will accept multiple connections, otherwise it will be closed after the first." (stop-server port) (sleep 5) (create-server :port port :style style :dont-close dont-close)) (defun accept-connections (socket style dont-close) (let ((client (unwind-protect (accept-connection socket :external-format nil :buffering t) (unless dont-close (close-socket socket))))) (serve-requests (make-connection socket client style)) (unless dont-close (send-to-sentinel `(:stop-server :socket ,socket))))) (defun serve-requests (connection) "Read and process all requests on connections." (etypecase connection (multithreaded-connection (spawn-threads-for-connection connection)) (singlethreaded-connection (ecase (connection-communication-style connection) ((nil) (simple-serve-requests connection)) (:sigio (install-sigio-handler connection)) (:fd-handler (install-fd-handler connection)))))) (defun stop-serving-requests (connection) (etypecase connection (multithreaded-connection (cleanup-connection-threads connection)) (singlethreaded-connection (ecase (connection-communication-style connection) ((nil)) (:sigio (deinstall-sigio-handler connection)) (:fd-handler (deinstall-fd-handler connection)))))) (defun announce-server-port (file port) (with-open-file (s file :direction :output :if-exists :error :if-does-not-exist :create) (format s "~S~%" port)) (simple-announce-function port)) (defun simple-announce-function (port) (when *langserver-debug-p* (format *log-output* "~&;; langserver started at port: ~D.~%" port) (force-output *log-output*))) (defun decode-message (stream) "Read an S-expression from STREAM using the langserver protocol." (log-event "decode-message~%") (without-client-interrupts (handler-bind ((error #'signal-langserver-error)) (handler-case (read-message stream *langserver-io-package*) )))) (defun encode-message (message stream) "Write an S-expression to STREAM using the langserver protocol." (log-event "encode-message~%") (without-client-interrupts (handler-bind ((error #'signal-langserver-error)) (write-message message *langserver-io-package* stream))))
6e7e7a88252b41720d34ba975383ae2a06917d9281d68db4286eb4e84f27913c
unisonweb/unison
RemoteRepo.hs
# LANGUAGE RecordWildCards # module Unison.Codebase.Editor.RemoteRepo where import Control.Lens (Lens') import qualified Control.Lens as Lens import qualified Data.Text as Text import Unison.Codebase.Path (Path) import qualified Unison.Codebase.Path as Path import Unison.Codebase.ShortCausalHash (ShortCausalHash) import qualified Unison.Codebase.ShortCausalHash as SCH import Unison.Prelude import Unison.Share.Types import qualified Unison.Util.Monoid as Monoid data ReadRepo = ReadRepoGit ReadGitRepo | ReadRepoShare ShareCodeserver deriving stock (Eq, Ord, Show) data ShareCodeserver = DefaultCodeserver | CustomCodeserver CodeserverURI deriving stock (Eq, Ord, Show) newtype ShareUserHandle = ShareUserHandle {shareUserHandleToText :: Text} deriving stock (Eq, Ord, Show) -- | -- >>> :set -XOverloadedLists -- >>> import Data.Maybe (fromJust) > > > import Network . URI -- >>> displayShareCodeserver DefaultCodeserver "share" ["base", "List"] -- "share.base.List" -- >>> displayShareCodeserver DefaultCodeserver "share" [] -- "share" -- >>> displayShareCodeserver (CustomCodeserver . fromJust $ parseURI "-next.unison-lang.org/api" >>= codeserverFromURI ) "unison" ["base", "List"] -- "share(-next.unison-lang.org:443/api).unison.base.List" displayShareCodeserver :: ShareCodeserver -> ShareUserHandle -> Path -> Text displayShareCodeserver cs shareUser path = let shareServer = case cs of DefaultCodeserver -> "" CustomCodeserver cu -> "share(" <> tShow cu <> ")." in shareServer <> shareUserHandleToText shareUser <> maybePrintPath path data ReadGitRepo = ReadGitRepo {url :: Text, ref :: Maybe Text} deriving stock (Eq, Ord, Show) data WriteRepo = WriteRepoGit WriteGitRepo | WriteRepoShare ShareCodeserver deriving stock (Eq, Ord, Show) data WriteGitRepo = WriteGitRepo {url :: Text, branch :: Maybe Text} deriving stock (Eq, Ord, Show) writeToRead :: WriteRepo -> ReadRepo writeToRead = \case WriteRepoGit repo -> ReadRepoGit (writeToReadGit repo) WriteRepoShare repo -> ReadRepoShare repo writeToReadGit :: WriteGitRepo -> ReadGitRepo writeToReadGit = \case WriteGitRepo {url, branch} -> ReadGitRepo {url = url, ref = branch} writePathToRead :: WriteRemotePath -> ReadRemoteNamespace writePathToRead = \case WriteRemotePathGit WriteGitRemotePath {repo, path} -> ReadRemoteNamespaceGit ReadGitRemoteNamespace {repo = writeToReadGit repo, sch = Nothing, path} WriteRemotePathShare WriteShareRemotePath {server, repo, path} -> ReadRemoteNamespaceShare ReadShareRemoteNamespace {server, repo, path} printReadGitRepo :: ReadGitRepo -> Text printReadGitRepo ReadGitRepo {url, ref} = "git(" <> url <> Monoid.fromMaybe (Text.cons ':' <$> ref) <> ")" printWriteGitRepo :: WriteGitRepo -> Text printWriteGitRepo WriteGitRepo {url, branch} = "git(" <> url <> Monoid.fromMaybe (Text.cons ':' <$> branch) <> ")" -- | print remote namespace printNamespace :: ReadRemoteNamespace -> Text printNamespace = \case ReadRemoteNamespaceGit ReadGitRemoteNamespace {repo, sch, path} -> printReadGitRepo repo <> maybePrintSCH sch <> maybePrintPath path where maybePrintSCH = \case Nothing -> mempty Just sch -> "#" <> SCH.toText sch ReadRemoteNamespaceShare ReadShareRemoteNamespace {server, repo, path} -> displayShareCodeserver server repo path -- | Render a 'WriteRemotePath' as text. printWriteRemotePath :: WriteRemotePath -> Text printWriteRemotePath = \case WriteRemotePathGit (WriteGitRemotePath {repo, path}) -> printWriteGitRepo repo <> maybePrintPath path WriteRemotePathShare (WriteShareRemotePath {server, repo, path}) -> displayShareCodeserver server repo path maybePrintPath :: Path -> Text maybePrintPath path = if path == Path.empty then mempty else "." <> Path.toText path data ReadRemoteNamespace = ReadRemoteNamespaceGit ReadGitRemoteNamespace | ReadRemoteNamespaceShare ReadShareRemoteNamespace deriving stock (Eq, Show) data ReadGitRemoteNamespace = ReadGitRemoteNamespace { repo :: ReadGitRepo, sch :: Maybe ShortCausalHash, path :: Path } deriving stock (Eq, Show) data ReadShareRemoteNamespace = ReadShareRemoteNamespace { server :: ShareCodeserver, repo :: ShareUserHandle, -- sch :: Maybe ShortCausalHash, -- maybe later path :: Path } deriving stock (Eq, Show) isPublic :: ReadShareRemoteNamespace -> Bool isPublic ReadShareRemoteNamespace {path} = case path of ("public" Path.:< _) -> True _ -> False data WriteRemotePath = WriteRemotePathGit WriteGitRemotePath | WriteRemotePathShare WriteShareRemotePath deriving stock (Eq, Show) -- | A lens which focuses the path of a remote path. remotePath_ :: Lens' WriteRemotePath Path remotePath_ = Lens.lens getter setter where getter = \case WriteRemotePathGit (WriteGitRemotePath _ path) -> path WriteRemotePathShare (WriteShareRemotePath _ _ path) -> path setter remote path = case remote of WriteRemotePathGit (WriteGitRemotePath repo _) -> WriteRemotePathGit $ WriteGitRemotePath repo path WriteRemotePathShare (WriteShareRemotePath server repo _) -> WriteRemotePathShare $ WriteShareRemotePath server repo path data WriteGitRemotePath = WriteGitRemotePath { repo :: WriteGitRepo, path :: Path } deriving stock (Eq, Show) data WriteShareRemotePath = WriteShareRemotePath { server :: ShareCodeserver, repo :: ShareUserHandle, path :: Path } deriving stock (Eq, Show)
null
https://raw.githubusercontent.com/unisonweb/unison/77e636320d9d886e561264e4df5511840af94cc0/parser-typechecker/src/Unison/Codebase/Editor/RemoteRepo.hs
haskell
| >>> :set -XOverloadedLists >>> import Data.Maybe (fromJust) >>> displayShareCodeserver DefaultCodeserver "share" ["base", "List"] "share.base.List" >>> displayShareCodeserver DefaultCodeserver "share" [] "share" >>> displayShareCodeserver (CustomCodeserver . fromJust $ parseURI "-next.unison-lang.org/api" >>= codeserverFromURI ) "unison" ["base", "List"] "share(-next.unison-lang.org:443/api).unison.base.List" | print remote namespace | Render a 'WriteRemotePath' as text. sch :: Maybe ShortCausalHash, -- maybe later | A lens which focuses the path of a remote path.
# LANGUAGE RecordWildCards # module Unison.Codebase.Editor.RemoteRepo where import Control.Lens (Lens') import qualified Control.Lens as Lens import qualified Data.Text as Text import Unison.Codebase.Path (Path) import qualified Unison.Codebase.Path as Path import Unison.Codebase.ShortCausalHash (ShortCausalHash) import qualified Unison.Codebase.ShortCausalHash as SCH import Unison.Prelude import Unison.Share.Types import qualified Unison.Util.Monoid as Monoid data ReadRepo = ReadRepoGit ReadGitRepo | ReadRepoShare ShareCodeserver deriving stock (Eq, Ord, Show) data ShareCodeserver = DefaultCodeserver | CustomCodeserver CodeserverURI deriving stock (Eq, Ord, Show) newtype ShareUserHandle = ShareUserHandle {shareUserHandleToText :: Text} deriving stock (Eq, Ord, Show) > > > import Network . URI displayShareCodeserver :: ShareCodeserver -> ShareUserHandle -> Path -> Text displayShareCodeserver cs shareUser path = let shareServer = case cs of DefaultCodeserver -> "" CustomCodeserver cu -> "share(" <> tShow cu <> ")." in shareServer <> shareUserHandleToText shareUser <> maybePrintPath path data ReadGitRepo = ReadGitRepo {url :: Text, ref :: Maybe Text} deriving stock (Eq, Ord, Show) data WriteRepo = WriteRepoGit WriteGitRepo | WriteRepoShare ShareCodeserver deriving stock (Eq, Ord, Show) data WriteGitRepo = WriteGitRepo {url :: Text, branch :: Maybe Text} deriving stock (Eq, Ord, Show) writeToRead :: WriteRepo -> ReadRepo writeToRead = \case WriteRepoGit repo -> ReadRepoGit (writeToReadGit repo) WriteRepoShare repo -> ReadRepoShare repo writeToReadGit :: WriteGitRepo -> ReadGitRepo writeToReadGit = \case WriteGitRepo {url, branch} -> ReadGitRepo {url = url, ref = branch} writePathToRead :: WriteRemotePath -> ReadRemoteNamespace writePathToRead = \case WriteRemotePathGit WriteGitRemotePath {repo, path} -> ReadRemoteNamespaceGit ReadGitRemoteNamespace {repo = writeToReadGit repo, sch = Nothing, path} WriteRemotePathShare WriteShareRemotePath {server, repo, path} -> ReadRemoteNamespaceShare ReadShareRemoteNamespace {server, repo, path} printReadGitRepo :: ReadGitRepo -> Text printReadGitRepo ReadGitRepo {url, ref} = "git(" <> url <> Monoid.fromMaybe (Text.cons ':' <$> ref) <> ")" printWriteGitRepo :: WriteGitRepo -> Text printWriteGitRepo WriteGitRepo {url, branch} = "git(" <> url <> Monoid.fromMaybe (Text.cons ':' <$> branch) <> ")" printNamespace :: ReadRemoteNamespace -> Text printNamespace = \case ReadRemoteNamespaceGit ReadGitRemoteNamespace {repo, sch, path} -> printReadGitRepo repo <> maybePrintSCH sch <> maybePrintPath path where maybePrintSCH = \case Nothing -> mempty Just sch -> "#" <> SCH.toText sch ReadRemoteNamespaceShare ReadShareRemoteNamespace {server, repo, path} -> displayShareCodeserver server repo path printWriteRemotePath :: WriteRemotePath -> Text printWriteRemotePath = \case WriteRemotePathGit (WriteGitRemotePath {repo, path}) -> printWriteGitRepo repo <> maybePrintPath path WriteRemotePathShare (WriteShareRemotePath {server, repo, path}) -> displayShareCodeserver server repo path maybePrintPath :: Path -> Text maybePrintPath path = if path == Path.empty then mempty else "." <> Path.toText path data ReadRemoteNamespace = ReadRemoteNamespaceGit ReadGitRemoteNamespace | ReadRemoteNamespaceShare ReadShareRemoteNamespace deriving stock (Eq, Show) data ReadGitRemoteNamespace = ReadGitRemoteNamespace { repo :: ReadGitRepo, sch :: Maybe ShortCausalHash, path :: Path } deriving stock (Eq, Show) data ReadShareRemoteNamespace = ReadShareRemoteNamespace { server :: ShareCodeserver, repo :: ShareUserHandle, path :: Path } deriving stock (Eq, Show) isPublic :: ReadShareRemoteNamespace -> Bool isPublic ReadShareRemoteNamespace {path} = case path of ("public" Path.:< _) -> True _ -> False data WriteRemotePath = WriteRemotePathGit WriteGitRemotePath | WriteRemotePathShare WriteShareRemotePath deriving stock (Eq, Show) remotePath_ :: Lens' WriteRemotePath Path remotePath_ = Lens.lens getter setter where getter = \case WriteRemotePathGit (WriteGitRemotePath _ path) -> path WriteRemotePathShare (WriteShareRemotePath _ _ path) -> path setter remote path = case remote of WriteRemotePathGit (WriteGitRemotePath repo _) -> WriteRemotePathGit $ WriteGitRemotePath repo path WriteRemotePathShare (WriteShareRemotePath server repo _) -> WriteRemotePathShare $ WriteShareRemotePath server repo path data WriteGitRemotePath = WriteGitRemotePath { repo :: WriteGitRepo, path :: Path } deriving stock (Eq, Show) data WriteShareRemotePath = WriteShareRemotePath { server :: ShareCodeserver, repo :: ShareUserHandle, path :: Path } deriving stock (Eq, Show)
eb783f3c7204841023b1adedf2d02a33a8731a6ab206322fcbacc0ec79db013c
philipcmonk/phlisped
run-code.rkt
#lang racket (require "../core/common.rkt") (require "../core/extractdata.rkt") (require "../core/gnode.rkt") (require "../core/compiler.rkt") (provide data) (define (run-code event) (let ((code (reify G 0 #t)) (ns (make-base-namespace))) (print code) (newline) (eval '(require racket "graph.ss") ns) (eval '(define Next-r -1) ns) (eval '(define stack '()) ns) (eval '(define h (hash)) ns) (eval code ns) (set-runtime-vals (eval 'h ns)) (update-data) (update-childfuncs child-fun))) (define data (list '(#\G run) run-code))
null
https://raw.githubusercontent.com/philipcmonk/phlisped/ded1be5d9e7206cd3c71db49ccd250fa4381cf99/commands/run-code.rkt
racket
#lang racket (require "../core/common.rkt") (require "../core/extractdata.rkt") (require "../core/gnode.rkt") (require "../core/compiler.rkt") (provide data) (define (run-code event) (let ((code (reify G 0 #t)) (ns (make-base-namespace))) (print code) (newline) (eval '(require racket "graph.ss") ns) (eval '(define Next-r -1) ns) (eval '(define stack '()) ns) (eval '(define h (hash)) ns) (eval code ns) (set-runtime-vals (eval 'h ns)) (update-data) (update-childfuncs child-fun))) (define data (list '(#\G run) run-code))
b5e550cb7122a4f8f74bd33a73189d8055acd707a78ad679cd28e508c829c4d3
racket/typed-racket
gh-issue-144.rkt
#lang typed/racket (define-type F (-> String F String)) (: f F) (define (f x g) (string-append x))
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/gh-issue-144.rkt
racket
#lang typed/racket (define-type F (-> String F String)) (: f F) (define (f x g) (string-append x))
0fd94b912ab61120f78872698b2de9ee375f403be3674bdb9d6a722dfe6b23af
Kakadu/fp2022
tree.mli
* Copyright 2022 - 2023 , and contributors * SPDX - License - Identifier : LGPL-3.0 - or - later (* binary search tree data sturcture *) open Type exception Duplicate exception NotFound val get : int -> 'a tree -> 'a val size : 'a tree -> int val insert : int * 'a -> 'a tree -> 'a tree val delete : int -> 'a tree -> 'a tree val update : int -> 'a -> 'a tree -> 'a tree (* returns a list of the values in the tree, in order *) val inorder : 'a tree -> (int * 'a) list val empty : 'a tree (* bottom-up fold on tree *) val fold : ('a -> 'b -> 'a -> 'a) -> 'a -> 'b tree -> 'a val map : ('a -> 'b) -> 'a tree -> 'b tree val filter_based_on_value : ('a -> bool) -> 'a tree -> 'a tree val filter_based_on_key : (int -> bool) -> 'a tree -> 'a tree val generate_new_key : 'a tree -> int val get_key : ('a * int -> bool) -> 'a tree -> int val get_key_col : (column * int -> bool) -> column tree -> int val update_key : 'a tree -> 'a tree (* create a list containing values, sorted in ascending order *) val to_value_list : 'a tree -> 'a list
null
https://raw.githubusercontent.com/Kakadu/fp2022/0eb49bf60d173287607678159465c425cdf699be/SQLyd/lib/tree.mli
ocaml
binary search tree data sturcture returns a list of the values in the tree, in order bottom-up fold on tree create a list containing values, sorted in ascending order
* Copyright 2022 - 2023 , and contributors * SPDX - License - Identifier : LGPL-3.0 - or - later open Type exception Duplicate exception NotFound val get : int -> 'a tree -> 'a val size : 'a tree -> int val insert : int * 'a -> 'a tree -> 'a tree val delete : int -> 'a tree -> 'a tree val update : int -> 'a -> 'a tree -> 'a tree val inorder : 'a tree -> (int * 'a) list val empty : 'a tree val fold : ('a -> 'b -> 'a -> 'a) -> 'a -> 'b tree -> 'a val map : ('a -> 'b) -> 'a tree -> 'b tree val filter_based_on_value : ('a -> bool) -> 'a tree -> 'a tree val filter_based_on_key : (int -> bool) -> 'a tree -> 'a tree val generate_new_key : 'a tree -> int val get_key : ('a * int -> bool) -> 'a tree -> int val get_key_col : (column * int -> bool) -> column tree -> int val update_key : 'a tree -> 'a tree val to_value_list : 'a tree -> 'a list
82cad8cf0ed7e1467b8331d70048248ede846ffbd5b7e9535077f65c161f78fb
brevis-us/brevis
single_bird.clj
(ns us.brevis.example.single-bird (:gen-class) (:require [brevis-utils.parameters :as parameters] [us.brevis.vector :as vector] [us.brevis.physics.utils :as physics] [us.brevis.utils :as utils] [us.brevis.shape.cone :as cone] [us.brevis.core :as core] [clj-random.core :as random])) (def this-bird (atom nil)) (defn lrand-vec3 "Return a random vec3." ([=] (lrand-vec3 1 1 1)) ([x y z] (vector/vec3 (random/lrand x) (random/lrand y) (random/lrand z))) ([xmn xmx ymn ymx zmn zmx] (vector/vec3 (random/lrand xmn xmx) (random/lrand ymn ymx) (random/lrand zmn zmx)))) (defn random-acceleration "Return a random acceleration vec3" [] (lrand-vec3 -0.001 0.001 -0.001 0.001 -0.001 0.001)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; # # Birds (defn make-bird "Make a new bird. At the specified location." [position] (physics/move (physics/make-real {:type :bird :color (vector/vec4 1 0 0 1) :shape (cone/create-cone 10.2 1.5)}) position)) (defn fly "Change the acceleration of a bird." [bird] (let [bird-pos (physics/get-position bird) dist (vector/length-vec3 bird-pos)] (if (> dist 100) (physics/set-velocity (physics/move bird (vector/vec3 0 0 0)) (random-acceleration)) bird))) new - acceleration ( if ( zero ? ( vector / length new - acceleration ) ) ; new-acceleration ( vector / mul new - acceleration ( / 1 ( vector / length new - acceleration ) ) ) ) ] ;(physics/orient-object (physics/set-velocity ; (physics/set-acceleration ; (if (or (> (Math/abs (vector/x-val bird-pos)) boundary) ; (> (Math/abs (vector/y-val bird-pos)) boundary) ; (> (Math/abs (vector/z-val bird-pos)) boundary)) ; (physics/move bird (periodic-boundary bird-pos) #_(vec3 0 25 0)) ; bird) ; (bound-acceleration ; ;(physics/get-acceleration bird) ; new-acceleration # _ ( add ( ( get - acceleration bird ) 0.5 ) ; (mul new-acceleration speed)))) ; (bound-velocity (physics/get-velocity bird))) ; (vector/vec3 0 0 1); This is the up-vector of the shape ; (physics/get-velocity bird)))) ( add - global - update - handler 10 ( fn [ ] ( println ( get - time ) ( System / nanoTime ) ) ) ) (physics/enable-kinematics-update :bird); This tells the simulator to move our objects (utils/add-update-handler :bird fly); This tells the simulator how to update these objects ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; # # brevis control code (defn initialize-simulation "This is the function where you add everything to the world." [] (parameters/set-param :gui false) (physics/init-world) #_(set-camera-information (vec3 -10.0 -50.0 -200.0) (vec4 1.0 0.0 0.0 0.0)) ( camera / set - camera - information ( vector / vec3 -10.0 57.939613 -890.0 ) ( vector / vec4 1.0 0.0 0.0 0.0 ) ) (utils/set-dt 0.005) (physics/set-neighborhood-radius 50) (reset! this-bird (utils/add-object (make-bird (vector/vec3 0 0 0)))) (Thread/sleep 100) (.setVisible (.getFloor (fun.imagej.sciview/get-sciview)) false) (.surroundLighting (fun.imagej.sciview/get-sciview)) (.centerOnScene(fun.imagej.sciview/get-sciview))) ;; Start zee macheen (defn -main [& args] #_(start-nogui initialize-simulation) (if-not (empty? args) (core/start-nogui initialize-simulation) (core/start-gui initialize-simulation))) (core/autostart-in-repl -main) ;(-main)
null
https://raw.githubusercontent.com/brevis-us/brevis/de51c173279e82cca6d5990010144167050358a3/src/main/clojure/us/brevis/example/single_bird.clj
clojure
new-acceleration (physics/orient-object (physics/set-velocity (physics/set-acceleration (if (or (> (Math/abs (vector/x-val bird-pos)) boundary) (> (Math/abs (vector/y-val bird-pos)) boundary) (> (Math/abs (vector/z-val bird-pos)) boundary)) (physics/move bird (periodic-boundary bird-pos) #_(vec3 0 25 0)) bird) (bound-acceleration ;(physics/get-acceleration bird) new-acceleration (mul new-acceleration speed)))) (bound-velocity (physics/get-velocity bird))) (vector/vec3 0 0 1); This is the up-vector of the shape (physics/get-velocity bird)))) This tells the simulator to move our objects This tells the simulator how to update these objects Start zee macheen (-main)
(ns us.brevis.example.single-bird (:gen-class) (:require [brevis-utils.parameters :as parameters] [us.brevis.vector :as vector] [us.brevis.physics.utils :as physics] [us.brevis.utils :as utils] [us.brevis.shape.cone :as cone] [us.brevis.core :as core] [clj-random.core :as random])) (def this-bird (atom nil)) (defn lrand-vec3 "Return a random vec3." ([=] (lrand-vec3 1 1 1)) ([x y z] (vector/vec3 (random/lrand x) (random/lrand y) (random/lrand z))) ([xmn xmx ymn ymx zmn zmx] (vector/vec3 (random/lrand xmn xmx) (random/lrand ymn ymx) (random/lrand zmn zmx)))) (defn random-acceleration "Return a random acceleration vec3" [] (lrand-vec3 -0.001 0.001 -0.001 0.001 -0.001 0.001)) # # Birds (defn make-bird "Make a new bird. At the specified location." [position] (physics/move (physics/make-real {:type :bird :color (vector/vec4 1 0 0 1) :shape (cone/create-cone 10.2 1.5)}) position)) (defn fly "Change the acceleration of a bird." [bird] (let [bird-pos (physics/get-position bird) dist (vector/length-vec3 bird-pos)] (if (> dist 100) (physics/set-velocity (physics/move bird (vector/vec3 0 0 0)) (random-acceleration)) bird))) new - acceleration ( if ( zero ? ( vector / length new - acceleration ) ) ( vector / mul new - acceleration ( / 1 ( vector / length new - acceleration ) ) ) ) ] # _ ( add ( ( get - acceleration bird ) 0.5 ) ( add - global - update - handler 10 ( fn [ ] ( println ( get - time ) ( System / nanoTime ) ) ) ) # # brevis control code (defn initialize-simulation "This is the function where you add everything to the world." [] (parameters/set-param :gui false) (physics/init-world) #_(set-camera-information (vec3 -10.0 -50.0 -200.0) (vec4 1.0 0.0 0.0 0.0)) ( camera / set - camera - information ( vector / vec3 -10.0 57.939613 -890.0 ) ( vector / vec4 1.0 0.0 0.0 0.0 ) ) (utils/set-dt 0.005) (physics/set-neighborhood-radius 50) (reset! this-bird (utils/add-object (make-bird (vector/vec3 0 0 0)))) (Thread/sleep 100) (.setVisible (.getFloor (fun.imagej.sciview/get-sciview)) false) (.surroundLighting (fun.imagej.sciview/get-sciview)) (.centerOnScene(fun.imagej.sciview/get-sciview))) (defn -main [& args] #_(start-nogui initialize-simulation) (if-not (empty? args) (core/start-nogui initialize-simulation) (core/start-gui initialize-simulation))) (core/autostart-in-repl -main)
e88b2f9c149deaabc197c34a268a72aebab16f66c58bef8aa87986291ab0a435
tweag/ormolu
prelude1.hs
{-# RULES "map/map" forall f g xs. map f (map g xs) = map (f.g) xs "map/append" forall f xs ys. map f (xs ++ ys) = map f xs ++ map f ys #-} # RULES " map " [ ~1 ] forall f xs . map f xs = build ( \c n - > foldr ( mapFB c f ) n xs ) " mapList " [ 1 ] forall foldr ( mapFB ( :) f ) [ ] = map f " mapFB " forall c f g. mapFB ( mapFB c f ) g = mapFB c ( f.g ) # "map" [~1] forall f xs. map f xs = build (\c n -> foldr (mapFB c f) n xs) "mapList" [1] forall f. foldr (mapFB (:) f) [] = map f "mapFB" forall c f g. mapFB (mapFB c f) g = mapFB c (f.g) #-} {-# RULES "map/map" [~2] forall f g xs. map f (map g xs) = map (f.g) xs; "f" op True y = False; "g" op True y = False #-}
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/rewrite-rule/prelude1.hs
haskell
# RULES "map/map" forall f g xs. map f (map g xs) = map (f.g) xs "map/append" forall f xs ys. map f (xs ++ ys) = map f xs ++ map f ys # # RULES "map/map" [~2] forall f g xs. map f (map g xs) = map (f.g) xs; "f" op True y = False; "g" op True y = False #
# RULES " map " [ ~1 ] forall f xs . map f xs = build ( \c n - > foldr ( mapFB c f ) n xs ) " mapList " [ 1 ] forall foldr ( mapFB ( :) f ) [ ] = map f " mapFB " forall c f g. mapFB ( mapFB c f ) g = mapFB c ( f.g ) # "map" [~1] forall f xs. map f xs = build (\c n -> foldr (mapFB c f) n xs) "mapList" [1] forall f. foldr (mapFB (:) f) [] = map f "mapFB" forall c f g. mapFB (mapFB c f) g = mapFB c (f.g) #-}
a2eb4a1977300bdee5649be0c5a6e85811f08e9b27677d69560e2c5542517f89
kennknowles/aspcc
php.ml
(* Printing functions *) open Printf let trim_eol s = try ignore (String.index s '\n'); String.sub s 0 ((String.length s) - 1) with | Not_found -> s (* Invalid_argument means the string has 0 length *) | Invalid_argument _ -> s let indent indentation str = (Str.global_replace (Str.regexp "^") indentation (trim_eol str)) ^ "\n" (*===========================================================================*) (* For managing a symbol table and class definitions *) (*===========================================================================*) TODO : this could be an entirely separate module for managing VB 's symbol table exception SymbolFound type symbol_variety = | Sub of AspAst.function_def | Function of AspAst.function_def the string option knows what type the var is , for OO lookup type the var is, for OO lookup *) | Class of AspAst.class_def | Const of AspAst.constant_definition | Dummy of unit type statement_context = | ToplevelContext | ClassContext | FunctionContext of string let symbol_table = Hashtbl.create 53 let scope_stack = Stack.create () let add_symbol name definition = Hashtbl.add symbol_table (String.lowercase name) definition; Hashtbl.add (Stack.top scope_stack) (String.lowercase name) () let find_symbol_in name sym_table = try let result = Hashtbl.find sym_table ( String.lowercase name ) in Some result with Not_found - > None try let result = Hashtbl.find sym_table (String.lowercase name) in Some result with Not_found -> None*) let find_symbol name = Hashtbl.find symbol_table name let push_scope () = Stack.push (Hashtbl.create 53) scope_stack let pop_scope () = Hashtbl.iter (fun key value -> Hashtbl.remove symbol_table key) (Stack.pop scope_stack) (* Add all the built-in functions and intrinsic objects*) Todo : add param info ... add OO member symbol tables ... add past the letter ' a ' let _ = push_scope (); List.iter (fun (x,y) -> add_symbol x y) [ "Abs", Function ("Abs", [], []); "Array", Function ("Array", [], []); "Asc", Function ("Asc", [], []); "Atn", Function ("Atn", [], []); "CBool", Function ("CBool", [], []); "CByte", Function ("CByte", [], []); "CCur", Function ("CCur", [], []); "CDate", Function ("CDate", [], []); "CDbl", Function ("CDbl", [], []); "Chr", Function ("Chr", [], []); "CInt", Function ("CInt", [], []); "CLng", Function ("CLng", [], []); "Cos", Function ("Cos", [], []) ]; (* an AspAst.Ident in the symbol table represents a variable *) List.iter (fun (x, y) -> add_symbol x (Variable (x, None))) [ "Response", "AspResponse"; "Request", "AspRequest"; "Server", "AspServer"; "Session", "AspSession" ] (* little helpers *) (* see if the current thing is registered as something other than a variable, and thus needs no dollar sign *) let is_variable symbol = try ( match find_symbol symbol with | Variable _ -> true | _ -> false ) with | Not_found -> true (* not quite, but could be an undeclared var *) let concat_map ?str func the_list = String.concat (match str with | Some c -> c | None -> "") (List.map func the_list) let comma_map func the_list = concat_map ~str:", " func the_list let arrow_map func the_list = concat_map ~str:"->" func the_list (*====== For tracking equivalencies for PHP =====*) type php_mapping_function = (AspAst.identifier -> string) let equivalency_table = Hashtbl.create 53 let get_php_equivalent vb_id = Hashtbl.find equivalency_table (String.lowercase vb_id) let add_equivalency vb_func sprint_func = Hashtbl.add equivalency_table (String.lowercase vb_func) sprint_func (* the adding of equivalent mappings occurs below, for declaration order convenience *) (*===========================================================================*) (* For outputing the PHP *) (*===========================================================================*) (*============= vb_identifier ================*) (* TODO: lookup of equivalencies *) let rec sprint_identifier ?(top : bool = true) id = (* if top then let format_func = get_php_equivalent (id_collapse id) *) match id with | AspAst.AtomicId s -> (if is_variable s then "$" else "") ^ s | AspAst.Dot (base,member) -> sprintf "%s->%s" (sprint_identifier base) member | AspAst.Indices (base,indices) -> sprintf "%s[%s]" (* or, if it is a function in the current scope "%s(%s)" *) (sprint_identifier base) (comma_map sprint_rvalue indices) (*============= vb_rvalue ================*) and sprint_rvalue rval = match rval with | AspAst.Int (AspAst.Dec, i) -> sprintf "%li" i | AspAst.Int (AspAst.Hex, h) -> sprintf "%lx" h | AspAst.Int (AspAst.Oct, o) -> sprintf "%lo" o | AspAst.Float f -> sprintf "%f" f | AspAst.String s -> sprintf "'%s'" s (* vbscript has nothing like PHP double-quote strings *) | AspAst.Bool b -> if b then "TRUE" else "FALSE" Re - implement these later - they need to be converted to the new AST layout | AspAst . Concat ( v1 , v2 ) - > sprintf " ( % s . % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Negative i - > sprintf " -%s " ( sprint_rvalue i ) | AspAst . Add ( v1 , v2 ) - > sprintf " ( % s + % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Subtract ( v1 , v2 ) - > sprintf " ( % s - % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Mult ( v1 , v2 ) - > sprintf " ( % s * % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . IntDiv ( v1 , v2 ) - > sprintf " ( % s / % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Div ( v1 , v2 ) - > sprintf " ( ( 1.0 * % s ) / % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Exp ( v1 , v2 ) - > sprintf " ( % s ^ % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Not n - > sprintf " ! ( % s ) " ( sprint_rvalue n ) ( * TODO : does not support bitwise operators Re-implement these later - they need to be converted to the new AST layout | AspAst.Concat (v1, v2) -> sprintf "(%s . %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Negative i -> sprintf "-%s" (sprint_rvalue i) | AspAst.Add (v1, v2) -> sprintf "(%s + %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Subtract (v1, v2) -> sprintf "(%s - %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Mult (v1, v2) -> sprintf "(%s * %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.IntDiv (v1, v2) -> sprintf "(%s / %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Div (v1, v2) -> sprintf "((1.0 * %s) / %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Exp (v1, v2) -> sprintf "(%s ^ %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Not n -> sprintf "!(%s)" (sprint_rvalue n) (* TODO: does not support bitwise operators *) | AspAst.And (v1, v2) -> sprintf "(%s && %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Or (v1, v2) -> sprintf "(%s || %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Xor (v1, v2) -> sprintf "(%s xor %s)" (sprint_rvalue v1) (sprint_rvalue v2) (* convert a->b to (not a or b) *) | AspAst.Imp (v1, v2) -> sprintf "(!%s || %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Eqv (v1, v2) -> sprintf "(%s == %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Equals (v1, v2) -> sprintf "(%s == %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.NotEquals (v1, v2) -> sprintf "(%s != %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.LessEqual (v1, v2) -> sprintf "(%s <= %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.GreaterEqual (v1, v2) -> sprintf "(%s >= %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Less (v1, v2) -> sprintf "(%s < %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Greater (v1, v2) -> sprintf "(%s > %s)" (sprint_rvalue v1) (sprint_rvalue v2) *) | AspAst.Identifier identifier -> sprint_identifier identifier | _ -> "/* Unknown expression */" (* since declaring member vars to be arrays must take place in the constructor, we need a function to scan a statement and output the constructor shit *) (* TODO: support preserving... probably by an extremely complex PHP function *) let rec sprint_dim_indices size_list = match size_list with | [] -> "''" | size::rest -> sprintf "array_pad(array(), %s, %s)" (sprint_rvalue size) (sprint_dim_indices rest) let sprint_dim_tail id = match id with | AspAst.Indices (base, []) -> sprintf "%s = array();\n" (sprint_identifier base) | AspAst.Indices (base, size) -> sprintf "%s = %s;\n" (sprint_identifier base) (sprint_dim_indices size) | _ -> "" let sprint_index_free_id id = match id with | AspAst.Indices (base, indices) -> sprint_identifier base | x -> sprint_identifier x let sprint_constructor_info (line_num, statement) = match statement with | AspAst . MemberDef ( _ , _ , ( AspAst . MemberIdent i d ) ) | AspAst . Dim i d - > sprint_dim_tail i d | AspAst.Dim id -> sprint_dim_tail id *) | _ -> "" (*========= vb_function =========*) let rec sprint_function ((name, params, statements) : AspAst.function_def) = (* TODO: when assigning to the function name, set $returnvalue, and always return it *) "" sprintf " function % s(%s)\n{\n%s}\n " name ( String.concat " , " params ) ( indent " \t " ( " $ returnvalue = '' ; " ^ ( concat_map ( sprint_statement ~context:(FunctionContext name ) ) statements ) ^ " return ( $ returnvalue ) ; ) ) (indent "\t" ("$returnvalue = '';\n" ^ (concat_map (sprint_statement ~context:(FunctionContext name)) statements) ^ "return ( $returnvalue );\n"))*) (*============== vb_assignment ================ *) and sprint_assignment context (id, rval) = (match context, id with (* This crazy match checks if the variable being assigned is the function of the current context *) | (FunctionContext funcname), (AspAst.AtomicId varname) when (funcname=varname) -> "$returnvalue" | _, _ -> (sprint_identifier id)) ^ " = " ^ (sprint_rvalue rval) ^ ";\n"; and sprint_dim context preserve id = match context with | ClassContext -> sprintf "var %s;\n" (sprint_index_free_id id) | _ -> sprint_dim_tail id and sprint_select context (rval, options) = sprintf "switch(%s)\n{\n%s}" (sprint_rvalue rval) (indent "\t" (concat_map (sprint_select_item context) options)) and sprint_select_item context (item, statements) = (match item with | AspAst.SelectValue rvals -> "case " ^ (concat_map ~str:":\ncase " sprint_rvalue rvals) ^ ":\n" | AspAst.SelectElse -> "default:\n") ^ (indent "\t" ( (concat_map (sprint_statement ~context:context) statements) ^ "break;\n")) context is probably needed : just an ( AspAst.vb_compound_statement Stack.t ) , and is needed for With since php has no such thing , and Exit since we might need a numeric argument to break for With since php has no such thing, and Exit since we might need a numeric argument to break *) and sprint_statement ?(context = ToplevelContext) (line_num, statement) = match statement with " // empty statement " | AspAst.Assignment (a_id, a_val) -> sprint_assignment context (a_id, a_val) | AspAst.Call id -> (sprint_identifier id) ^ ";\n" | AspAst.Class (name, statements) -> sprintf "class %s { \n%s }\n" name (indent "\t" ( (String.concat "" (List.map (sprint_statement ~context:ClassContext) statements)) ^ (sprintf "function %s()\n{\n%s}\n" name (indent "\t" (String.concat "" (List.map sprint_constructor_info statements)))))) | AspAst.Comment c -> "// " ^ c | AspAst.CompoundStatement (compound_type, statements) -> (match compound_type with (* unsafe use of != instead of < or > because step can be negative a safe workaround is to assign STEP to a var, and then have an overly complex condition that is > if it is negative or < if it is positive... before that happens we should do a match on inc to see if it is simple and we can determine it at compile time *) | AspAst.For (var, start, finish, inc) -> sprintf "for(%s = %s; %s != %s; %s += %s)\n" var (sprint_rvalue start) var (sprint_rvalue finish) var (sprint_rvalue inc) | AspAst.ForEach (name, collection) -> sprintf "foreach(%s as $%s)\n" (sprint_rvalue collection) name | AspAst.While expr -> sprintf "while(%s)\n" (sprint_rvalue expr) | AspAst.With lval -> "" ) ^ "{\n" ^ (indent "\t" (String.concat "" (List.map sprint_statement statements))) ^ "}\n" | AspAst.Const (name, rval) -> sprintf "define(\"%s\", %s);\n" name (sprint_rvalue rval) (* TODO: in class context, cannot assign this to array() *) (* | AspAst.Dim id -> sprint_dim context false id *) | AspAst.Erase (var) -> (sprint_identifier var) ^ " = '';\n" | AspAst.Execute (rval) -> "// WARNING: the string passed to this eval has *not* been converted!\n" ^ "eval(" ^ (sprint_rvalue rval) ^ ");\n" | AspAst.Exit target -> (match target with | `Function -> "return ( $returnvalue );\n" | `Sub -> "return;\n" (* TODO: break with a number to bust out of many levels deep *) | _ -> "break;\n") | AspAst.Function func_def -> sprint_function func_def | AspAst.If (predicate, then_block, else_block) -> sprintf "if ( %s ) \n{\n%s}\nelse\n{\n%s}\n" (sprint_rvalue predicate) (indent "\t" (String.concat "" (List.map sprint_statement then_block))) (indent "\t" (String.concat "" (List.map sprint_statement else_block))) | AspAst.MemberDef (access, default, memberstatement) -> (* PHP doesn't have private/public *) (match memberstatement with (* | AspAst.MemberIdent id_list -> sprintf "var $%s;\n" (sprint_identifier id) *) | AspAst.MemberFunction x | AspAst.MemberSub x -> sprint_function x | AspAst.PropertyLet (name, params, statements) -> sprint_function (name ^ "_let", params, statements) | AspAst.PropertyGet (name, params, statements) -> sprint_function (name ^ "_get", params, statements) | AspAst.PropertySet (name, params, statements) -> sprint_function (name ^ "_set", params, statements)) | AspAst . | AspAst . OnErrorGotoZero - > " // error handling ? bah!\n " "// error handling? bah!\n" *) | AspAst.OptionExplicit -> "// option explicit? i guess i could look it up, bleh\n" | AspAst.Randomize -> "list ($r_usec, $r_sec) = explode(' ', microtime());\n" ^ "srand((float)$r_sec + (($float) $r_usec * 100000));\n" | AspAst.ReDim (preserve, id_list) -> List.map ( sprint_dim context preserve ) id_list | AspAst.Select (rval, options) -> sprint_select context (rval, options) (* TODO: here is where we can track the class type... i wish i knew some type-checking theory *) | AspAst.Set (id, rval) -> sprint_assignment context (id, rval) | AspAst.Sub func_def -> sprint_function func_def | AspAst.SubCall (id, rvals) -> sprint_identifier (AspAst.Indices (id, rvals)) ^ ";\n" (*| _ -> "// Encountered unknown statement\n"*) let sprint_page page = String.concat " " ( List.map ( function | AspAst . Html html - > html | AspAst . " < ? " ^ ( indent " \t " ( String.concat " " ( List.map sprint_statement vb ) ) ) ^ " \n ? > " ) page ) "" (List.map (function | AspAst.Html html -> html | AspAst.VbScript vb -> "<?" ^ (indent "\t" (String.concat "" (List.map sprint_statement vb))) ^ "\n?>") page)*) let print_page page = print_string (sprint_page page) (*========================================================================*) (*================== Addition of existing mappings =======================*) (*========================================================================*) (* note: 'direct_mapping' and 'implemented' do the same thing now, but this may not always be the case, so no merging *) let direct_mapping php_func = (fun (_, rvals) -> sprintf "%s(%s)" php_func (comma_map sprint_rvalue rvals)) (* the comma_map in this should be unneccessary since we can only convert a single value! *) let map_to_cast php_type = (fun (_, rvals) -> sprintf "((%s) %s)" php_type (comma_map sprint_rvalue rvals)) let map_to_literal php_code = (fun (_, rvals) -> php_code) let implemented php_func = (fun (_, rvals) -> sprintf "%s(%s)" php_func (comma_map sprint_rvalue rvals)) let format_dateserial (_, rvals) = match rvals with | year::month::day::_ -> sprintf "mktime(0, 0, 0, %s, %s, %s)" (sprint_rvalue month) (sprint_rvalue day) (sprint_rvalue year) | _ -> "" (* TODO: raise an exception here *) (* note: this get_date is not a builtin, but a wrapper because php cannot parse this: getdate(..)['...'] *) let format_date datepart (_, rvals) = sprintf "date('%s', datevalue(%s))" datepart (comma_map sprint_rvalue rvals) let format_instr (_, rvals) = match rvals with | haystack::needle::[] -> sprintf "instr(%s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) | start::haystack::needle::[] -> sprintf "instr(%s, %s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) (sprint_rvalue start) | start::haystack::needle::compare::_ -> sprintf "instr(%s, %s, %s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) (sprint_rvalue start) (sprint_rvalue compare) | _ -> "" (* TODO: raise an exception here *) (*============ for converting vb function calls to php ==========*) Comprehensive list of VBscript functions . There are four categories of functions : * Direct mappings * Functions implemented in PHP in asp_implementations.php * Functions that make no sense * Functions that are unsupported at this time There are four categories of functions: * Direct mappings * Functions implemented in PHP in asp_implementations.php * Functions that make no sense * Functions that are unsupported at this time *) TODO : make implementations for casts , which do the checking the functions would ... though they error all the time in horrendous ways :( VbScript functions would... though they error all the time in horrendous ways :( *) (* btw 0 is false, true is -1, use default is -2 *) let _ = List.iter (fun (x, y) -> add_equivalency x y) [ (* ============== BUILTIN FUNCTIONS ============== *) "abs", (direct_mapping "abs"); "array", (direct_mapping "array"); "asc", (direct_mapping "ord"); "atn", (direct_mapping "atan"); "cbool", (map_to_cast "bool"); "cbyte", (map_to_cast "int"); "ccur", (map_to_cast "double"); "cdate", (implemented "datevalue"); "cdbl", (map_to_cast "double"); "chr", (direct_mapping "chr"); "cint", (map_to_cast "int"); "clng", (map_to_cast "int"); "cos", (direct_mapping "cos"); (* "createobject" not supported, it would be useless anyhow *) "csng", (map_to_cast "float"); "cstr", (map_to_cast "string"); "date", (map_to_literal "date('m/d/Y')"); "dateadd", (implemented "dateadd"); "datediff", (implemented "datediff"); "datepart", (implemented "datepart"); "dateserial", format_dateserial; "datevalue", (implemented "datevalue"); "day", (format_date "d"); (* Eval sux *) "exp", (direct_mapping "exp"); "filter", (implemented "filter"); "fix", (implemented "fix"); "formatcurrency", (fun (id,rvals) -> "$" ^ (implemented "formatnumber" (id,rvals))); "formatdatetime", (implemented "formatdatetime"); "formatnumber", (implemented "formatnumber"); "formatpercent", (implemented "formatpercent"); GetLocale returns some unique i d number for locle LCID GetObject this is some fucked up thing GetRef dunno wtfg "hex", (direct_mapping "dechex"); "hour", (format_date "H"); (* "inputbox" client side only *) "instr", format_instr; "instrrev", (implemented "instrrev"); "int", (direct_mapping "floor"); "isarray", (direct_mapping "is_array"); "isdate", (implemented "isdate"); "isempty", (fun (id,rvals) -> sprintf "!%s" (sprint_rvalue (List.hd rvals))); "isnull", (fun (id,rvals) -> sprintf "!%s" (sprint_rvalue (List.hd rvals))); "isnumeric", (direct_mapping "is_numeric"); (* NOT is_int *) "isobject", (direct_mapping "is_object"); "join", (fun (id,rvals) -> match rvals with | val1::val2::[] -> sprintf "join(%s, %s)" (sprint_rvalue val2) (sprint_rvalue val1) | _ -> "" (* TODO: raise exception *)); "lbound", (map_to_literal "0"); "lcase", (direct_mapping "strtolower"); "left", (implemented "left"); "len", (direct_mapping "strlen"); LoadPicture - nonsense "log", (direct_mapping "log"); "ltrim", (direct_mapping "ltrim"); "mid", (direct_mapping "substr"); "minute", (format_date "i"); "month", (format_date "m"); "monthname", (implemented "monthname"); MsgBox - nonsense "now", (map_to_literal "date('D M d H:i:s Y')"); "oct", (direct_mapping "decoct"); (* Replace(string,find,replace,start,count,compare) *) (* RGB - who cares *) "rght", (implemented "right"); "rnd", (fun (id,rvals) -> "(rand()/(float)getrandmax())"); "round", (direct_mapping "round"); "rtrim", (direct_mapping "rtrim"); ScriptEngine - returns language , i.e. (* ScriptEngineBuildVersion none of these maatter *) (* ScriptEngineMajorVersion *) (* ScriptEngineMinorVersion *) "second", (format_date "s"); SetLocale more LCID stuff "sgn", (fun (id,rvals) -> let v = (sprint_rvalue (List.hd rvals)) in sprintf "(abs(%s)/%s)" v v); (* Sgn - the sign of a number *) "sin", (direct_mapping "sin"); "space", (fun (id,rvals) -> sprintf "str_pad('', %s)" (sprint_rvalue (List.hd rvals))); Split(expression , delim , count , compare ) "sqr", (fun (id,rvals) -> let expr = (sprint_rvalue (List.hd rvals)) in sprintf "(%s * %s)" expr expr); ) - strcmp "string", (fun (id,rvals) -> sprintf "str_pad('', %s, %s)" (sprint_rvalue (List.hd rvals)) (sprint_rvalue (List.nth rvals 1))); (* String(num,char) - use str_pad *) "strreverse", (direct_mapping "strrev"); "tan", (direct_mapping "tan"); "time", (map_to_literal "date('h:i:s A')"); Timer - number of seconds to seven decimal places since midnight "timeserial", (direct_mapping "mktime"); (* TimeValue(aanything) *) "trim", (direct_mapping "trim"); "ubound", (fun (id,rvals) -> sprintf "(count(%s)-1)" (sprint_rvalue (List.hd rvals))); "ucase", (direct_mapping "strtoupper"); VarType - something like gettype "weekday", (fun (id, rvals) -> sprintf "(%s + 1)" (format_date "w" (id,rvals))); "weekdayname", (implemented "weekdayname"); "year", (format_date "Y"); (* ================ RESPONSE ====================== *) "response.write", (direct_mapping "echo"); "response.end", (direct_mapping "exit"); (* ================ SERVER ====================== *) "server.execute", (direct_mapping "require"); "transfer", (fun (id,rvals) -> (direct_mapping "require" (id,rvals)) ^ ";\nexit();\n") ] = = = = = = = = = = = = = = = = XML = = = = = = = = = = = = = = = = = = set zzz = Server . CreateObject("Microsoft . XMLDOM " ) - > nothing zzz.load(filepath ) - > $ zzz = domxml_open_file(filepath ) ; = = = exact method matches : zzz . ) $ zzz->get_elements_by_tagname(xxx ) zzz . ChildNodes $ zzz->child_nodes ( ) zzz . NodeName $ zzz->node_name ( ) = = near matches zzz . GetAttribute(xxx ) $ zzz->attributes()[xxx ] zzz . Xml $ zzz->dump_node ( ) ================ XML ================== set zzz = Server.CreateObject("Microsoft.XMLDOM") -> nothing zzz.load(filepath) -> $zzz = domxml_open_file(filepath); === exact method matches: zzz.GetElementsByTagName(xxx) $zzz->get_elements_by_tagname(xxx) zzz.ChildNodes $zzz->child_nodes() zzz.NodeName $zzz->node_name() == near matches zzz.GetAttribute(xxx) $zzz->attributes()[xxx] zzz.Xml $zzz->dump_node() *) = = = = = = = = = = = = = = = = = intrinsics = = = = = = = = = = = = = = = = Application : not particularly useful Request : supported by PHP 's $ _ REQUEST [ ... ] , though a wrapper for safety may be a good idea . Also can use % .Form $ _ POST .QueryString $ _ GET .ServerVariables $ _ SERVER " http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF ] " also $ _ SERVER[PATH_INFO ] though I 'm not sure it is the same .. hopefully ! Response : .ContentType header("Content - type : " . xxx ) ; .End exit ( ) ; .Write echo ( xxx ) ; .Redirect header("Location : " . xxx ) ; more specifically header("Location : http:// " . $ _ SERVER['HTTP_HOST ' ] . dirname($_SERVER['PHP_SELF ' ] ) . " / " . xxx ) ; Server : .ScriptTimeout = seconds set_time_limit(seconds ) .CreateObject ( ... ) either ' new ' or special case .Execute ( ... ) include ( ... ) for suck require_once ( ... ) for good ( you can mix and match include / require + once / many ) .HtmlEncode ( xxx ) htmlspecialchars(xxx ) .MapPath(xxx ) the way the path is generated it will already be mapped , i hope .UrlEncode(xxx ) urlencode(xxx ) Session : .SessionID session_id ( ) .Timeout = xxx session_set_cookie_params(lifetime [ , ... ] ) .Contents("xxx " ) $ _ SESSION['xxx ' ] session_destroy ( ) .OnStart .OnEnd can hack it in with a require_once script that populates it if and only if it is n't already there ================= intrinsics ================ Application: not particularly useful Request: supported by PHP's $_REQUEST[...], though a wrapper for safety may be a good idea. Also can use % .Form $_POST .QueryString $_GET .ServerVariables $_SERVER PATH_INFO "http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]" also $_SERVER[PATH_INFO] though I'm not sure it is the same.. hopefully! Response: .ContentType header("Content-type: " . xxx); .End exit(); .Write echo( xxx ); .Redirect header("Location: " . xxx); more specifically header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . xxx ); Server: .ScriptTimeout = seconds set_time_limit(seconds) .CreateObject( ... ) either 'new' or special case .Execute( ... ) include(...) for suck require_once(...) for good (you can mix and match include/require + once/many) .HtmlEncode( xxx ) htmlspecialchars(xxx) .MapPath(xxx) the way the path is generated it will already be mapped, i hope .UrlEncode(xxx) urlencode(xxx) Session: .SessionID session_id() .Timeout = xxx session_set_cookie_params(lifetime [, ...]) .Contents("xxx") $_SESSION['xxx'] .Abandon session_destroy() .OnStart .OnEnd can hack it in with a require_once script that populates it if and only if it isn't already there *)
null
https://raw.githubusercontent.com/kennknowles/aspcc/951a91cc21e291b1d3c750bbbca7fa79209edd08/output/php.ml
ocaml
Printing functions Invalid_argument means the string has 0 length =========================================================================== For managing a symbol table and class definitions =========================================================================== Add all the built-in functions and intrinsic objects an AspAst.Ident in the symbol table represents a variable little helpers see if the current thing is registered as something other than a variable, and thus needs no dollar sign not quite, but could be an undeclared var ====== For tracking equivalencies for PHP ===== the adding of equivalent mappings occurs below, for declaration order convenience =========================================================================== For outputing the PHP =========================================================================== ============= vb_identifier ================ TODO: lookup of equivalencies if top then let format_func = get_php_equivalent (id_collapse id) or, if it is a function in the current scope "%s(%s)" ============= vb_rvalue ================ vbscript has nothing like PHP double-quote strings TODO: does not support bitwise operators convert a->b to (not a or b) since declaring member vars to be arrays must take place in the constructor, we need a function to scan a statement and output the constructor shit TODO: support preserving... probably by an extremely complex PHP function ========= vb_function ========= TODO: when assigning to the function name, set $returnvalue, and always return it ============== vb_assignment ================ This crazy match checks if the variable being assigned is the function of the current context unsafe use of != instead of < or > because step can be negative a safe workaround is to assign STEP to a var, and then have an overly complex condition that is > if it is negative or < if it is positive... before that happens we should do a match on inc to see if it is simple and we can determine it at compile time TODO: in class context, cannot assign this to array() | AspAst.Dim id -> sprint_dim context false id TODO: break with a number to bust out of many levels deep PHP doesn't have private/public | AspAst.MemberIdent id_list -> sprintf "var $%s;\n" (sprint_identifier id) TODO: here is where we can track the class type... i wish i knew some type-checking theory | _ -> "// Encountered unknown statement\n" ======================================================================== ================== Addition of existing mappings ======================= ======================================================================== note: 'direct_mapping' and 'implemented' do the same thing now, but this may not always be the case, so no merging the comma_map in this should be unneccessary since we can only convert a single value! TODO: raise an exception here note: this get_date is not a builtin, but a wrapper because php cannot parse this: getdate(..)['...'] TODO: raise an exception here ============ for converting vb function calls to php ========== btw 0 is false, true is -1, use default is -2 ============== BUILTIN FUNCTIONS ============== "createobject" not supported, it would be useless anyhow Eval sux "inputbox" client side only NOT is_int TODO: raise exception Replace(string,find,replace,start,count,compare) RGB - who cares ScriptEngineBuildVersion none of these maatter ScriptEngineMajorVersion ScriptEngineMinorVersion Sgn - the sign of a number String(num,char) - use str_pad TimeValue(aanything) ================ RESPONSE ====================== ================ SERVER ======================
open Printf let trim_eol s = try ignore (String.index s '\n'); String.sub s 0 ((String.length s) - 1) with | Not_found -> s | Invalid_argument _ -> s let indent indentation str = (Str.global_replace (Str.regexp "^") indentation (trim_eol str)) ^ "\n" TODO : this could be an entirely separate module for managing VB 's symbol table exception SymbolFound type symbol_variety = | Sub of AspAst.function_def | Function of AspAst.function_def the string option knows what type the var is , for OO lookup type the var is, for OO lookup *) | Class of AspAst.class_def | Const of AspAst.constant_definition | Dummy of unit type statement_context = | ToplevelContext | ClassContext | FunctionContext of string let symbol_table = Hashtbl.create 53 let scope_stack = Stack.create () let add_symbol name definition = Hashtbl.add symbol_table (String.lowercase name) definition; Hashtbl.add (Stack.top scope_stack) (String.lowercase name) () let find_symbol_in name sym_table = try let result = Hashtbl.find sym_table ( String.lowercase name ) in Some result with Not_found - > None try let result = Hashtbl.find sym_table (String.lowercase name) in Some result with Not_found -> None*) let find_symbol name = Hashtbl.find symbol_table name let push_scope () = Stack.push (Hashtbl.create 53) scope_stack let pop_scope () = Hashtbl.iter (fun key value -> Hashtbl.remove symbol_table key) (Stack.pop scope_stack) Todo : add param info ... add OO member symbol tables ... add past the letter ' a ' let _ = push_scope (); List.iter (fun (x,y) -> add_symbol x y) [ "Abs", Function ("Abs", [], []); "Array", Function ("Array", [], []); "Asc", Function ("Asc", [], []); "Atn", Function ("Atn", [], []); "CBool", Function ("CBool", [], []); "CByte", Function ("CByte", [], []); "CCur", Function ("CCur", [], []); "CDate", Function ("CDate", [], []); "CDbl", Function ("CDbl", [], []); "Chr", Function ("Chr", [], []); "CInt", Function ("CInt", [], []); "CLng", Function ("CLng", [], []); "Cos", Function ("Cos", [], []) ]; List.iter (fun (x, y) -> add_symbol x (Variable (x, None))) [ "Response", "AspResponse"; "Request", "AspRequest"; "Server", "AspServer"; "Session", "AspSession" ] let is_variable symbol = try ( match find_symbol symbol with | Variable _ -> true | _ -> false ) with let concat_map ?str func the_list = String.concat (match str with | Some c -> c | None -> "") (List.map func the_list) let comma_map func the_list = concat_map ~str:", " func the_list let arrow_map func the_list = concat_map ~str:"->" func the_list type php_mapping_function = (AspAst.identifier -> string) let equivalency_table = Hashtbl.create 53 let get_php_equivalent vb_id = Hashtbl.find equivalency_table (String.lowercase vb_id) let add_equivalency vb_func sprint_func = Hashtbl.add equivalency_table (String.lowercase vb_func) sprint_func let rec sprint_identifier ?(top : bool = true) id = match id with | AspAst.AtomicId s -> (if is_variable s then "$" else "") ^ s | AspAst.Dot (base,member) -> sprintf "%s->%s" (sprint_identifier base) member | AspAst.Indices (base,indices) -> sprintf "%s[%s]" (sprint_identifier base) (comma_map sprint_rvalue indices) and sprint_rvalue rval = match rval with | AspAst.Int (AspAst.Dec, i) -> sprintf "%li" i | AspAst.Int (AspAst.Hex, h) -> sprintf "%lx" h | AspAst.Int (AspAst.Oct, o) -> sprintf "%lo" o | AspAst.Float f -> sprintf "%f" f | AspAst.Bool b -> if b then "TRUE" else "FALSE" Re - implement these later - they need to be converted to the new AST layout | AspAst . Concat ( v1 , v2 ) - > sprintf " ( % s . % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Negative i - > sprintf " -%s " ( sprint_rvalue i ) | AspAst . Add ( v1 , v2 ) - > sprintf " ( % s + % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Subtract ( v1 , v2 ) - > sprintf " ( % s - % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Mult ( v1 , v2 ) - > sprintf " ( % s * % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . IntDiv ( v1 , v2 ) - > sprintf " ( % s / % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Div ( v1 , v2 ) - > sprintf " ( ( 1.0 * % s ) / % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Exp ( v1 , v2 ) - > sprintf " ( % s ^ % s ) " ( sprint_rvalue v1 ) ( sprint_rvalue v2 ) | AspAst . Not n - > sprintf " ! ( % s ) " ( sprint_rvalue n ) ( * TODO : does not support bitwise operators Re-implement these later - they need to be converted to the new AST layout | AspAst.Concat (v1, v2) -> sprintf "(%s . %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Negative i -> sprintf "-%s" (sprint_rvalue i) | AspAst.Add (v1, v2) -> sprintf "(%s + %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Subtract (v1, v2) -> sprintf "(%s - %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Mult (v1, v2) -> sprintf "(%s * %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.IntDiv (v1, v2) -> sprintf "(%s / %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Div (v1, v2) -> sprintf "((1.0 * %s) / %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Exp (v1, v2) -> sprintf "(%s ^ %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Not n -> sprintf "!(%s)" (sprint_rvalue n) | AspAst.And (v1, v2) -> sprintf "(%s && %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Or (v1, v2) -> sprintf "(%s || %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Xor (v1, v2) -> sprintf "(%s xor %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Imp (v1, v2) -> sprintf "(!%s || %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Eqv (v1, v2) -> sprintf "(%s == %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Equals (v1, v2) -> sprintf "(%s == %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.NotEquals (v1, v2) -> sprintf "(%s != %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.LessEqual (v1, v2) -> sprintf "(%s <= %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.GreaterEqual (v1, v2) -> sprintf "(%s >= %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Less (v1, v2) -> sprintf "(%s < %s)" (sprint_rvalue v1) (sprint_rvalue v2) | AspAst.Greater (v1, v2) -> sprintf "(%s > %s)" (sprint_rvalue v1) (sprint_rvalue v2) *) | AspAst.Identifier identifier -> sprint_identifier identifier | _ -> "/* Unknown expression */" let rec sprint_dim_indices size_list = match size_list with | [] -> "''" | size::rest -> sprintf "array_pad(array(), %s, %s)" (sprint_rvalue size) (sprint_dim_indices rest) let sprint_dim_tail id = match id with | AspAst.Indices (base, []) -> sprintf "%s = array();\n" (sprint_identifier base) | AspAst.Indices (base, size) -> sprintf "%s = %s;\n" (sprint_identifier base) (sprint_dim_indices size) | _ -> "" let sprint_index_free_id id = match id with | AspAst.Indices (base, indices) -> sprint_identifier base | x -> sprint_identifier x let sprint_constructor_info (line_num, statement) = match statement with | AspAst . MemberDef ( _ , _ , ( AspAst . MemberIdent i d ) ) | AspAst . Dim i d - > sprint_dim_tail i d | AspAst.Dim id -> sprint_dim_tail id *) | _ -> "" let rec sprint_function ((name, params, statements) : AspAst.function_def) = "" sprintf " function % s(%s)\n{\n%s}\n " name ( String.concat " , " params ) ( indent " \t " ( " $ returnvalue = '' ; " ^ ( concat_map ( sprint_statement ~context:(FunctionContext name ) ) statements ) ^ " return ( $ returnvalue ) ; ) ) (indent "\t" ("$returnvalue = '';\n" ^ (concat_map (sprint_statement ~context:(FunctionContext name)) statements) ^ "return ( $returnvalue );\n"))*) and sprint_assignment context (id, rval) = (match context, id with | (FunctionContext funcname), (AspAst.AtomicId varname) when (funcname=varname) -> "$returnvalue" | _, _ -> (sprint_identifier id)) ^ " = " ^ (sprint_rvalue rval) ^ ";\n"; and sprint_dim context preserve id = match context with | ClassContext -> sprintf "var %s;\n" (sprint_index_free_id id) | _ -> sprint_dim_tail id and sprint_select context (rval, options) = sprintf "switch(%s)\n{\n%s}" (sprint_rvalue rval) (indent "\t" (concat_map (sprint_select_item context) options)) and sprint_select_item context (item, statements) = (match item with | AspAst.SelectValue rvals -> "case " ^ (concat_map ~str:":\ncase " sprint_rvalue rvals) ^ ":\n" | AspAst.SelectElse -> "default:\n") ^ (indent "\t" ( (concat_map (sprint_statement ~context:context) statements) ^ "break;\n")) context is probably needed : just an ( AspAst.vb_compound_statement Stack.t ) , and is needed for With since php has no such thing , and Exit since we might need a numeric argument to break for With since php has no such thing, and Exit since we might need a numeric argument to break *) and sprint_statement ?(context = ToplevelContext) (line_num, statement) = match statement with " // empty statement " | AspAst.Assignment (a_id, a_val) -> sprint_assignment context (a_id, a_val) | AspAst.Call id -> (sprint_identifier id) ^ ";\n" | AspAst.Class (name, statements) -> sprintf "class %s { \n%s }\n" name (indent "\t" ( (String.concat "" (List.map (sprint_statement ~context:ClassContext) statements)) ^ (sprintf "function %s()\n{\n%s}\n" name (indent "\t" (String.concat "" (List.map sprint_constructor_info statements)))))) | AspAst.Comment c -> "// " ^ c | AspAst.CompoundStatement (compound_type, statements) -> (match compound_type with | AspAst.For (var, start, finish, inc) -> sprintf "for(%s = %s; %s != %s; %s += %s)\n" var (sprint_rvalue start) var (sprint_rvalue finish) var (sprint_rvalue inc) | AspAst.ForEach (name, collection) -> sprintf "foreach(%s as $%s)\n" (sprint_rvalue collection) name | AspAst.While expr -> sprintf "while(%s)\n" (sprint_rvalue expr) | AspAst.With lval -> "" ) ^ "{\n" ^ (indent "\t" (String.concat "" (List.map sprint_statement statements))) ^ "}\n" | AspAst.Const (name, rval) -> sprintf "define(\"%s\", %s);\n" name (sprint_rvalue rval) | AspAst.Erase (var) -> (sprint_identifier var) ^ " = '';\n" | AspAst.Execute (rval) -> "// WARNING: the string passed to this eval has *not* been converted!\n" ^ "eval(" ^ (sprint_rvalue rval) ^ ");\n" | AspAst.Exit target -> (match target with | `Function -> "return ( $returnvalue );\n" | `Sub -> "return;\n" | _ -> "break;\n") | AspAst.Function func_def -> sprint_function func_def | AspAst.If (predicate, then_block, else_block) -> sprintf "if ( %s ) \n{\n%s}\nelse\n{\n%s}\n" (sprint_rvalue predicate) (indent "\t" (String.concat "" (List.map sprint_statement then_block))) (indent "\t" (String.concat "" (List.map sprint_statement else_block))) | AspAst.MemberDef (access, default, memberstatement) -> (match memberstatement with | AspAst.MemberFunction x | AspAst.MemberSub x -> sprint_function x | AspAst.PropertyLet (name, params, statements) -> sprint_function (name ^ "_let", params, statements) | AspAst.PropertyGet (name, params, statements) -> sprint_function (name ^ "_get", params, statements) | AspAst.PropertySet (name, params, statements) -> sprint_function (name ^ "_set", params, statements)) | AspAst . | AspAst . OnErrorGotoZero - > " // error handling ? bah!\n " "// error handling? bah!\n" *) | AspAst.OptionExplicit -> "// option explicit? i guess i could look it up, bleh\n" | AspAst.Randomize -> "list ($r_usec, $r_sec) = explode(' ', microtime());\n" ^ "srand((float)$r_sec + (($float) $r_usec * 100000));\n" | AspAst.ReDim (preserve, id_list) -> List.map ( sprint_dim context preserve ) id_list | AspAst.Select (rval, options) -> sprint_select context (rval, options) | AspAst.Set (id, rval) -> sprint_assignment context (id, rval) | AspAst.Sub func_def -> sprint_function func_def | AspAst.SubCall (id, rvals) -> sprint_identifier (AspAst.Indices (id, rvals)) ^ ";\n" let sprint_page page = String.concat " " ( List.map ( function | AspAst . Html html - > html | AspAst . " < ? " ^ ( indent " \t " ( String.concat " " ( List.map sprint_statement vb ) ) ) ^ " \n ? > " ) page ) "" (List.map (function | AspAst.Html html -> html | AspAst.VbScript vb -> "<?" ^ (indent "\t" (String.concat "" (List.map sprint_statement vb))) ^ "\n?>") page)*) let print_page page = print_string (sprint_page page) let direct_mapping php_func = (fun (_, rvals) -> sprintf "%s(%s)" php_func (comma_map sprint_rvalue rvals)) let map_to_cast php_type = (fun (_, rvals) -> sprintf "((%s) %s)" php_type (comma_map sprint_rvalue rvals)) let map_to_literal php_code = (fun (_, rvals) -> php_code) let implemented php_func = (fun (_, rvals) -> sprintf "%s(%s)" php_func (comma_map sprint_rvalue rvals)) let format_dateserial (_, rvals) = match rvals with | year::month::day::_ -> sprintf "mktime(0, 0, 0, %s, %s, %s)" (sprint_rvalue month) (sprint_rvalue day) (sprint_rvalue year) let format_date datepart (_, rvals) = sprintf "date('%s', datevalue(%s))" datepart (comma_map sprint_rvalue rvals) let format_instr (_, rvals) = match rvals with | haystack::needle::[] -> sprintf "instr(%s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) | start::haystack::needle::[] -> sprintf "instr(%s, %s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) (sprint_rvalue start) | start::haystack::needle::compare::_ -> sprintf "instr(%s, %s, %s, %s)" (sprint_rvalue haystack) (sprint_rvalue needle) (sprint_rvalue start) (sprint_rvalue compare) Comprehensive list of VBscript functions . There are four categories of functions : * Direct mappings * Functions implemented in PHP in asp_implementations.php * Functions that make no sense * Functions that are unsupported at this time There are four categories of functions: * Direct mappings * Functions implemented in PHP in asp_implementations.php * Functions that make no sense * Functions that are unsupported at this time *) TODO : make implementations for casts , which do the checking the functions would ... though they error all the time in horrendous ways :( VbScript functions would... though they error all the time in horrendous ways :( *) let _ = List.iter (fun (x, y) -> add_equivalency x y) [ "abs", (direct_mapping "abs"); "array", (direct_mapping "array"); "asc", (direct_mapping "ord"); "atn", (direct_mapping "atan"); "cbool", (map_to_cast "bool"); "cbyte", (map_to_cast "int"); "ccur", (map_to_cast "double"); "cdate", (implemented "datevalue"); "cdbl", (map_to_cast "double"); "chr", (direct_mapping "chr"); "cint", (map_to_cast "int"); "clng", (map_to_cast "int"); "cos", (direct_mapping "cos"); "csng", (map_to_cast "float"); "cstr", (map_to_cast "string"); "date", (map_to_literal "date('m/d/Y')"); "dateadd", (implemented "dateadd"); "datediff", (implemented "datediff"); "datepart", (implemented "datepart"); "dateserial", format_dateserial; "datevalue", (implemented "datevalue"); "day", (format_date "d"); "exp", (direct_mapping "exp"); "filter", (implemented "filter"); "fix", (implemented "fix"); "formatcurrency", (fun (id,rvals) -> "$" ^ (implemented "formatnumber" (id,rvals))); "formatdatetime", (implemented "formatdatetime"); "formatnumber", (implemented "formatnumber"); "formatpercent", (implemented "formatpercent"); GetLocale returns some unique i d number for locle LCID GetObject this is some fucked up thing GetRef dunno wtfg "hex", (direct_mapping "dechex"); "hour", (format_date "H"); "instr", format_instr; "instrrev", (implemented "instrrev"); "int", (direct_mapping "floor"); "isarray", (direct_mapping "is_array"); "isdate", (implemented "isdate"); "isempty", (fun (id,rvals) -> sprintf "!%s" (sprint_rvalue (List.hd rvals))); "isnull", (fun (id,rvals) -> sprintf "!%s" (sprint_rvalue (List.hd rvals))); "isobject", (direct_mapping "is_object"); "join", (fun (id,rvals) -> match rvals with | val1::val2::[] -> sprintf "join(%s, %s)" (sprint_rvalue val2) (sprint_rvalue val1) "lbound", (map_to_literal "0"); "lcase", (direct_mapping "strtolower"); "left", (implemented "left"); "len", (direct_mapping "strlen"); LoadPicture - nonsense "log", (direct_mapping "log"); "ltrim", (direct_mapping "ltrim"); "mid", (direct_mapping "substr"); "minute", (format_date "i"); "month", (format_date "m"); "monthname", (implemented "monthname"); MsgBox - nonsense "now", (map_to_literal "date('D M d H:i:s Y')"); "oct", (direct_mapping "decoct"); "rght", (implemented "right"); "rnd", (fun (id,rvals) -> "(rand()/(float)getrandmax())"); "round", (direct_mapping "round"); "rtrim", (direct_mapping "rtrim"); ScriptEngine - returns language , i.e. "second", (format_date "s"); SetLocale more LCID stuff "sgn", (fun (id,rvals) -> let v = (sprint_rvalue (List.hd rvals)) in sprintf "(abs(%s)/%s)" v v); "sin", (direct_mapping "sin"); "space", (fun (id,rvals) -> sprintf "str_pad('', %s)" (sprint_rvalue (List.hd rvals))); Split(expression , delim , count , compare ) "sqr", (fun (id,rvals) -> let expr = (sprint_rvalue (List.hd rvals)) in sprintf "(%s * %s)" expr expr); ) - strcmp "string", (fun (id,rvals) -> sprintf "str_pad('', %s, %s)" (sprint_rvalue (List.hd rvals)) (sprint_rvalue (List.nth rvals 1))); "strreverse", (direct_mapping "strrev"); "tan", (direct_mapping "tan"); "time", (map_to_literal "date('h:i:s A')"); Timer - number of seconds to seven decimal places since midnight "timeserial", (direct_mapping "mktime"); "trim", (direct_mapping "trim"); "ubound", (fun (id,rvals) -> sprintf "(count(%s)-1)" (sprint_rvalue (List.hd rvals))); "ucase", (direct_mapping "strtoupper"); VarType - something like gettype "weekday", (fun (id, rvals) -> sprintf "(%s + 1)" (format_date "w" (id,rvals))); "weekdayname", (implemented "weekdayname"); "year", (format_date "Y"); "response.write", (direct_mapping "echo"); "response.end", (direct_mapping "exit"); "server.execute", (direct_mapping "require"); "transfer", (fun (id,rvals) -> (direct_mapping "require" (id,rvals)) ^ ";\nexit();\n") ] = = = = = = = = = = = = = = = = XML = = = = = = = = = = = = = = = = = = set zzz = Server . CreateObject("Microsoft . XMLDOM " ) - > nothing zzz.load(filepath ) - > $ zzz = domxml_open_file(filepath ) ; = = = exact method matches : zzz . ) $ zzz->get_elements_by_tagname(xxx ) zzz . ChildNodes $ zzz->child_nodes ( ) zzz . NodeName $ zzz->node_name ( ) = = near matches zzz . GetAttribute(xxx ) $ zzz->attributes()[xxx ] zzz . Xml $ zzz->dump_node ( ) ================ XML ================== set zzz = Server.CreateObject("Microsoft.XMLDOM") -> nothing zzz.load(filepath) -> $zzz = domxml_open_file(filepath); === exact method matches: zzz.GetElementsByTagName(xxx) $zzz->get_elements_by_tagname(xxx) zzz.ChildNodes $zzz->child_nodes() zzz.NodeName $zzz->node_name() == near matches zzz.GetAttribute(xxx) $zzz->attributes()[xxx] zzz.Xml $zzz->dump_node() *) = = = = = = = = = = = = = = = = = intrinsics = = = = = = = = = = = = = = = = Application : not particularly useful Request : supported by PHP 's $ _ REQUEST [ ... ] , though a wrapper for safety may be a good idea . Also can use % .Form $ _ POST .QueryString $ _ GET .ServerVariables $ _ SERVER " http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF ] " also $ _ SERVER[PATH_INFO ] though I 'm not sure it is the same .. hopefully ! Response : .ContentType header("Content - type : " . xxx ) ; .End exit ( ) ; .Write echo ( xxx ) ; .Redirect header("Location : " . xxx ) ; more specifically header("Location : http:// " . $ _ SERVER['HTTP_HOST ' ] . dirname($_SERVER['PHP_SELF ' ] ) . " / " . xxx ) ; Server : .ScriptTimeout = seconds set_time_limit(seconds ) .CreateObject ( ... ) either ' new ' or special case .Execute ( ... ) include ( ... ) for suck require_once ( ... ) for good ( you can mix and match include / require + once / many ) .HtmlEncode ( xxx ) htmlspecialchars(xxx ) .MapPath(xxx ) the way the path is generated it will already be mapped , i hope .UrlEncode(xxx ) urlencode(xxx ) Session : .SessionID session_id ( ) .Timeout = xxx session_set_cookie_params(lifetime [ , ... ] ) .Contents("xxx " ) $ _ SESSION['xxx ' ] session_destroy ( ) .OnStart .OnEnd can hack it in with a require_once script that populates it if and only if it is n't already there ================= intrinsics ================ Application: not particularly useful Request: supported by PHP's $_REQUEST[...], though a wrapper for safety may be a good idea. Also can use % .Form $_POST .QueryString $_GET .ServerVariables $_SERVER PATH_INFO "http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]" also $_SERVER[PATH_INFO] though I'm not sure it is the same.. hopefully! Response: .ContentType header("Content-type: " . xxx); .End exit(); .Write echo( xxx ); .Redirect header("Location: " . xxx); more specifically header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . xxx ); Server: .ScriptTimeout = seconds set_time_limit(seconds) .CreateObject( ... ) either 'new' or special case .Execute( ... ) include(...) for suck require_once(...) for good (you can mix and match include/require + once/many) .HtmlEncode( xxx ) htmlspecialchars(xxx) .MapPath(xxx) the way the path is generated it will already be mapped, i hope .UrlEncode(xxx) urlencode(xxx) Session: .SessionID session_id() .Timeout = xxx session_set_cookie_params(lifetime [, ...]) .Contents("xxx") $_SESSION['xxx'] .Abandon session_destroy() .OnStart .OnEnd can hack it in with a require_once script that populates it if and only if it isn't already there *)
c325029cef28adbb705aff37b37b6874d41b7bc598c131b253dcf99fc08176cd
wereHamster/mole
Image.hs
module Data.Mole.Builder.Image where import Control.Concurrent.STM import qualified Data.Set as S import qualified Data.ByteString as BS import qualified Data.Text as T import Data.Maybe import Data.Time import Text.Printf import Data.Mole.Types import Data.Mole.Builder.Internal.Fingerprint import qualified Network.Kraken as K import System.Environment import System.FilePath import System.Directory import System.Posix.Files imageBuilder :: String -> String -> Handle -> AssetId -> IO Builder imageBuilder src contentType h aId = do originalBody <- BS.readFile src let fp = contentHash originalBody cacheDir <- lookupEnv "XDG_CACHE_DIR" let cacheName = (fromMaybe ".cache" cacheDir) </> "kraken" </> T.unpack fp inCache <- fileExist cacheName body <- if inCache then do BS.readFile cacheName else case krakenH h of Nothing -> return originalBody Just kh -> do atomically $ takeTMVar (lock h) logMessage' h aId $ "Compressing image with Kraken..." res <- K.compressImage kh (K.Options Nothing Nothing Nothing) originalBody case res of Left _ -> do atomically $ putTMVar (lock h) () return originalBody Right body -> do createDirectoryIfMissing True $ takeDirectory cacheName BS.writeFile cacheName body atomically $ putTMVar (lock h) () return body let ol = BS.length originalBody let nl = BS.length body let ratio :: Double ratio = (100.0 * ((fromIntegral nl :: Double) / (fromIntegral ol))) logMessage' h aId $ concat [ "Compressed image from " , show ol , " to " , show nl , " bytes (" , printf "%.2f" ratio , "%)" ] return $ Builder { assetSources = S.singleton src , assetDependencies = S.empty , packageAsset = const $ Right $ Result (PublicIdentifier $ fingerprint body src) $ Just (body, contentType) , sourceFingerprint = originalBody } logMessage' :: Handle -> AssetId -> String -> IO () logMessage' h aId msg = do now <- getCurrentTime atomically $ writeTQueue (messages h) (Message now aId msg)
null
https://raw.githubusercontent.com/wereHamster/mole/f9476a160d1e35fc720498334d292b41658f9d72/src/Data/Mole/Builder/Image.hs
haskell
module Data.Mole.Builder.Image where import Control.Concurrent.STM import qualified Data.Set as S import qualified Data.ByteString as BS import qualified Data.Text as T import Data.Maybe import Data.Time import Text.Printf import Data.Mole.Types import Data.Mole.Builder.Internal.Fingerprint import qualified Network.Kraken as K import System.Environment import System.FilePath import System.Directory import System.Posix.Files imageBuilder :: String -> String -> Handle -> AssetId -> IO Builder imageBuilder src contentType h aId = do originalBody <- BS.readFile src let fp = contentHash originalBody cacheDir <- lookupEnv "XDG_CACHE_DIR" let cacheName = (fromMaybe ".cache" cacheDir) </> "kraken" </> T.unpack fp inCache <- fileExist cacheName body <- if inCache then do BS.readFile cacheName else case krakenH h of Nothing -> return originalBody Just kh -> do atomically $ takeTMVar (lock h) logMessage' h aId $ "Compressing image with Kraken..." res <- K.compressImage kh (K.Options Nothing Nothing Nothing) originalBody case res of Left _ -> do atomically $ putTMVar (lock h) () return originalBody Right body -> do createDirectoryIfMissing True $ takeDirectory cacheName BS.writeFile cacheName body atomically $ putTMVar (lock h) () return body let ol = BS.length originalBody let nl = BS.length body let ratio :: Double ratio = (100.0 * ((fromIntegral nl :: Double) / (fromIntegral ol))) logMessage' h aId $ concat [ "Compressed image from " , show ol , " to " , show nl , " bytes (" , printf "%.2f" ratio , "%)" ] return $ Builder { assetSources = S.singleton src , assetDependencies = S.empty , packageAsset = const $ Right $ Result (PublicIdentifier $ fingerprint body src) $ Just (body, contentType) , sourceFingerprint = originalBody } logMessage' :: Handle -> AssetId -> String -> IO () logMessage' h aId msg = do now <- getCurrentTime atomically $ writeTQueue (messages h) (Message now aId msg)
dc2b6f3379d2c3cf7f65a2d6ad316aa706007f27893d6757056bffe4cf4ac329
tuura/pangraph
Main.hs
module Main where import GraphML import Show import Containers import TestPangraph import FGL import Gml import Pajek import Test.HUnit main :: IO Counts main = (runTestTT . TestList . concat) [containersTests, fglTests, graphmlTests, showTests, pangraphTests, gmlTests, pajekTests]
null
https://raw.githubusercontent.com/tuura/pangraph/ca896f25e5b49e0f59b69367125d01a2aa42beb3/test/Main.hs
haskell
module Main where import GraphML import Show import Containers import TestPangraph import FGL import Gml import Pajek import Test.HUnit main :: IO Counts main = (runTestTT . TestList . concat) [containersTests, fglTests, graphmlTests, showTests, pangraphTests, gmlTests, pajekTests]
ce59fd255de95c6f9e92cd544b86f38c537a44bda19b9f0582f2f73c9aeed9ee
oscoin/oscoin
Abstract.hs
-- | Types and type families used by all transaction types. -- module Oscoin.Data.Tx.Abstract where import Oscoin.Prelude -- | A transaction validation error. type family TxValidationError c tx -- | The output of applying a transaction to the state. type family TxOutput c tx -- | The input and output of transaction application. type family TxState c tx | The validation function used by for example the ' ' . type TxValidator c tx = tx -> Either (TxValidationError c tx) ()
null
https://raw.githubusercontent.com/oscoin/oscoin/2eb5652c9999dd0f30c70b3ba6b638156c74cdb1/src/Oscoin/Data/Tx/Abstract.hs
haskell
| Types and type families used by all transaction types. | A transaction validation error. | The output of applying a transaction to the state. | The input and output of transaction application.
module Oscoin.Data.Tx.Abstract where import Oscoin.Prelude type family TxValidationError c tx type family TxOutput c tx type family TxState c tx | The validation function used by for example the ' ' . type TxValidator c tx = tx -> Either (TxValidationError c tx) ()
113c90db54bc4317829f0d8c04b8337a18370b48bbef9035f8785c8227085272
thi-ng/demos
project.clj
(defproject ws-ldn-8-ex06 "0.1.0-SNAPSHOT" :description "thi.ng Clojurescript workshop WS-LDN-8" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.5.3" :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.8.51"] [org.clojure/core.async "0.2.374" :exclusions [org.clojure/tools.reader]] [thi.ng/geom "0.0.1158-SNAPSHOT"] [thi.ng/domus "0.3.0-SNAPSHOT"] [reagent "0.5.1"] [cljsjs/localforage "1.3.1-0"]] :plugins [[lein-figwheel "0.5.0-6"] [lein-cljsbuild "1.1.3" :exclusions [[org.clojure/clojure]]]] :source-paths ["src"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target"] :cljsbuild {:builds [{:id "dev1" :source-paths ["src"] :figwheel true :compiler {:main ex06.core :asset-path "js/compiled/out" :output-to "resources/public/js/compiled/app.js" :output-dir "resources/public/js/compiled/out" :source-map-timestamp true}} {:id "min" :source-paths ["src"] :compiler {:output-to "resources/public/js/compiled/app.js" :optimizations :advanced :pretty-print false}}]} :figwheel {:css-dirs ["resources/public/css"] ;; :ring-handler hello_world.server/handler })
null
https://raw.githubusercontent.com/thi-ng/demos/048cd131099a7db29be56b965c053908acad4166/ws-ldn-8/day3/ex06/project.clj
clojure
:ring-handler hello_world.server/handler
(defproject ws-ldn-8-ex06 "0.1.0-SNAPSHOT" :description "thi.ng Clojurescript workshop WS-LDN-8" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.5.3" :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.8.51"] [org.clojure/core.async "0.2.374" :exclusions [org.clojure/tools.reader]] [thi.ng/geom "0.0.1158-SNAPSHOT"] [thi.ng/domus "0.3.0-SNAPSHOT"] [reagent "0.5.1"] [cljsjs/localforage "1.3.1-0"]] :plugins [[lein-figwheel "0.5.0-6"] [lein-cljsbuild "1.1.3" :exclusions [[org.clojure/clojure]]]] :source-paths ["src"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target"] :cljsbuild {:builds [{:id "dev1" :source-paths ["src"] :figwheel true :compiler {:main ex06.core :asset-path "js/compiled/out" :output-to "resources/public/js/compiled/app.js" :output-dir "resources/public/js/compiled/out" :source-map-timestamp true}} {:id "min" :source-paths ["src"] :compiler {:output-to "resources/public/js/compiled/app.js" :optimizations :advanced :pretty-print false}}]} :figwheel {:css-dirs ["resources/public/css"] })
37baaab74fd6d7cb3504fffad5a2ed0fbf6763a032a752564e553accef788a26
styx/Raincat
Graphics.hs
# LANGUAGE CPP # module Nxt.Graphics (begin, end, initWindow, initGraphics, toGLdouble, fromGLdouble, loadTexture, freeTexture, drawTexture, drawTextureFlip, drawString, drawRect, drawPoly, worldTransform, cycleTextures, cycleTextures2, repeatTexturesN) where import Control.Monad import Graphics.UI.GLUT as GLUT hiding (windowSize, windowTitle) import Graphics.Rendering.OpenGL as GL import qualified SDL.Image as SDLImage hiding (loadTexture) import qualified SDL.Vect import qualified SDL.Video import Nxt.Types hiding (rectX, rectY, rectWidth, rectHeight) import Unsafe.Coerce -- initWindow initWindow :: Size -> String -> IO () initWindow windowSize windowTitle = do _ <- getArgsAndInitialize initialWindowSize $= windowSize initialDisplayMode $= [DoubleBuffered] _ <- createWindow windowTitle return () -- initGraphics initGraphics :: GLdouble -> GLdouble -> IO () initGraphics screenResWidth screenResHeight = do blend $= Enabled blendFunc $= (GL.SrcAlpha, OneMinusSrcAlpha) shadeModel $= Flat matrixMode $= Projection loadIdentity ortho 0.0 screenResWidth 0.0 screenResHeight (-1.0) 0.0 matrixMode $= Modelview 0 return () -- begin begin :: IO () begin = clear [ColorBuffer, DepthBuffer] -- end end :: IO () end = do swapBuffers flush -- toGLdouble toGLdouble :: a -> GLdouble toGLdouble = unsafeCoerce -- fromGLdouble fromGLdouble :: a -> Double fromGLdouble = unsafeCoerce -- loadTexture (only specified to load PNGs) loadTexture :: String -> IO Nxt.Types.Texture loadTexture textureFilePath = do surface <- SDLImage.load textureFilePath SDL.Vect.V2 rawWidth rawHeight <- SDL.Video.surfaceDimensions surface let width = fromIntegral rawWidth let height = fromIntegral rawHeight let surfaceSize = TextureSize2D width height textureObj <- liftM head (genObjectNames 1) textureBinding Texture2D $= Just textureObj textureWrapMode Texture2D S $= (Repeated, Repeat) textureWrapMode Texture2D T $= (Repeated, Repeat) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) surfacePixels <- SDL.Video.surfacePixels surface let pixelData = PixelData RGBA UnsignedByte surfacePixels texImage2D #if MIN_VERSION_OpenGL(2,9,0) Texture2D #else Nothing #endif NoProxy 0 RGBA' surfaceSize 0 pixelData SDL.Video.freeSurface surface return (Nxt.Types.Texture width height textureObj) -- freeTexture freeTexture :: Nxt.Types.Texture -> IO () freeTexture tex = deleteObjectNames [textureObject tex] -- drawTexture drawTexture :: Double -> Double -> Nxt.Types.Texture -> GLdouble -> IO () drawTexture x y tex alpha = drawTextureFlip x y tex alpha False drawTextureFlip drawTextureFlip :: Double -> Double -> Nxt.Types.Texture -> GLdouble -> Bool -> IO () drawTextureFlip x y tex alpha fliped = do texture Texture2D $= Enabled textureBinding Texture2D $= Just (textureObject tex) let texWidth = fromIntegral $ textureWidth tex texHeight = fromIntegral $ textureHeight tex let texCoord2f = texCoord :: TexCoord2 GLdouble -> IO () vertex3f = vertex :: Vertex3 GLdouble -> IO () color4f = color :: Color4 GLdouble -> IO () col = color4f (Color4 (1.0::GLdouble) (1.0::GLdouble) (1.0::GLdouble) alpha) let texCoordX = if fliped then (-1) else 1 x' = toGLdouble x y' = toGLdouble y renderPrimitive Quads $ do texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 x' y' 0.0); col texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 x' (y' + texHeight) 0.0); col texCoord2f (TexCoord2 texCoordX 0); vertex3f (Vertex3 (x' + texWidth) (y' + texHeight) 0.0); col texCoord2f (TexCoord2 texCoordX 1); vertex3f (Vertex3 (x' + texWidth) y' 0.0); col texture Texture2D $= Disabled drawString ( using Helvetica 12pt font ) drawString :: GLfloat -> GLfloat -> String -> Color4 GLfloat -> IO () drawString x y string col = do color col currentRasterPosition $= Vertex4 x y (0.0::GLfloat) (1.0::GLfloat) renderString Helvetica12 string -- drawRect drawRect :: Nxt.Types.Rect -> Color4 GLdouble -> IO () drawRect (Rect rectX rectY rectWidth rectHeight) rectColor = do let rX = toGLdouble rectX rY = toGLdouble rectY rW = toGLdouble rectWidth rH = toGLdouble rectHeight rectVertices = [Vertex3 rX rY 0.0, Vertex3 (rX + rW) rY 0.0, Vertex3 (rX + rW) (rY + rH) 0.0, Vertex3 rX (rY + rH) 0.0] renderPrimitive Quads $ do mapM_ color [rectColor] mapM_ vertex rectVertices -- drawPoly drawPoly :: Nxt.Types.Poly -> Color4 GLdouble -> IO () drawPoly (Poly _ points) polyColor = do let polyVerts = map (\(x,y) -> Vertex3 (toGLdouble x) (toGLdouble y) (0.0::GLdouble)) points renderPrimitive Polygon $ do mapM_ color [polyColor] mapM_ vertex polyVerts worldTransform worldTransform :: Double -> Double -> IO () worldTransform worldX worldY = do loadIdentity translate (Vector3 (toGLdouble worldX) (toGLdouble worldY) 0.0) -- cycleTextures cycleTextures :: String -> Int -> Int -> IO [Nxt.Types.Texture] cycleTextures filePath frames frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] let textures = cycle $ foldr ((++) . replicate frameTime) [] texLists return textures -- cycleTextures2 cycleTextures2 :: String -> Int -> Int -> Int -> IO [Nxt.Types.Texture] cycleTextures2 filePath frames lastFrame frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] texLists2 <- Nxt.Graphics.loadTexture (filePath ++ show lastFrame ++ ".png"); let textures = foldr ((++) . replicate frameTime) (repeat texLists2) texLists return textures -- repeatTexturesN repeatTexturesN :: String -> Int -> Int -> Int -> Int -> Int -> Int -> IO [Nxt.Types.Texture] repeatTexturesN filePath frames startRepeat endRepeat nRepeats lastFrame frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] repeatTexLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [startRepeat..endRepeat] endTexLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [(endRepeat + 1)..lastFrame] let textures = replicate 60 (last endTexLists) ++ foldr ((++) . replicate frameTime) [] texLists ++ take (nRepeats * frameTime * (endRepeat - startRepeat)) (cycle $ foldr ((++) . replicate frameTime) [] repeatTexLists) ++ foldr ((++) . replicate frameTime) (repeat $ last endTexLists) endTexLists return textures
null
https://raw.githubusercontent.com/styx/Raincat/49b688c73335c9a4090708bc75f6af9575a65670/src/Nxt/Graphics.hs
haskell
initWindow initGraphics begin end toGLdouble fromGLdouble loadTexture (only specified to load PNGs) freeTexture drawTexture drawRect drawPoly cycleTextures cycleTextures2 repeatTexturesN
# LANGUAGE CPP # module Nxt.Graphics (begin, end, initWindow, initGraphics, toGLdouble, fromGLdouble, loadTexture, freeTexture, drawTexture, drawTextureFlip, drawString, drawRect, drawPoly, worldTransform, cycleTextures, cycleTextures2, repeatTexturesN) where import Control.Monad import Graphics.UI.GLUT as GLUT hiding (windowSize, windowTitle) import Graphics.Rendering.OpenGL as GL import qualified SDL.Image as SDLImage hiding (loadTexture) import qualified SDL.Vect import qualified SDL.Video import Nxt.Types hiding (rectX, rectY, rectWidth, rectHeight) import Unsafe.Coerce initWindow :: Size -> String -> IO () initWindow windowSize windowTitle = do _ <- getArgsAndInitialize initialWindowSize $= windowSize initialDisplayMode $= [DoubleBuffered] _ <- createWindow windowTitle return () initGraphics :: GLdouble -> GLdouble -> IO () initGraphics screenResWidth screenResHeight = do blend $= Enabled blendFunc $= (GL.SrcAlpha, OneMinusSrcAlpha) shadeModel $= Flat matrixMode $= Projection loadIdentity ortho 0.0 screenResWidth 0.0 screenResHeight (-1.0) 0.0 matrixMode $= Modelview 0 return () begin :: IO () begin = clear [ColorBuffer, DepthBuffer] end :: IO () end = do swapBuffers flush toGLdouble :: a -> GLdouble toGLdouble = unsafeCoerce fromGLdouble :: a -> Double fromGLdouble = unsafeCoerce loadTexture :: String -> IO Nxt.Types.Texture loadTexture textureFilePath = do surface <- SDLImage.load textureFilePath SDL.Vect.V2 rawWidth rawHeight <- SDL.Video.surfaceDimensions surface let width = fromIntegral rawWidth let height = fromIntegral rawHeight let surfaceSize = TextureSize2D width height textureObj <- liftM head (genObjectNames 1) textureBinding Texture2D $= Just textureObj textureWrapMode Texture2D S $= (Repeated, Repeat) textureWrapMode Texture2D T $= (Repeated, Repeat) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) surfacePixels <- SDL.Video.surfacePixels surface let pixelData = PixelData RGBA UnsignedByte surfacePixels texImage2D #if MIN_VERSION_OpenGL(2,9,0) Texture2D #else Nothing #endif NoProxy 0 RGBA' surfaceSize 0 pixelData SDL.Video.freeSurface surface return (Nxt.Types.Texture width height textureObj) freeTexture :: Nxt.Types.Texture -> IO () freeTexture tex = deleteObjectNames [textureObject tex] drawTexture :: Double -> Double -> Nxt.Types.Texture -> GLdouble -> IO () drawTexture x y tex alpha = drawTextureFlip x y tex alpha False drawTextureFlip drawTextureFlip :: Double -> Double -> Nxt.Types.Texture -> GLdouble -> Bool -> IO () drawTextureFlip x y tex alpha fliped = do texture Texture2D $= Enabled textureBinding Texture2D $= Just (textureObject tex) let texWidth = fromIntegral $ textureWidth tex texHeight = fromIntegral $ textureHeight tex let texCoord2f = texCoord :: TexCoord2 GLdouble -> IO () vertex3f = vertex :: Vertex3 GLdouble -> IO () color4f = color :: Color4 GLdouble -> IO () col = color4f (Color4 (1.0::GLdouble) (1.0::GLdouble) (1.0::GLdouble) alpha) let texCoordX = if fliped then (-1) else 1 x' = toGLdouble x y' = toGLdouble y renderPrimitive Quads $ do texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 x' y' 0.0); col texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 x' (y' + texHeight) 0.0); col texCoord2f (TexCoord2 texCoordX 0); vertex3f (Vertex3 (x' + texWidth) (y' + texHeight) 0.0); col texCoord2f (TexCoord2 texCoordX 1); vertex3f (Vertex3 (x' + texWidth) y' 0.0); col texture Texture2D $= Disabled drawString ( using Helvetica 12pt font ) drawString :: GLfloat -> GLfloat -> String -> Color4 GLfloat -> IO () drawString x y string col = do color col currentRasterPosition $= Vertex4 x y (0.0::GLfloat) (1.0::GLfloat) renderString Helvetica12 string drawRect :: Nxt.Types.Rect -> Color4 GLdouble -> IO () drawRect (Rect rectX rectY rectWidth rectHeight) rectColor = do let rX = toGLdouble rectX rY = toGLdouble rectY rW = toGLdouble rectWidth rH = toGLdouble rectHeight rectVertices = [Vertex3 rX rY 0.0, Vertex3 (rX + rW) rY 0.0, Vertex3 (rX + rW) (rY + rH) 0.0, Vertex3 rX (rY + rH) 0.0] renderPrimitive Quads $ do mapM_ color [rectColor] mapM_ vertex rectVertices drawPoly :: Nxt.Types.Poly -> Color4 GLdouble -> IO () drawPoly (Poly _ points) polyColor = do let polyVerts = map (\(x,y) -> Vertex3 (toGLdouble x) (toGLdouble y) (0.0::GLdouble)) points renderPrimitive Polygon $ do mapM_ color [polyColor] mapM_ vertex polyVerts worldTransform worldTransform :: Double -> Double -> IO () worldTransform worldX worldY = do loadIdentity translate (Vector3 (toGLdouble worldX) (toGLdouble worldY) 0.0) cycleTextures :: String -> Int -> Int -> IO [Nxt.Types.Texture] cycleTextures filePath frames frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] let textures = cycle $ foldr ((++) . replicate frameTime) [] texLists return textures cycleTextures2 :: String -> Int -> Int -> Int -> IO [Nxt.Types.Texture] cycleTextures2 filePath frames lastFrame frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] texLists2 <- Nxt.Graphics.loadTexture (filePath ++ show lastFrame ++ ".png"); let textures = foldr ((++) . replicate frameTime) (repeat texLists2) texLists return textures repeatTexturesN :: String -> Int -> Int -> Int -> Int -> Int -> Int -> IO [Nxt.Types.Texture] repeatTexturesN filePath frames startRepeat endRepeat nRepeats lastFrame frameTime = do texLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [1..frames] repeatTexLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [startRepeat..endRepeat] endTexLists <- mapM (\n -> Nxt.Graphics.loadTexture (filePath ++ show n ++ ".png")) [(endRepeat + 1)..lastFrame] let textures = replicate 60 (last endTexLists) ++ foldr ((++) . replicate frameTime) [] texLists ++ take (nRepeats * frameTime * (endRepeat - startRepeat)) (cycle $ foldr ((++) . replicate frameTime) [] repeatTexLists) ++ foldr ((++) . replicate frameTime) (repeat $ last endTexLists) endTexLists return textures
e7024d513396034ff63faa5980223ad508dd1fae3d165417ee895cdeada34dbd
erlang/rebar3
rebar_prv_app_discovery.erl
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- %% ex: ts=4 sw=4 et -module(rebar_prv_app_discovery). -behaviour(provider). -export([init/1, do/1, format_error/1]). -include("rebar.hrl"). -include_lib("providers/include/providers.hrl"). -define(PROVIDER, app_discovery). -define(DEPS, []). %% =================================================================== %% Public API %% =================================================================== -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. init(State) -> State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER}, {module, ?MODULE}, {bare, false}, {deps, ?DEPS}, {example, ""}, {short_desc, ""}, {desc, ""}, {opts, []}])), {ok, State1}. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. do(State) -> LibDirs = rebar_dir:lib_dirs(State), try State1 = rebar_app_discover:do(State, LibDirs), State2 = rebar_plugins:project_apps_install(State1), {ok, State2} catch throw:{error, {rebar_packages, Error}} -> {error, {rebar_packages, Error}}; throw:{error, {rebar_app_utils, Error}} -> {error, {rebar_app_utils, Error}}; throw:{error, {rebar_app_discover, Error}} -> {error, {rebar_app_discover, Error}}; throw:{error, Error} -> ?PRV_ERROR(Error) end. -spec format_error(any()) -> iolist(). format_error({multiple_app_files, Files}) -> io_lib:format("Multiple app files found in one app dir: ~ts", [rebar_string:join(Files, " and ")]); format_error({invalid_app_file, File, Reason}) -> case Reason of {Line, erl_parse, Description} -> io_lib:format("Invalid app file ~ts at line ~b: ~p", [File, Line, lists:flatten(Description)]); _ -> io_lib:format("Invalid app file ~ts: ~p", [File, Reason]) end; %% Provide a slightly more informative error message for consult of app file failure format_error({rebar_file_utils, {bad_term_file, AppFile, Reason}}) -> io_lib:format("Error in app file ~ts: ~ts", [rebar_dir:make_relative_path(AppFile, rebar_dir:get_cwd()), file:format_error(Reason)]); format_error(Reason) -> io_lib:format("~p", [Reason]).
null
https://raw.githubusercontent.com/erlang/rebar3/048412ed4593e19097f4fa91747593aac6706afb/apps/rebar/src/rebar_prv_app_discovery.erl
erlang
ex: ts=4 sw=4 et =================================================================== Public API =================================================================== Provide a slightly more informative error message for consult of app file failure
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- -module(rebar_prv_app_discovery). -behaviour(provider). -export([init/1, do/1, format_error/1]). -include("rebar.hrl"). -include_lib("providers/include/providers.hrl"). -define(PROVIDER, app_discovery). -define(DEPS, []). -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. init(State) -> State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER}, {module, ?MODULE}, {bare, false}, {deps, ?DEPS}, {example, ""}, {short_desc, ""}, {desc, ""}, {opts, []}])), {ok, State1}. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. do(State) -> LibDirs = rebar_dir:lib_dirs(State), try State1 = rebar_app_discover:do(State, LibDirs), State2 = rebar_plugins:project_apps_install(State1), {ok, State2} catch throw:{error, {rebar_packages, Error}} -> {error, {rebar_packages, Error}}; throw:{error, {rebar_app_utils, Error}} -> {error, {rebar_app_utils, Error}}; throw:{error, {rebar_app_discover, Error}} -> {error, {rebar_app_discover, Error}}; throw:{error, Error} -> ?PRV_ERROR(Error) end. -spec format_error(any()) -> iolist(). format_error({multiple_app_files, Files}) -> io_lib:format("Multiple app files found in one app dir: ~ts", [rebar_string:join(Files, " and ")]); format_error({invalid_app_file, File, Reason}) -> case Reason of {Line, erl_parse, Description} -> io_lib:format("Invalid app file ~ts at line ~b: ~p", [File, Line, lists:flatten(Description)]); _ -> io_lib:format("Invalid app file ~ts: ~p", [File, Reason]) end; format_error({rebar_file_utils, {bad_term_file, AppFile, Reason}}) -> io_lib:format("Error in app file ~ts: ~ts", [rebar_dir:make_relative_path(AppFile, rebar_dir:get_cwd()), file:format_error(Reason)]); format_error(Reason) -> io_lib:format("~p", [Reason]).
ff582d078ae0283f5211978a5c04bbcce7af1e72a38c6bfe0ca5eadd7098f88e
CardanoSolutions/kupo
ChainSync.hs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. module Kupo.Data.ChainSync ( ForcedRollbackHandler (..) , IntersectionNotFoundException (..) , HandshakeException (..) * , DistanceFromTip , mkDistanceFromTip , maxInFlight ) where import Kupo.Prelude import Kupo.Data.Cardano ( Point , SlotNo , Tip , WithOrigin (..) , distanceToTip , getPointSlotNo ) data ForcedRollbackHandler (m :: Type -> Type) = ForcedRollbackHandler { onSuccess :: !(m ()) , onFailure :: !(m ()) } | Exception thrown when first establishing a connection with a remote cardano - node . data HandshakeException = HandshakeException Text deriving (Show) instance Exception HandshakeException -- | Exception thrown when creating a chain-sync client from an invalid list of -- points. data IntersectionNotFoundException = IntersectionNotFound { requestedPoints :: ![WithOrigin SlotNo] -- ^ Provided points for intersection. , tip :: !(WithOrigin SlotNo) -- ^ Current known tip of the chain. } | ForcedIntersectionNotFound { point :: !(WithOrigin SlotNo) -- ^ Forced intersection point } deriving (Show) instance Exception IntersectionNotFoundException -- | A number of slots between the current cursor and the node's tip. newtype DistanceFromTip = DistanceFromTip Integer deriving (Generic, Show) | A smart constructor for constructing ' ' mkDistanceFromTip :: Tip -> Point -> DistanceFromTip mkDistanceFromTip tip = DistanceFromTip . toInteger . distanceToTip tip . getPointSlotNo -- | Decision has to whether pipeline an extra message. This is meant to create an 'elastic' -- pipelining where we do pipeline many messages when catching up from a point far in the past, but -- do not needlessly pipeline too many messages when close to the tip. -- -- This may sound like a needless "optimization" but it is actually crucial in order to support -- forced-rollback from clients. Indeed, if we've pipelined too many messages, we can't simply ask for -- a new intersection before all responses to these messages have been collected! When the client is already synchronized , this means it can take a long time as responses come one - by - one every ~20s or -- so. maxInFlight :: DistanceFromTip -> Integer maxInFlight (DistanceFromTip d) | d > 6000 = 100 | d > 1000 = 5 | otherwise = 1
null
https://raw.githubusercontent.com/CardanoSolutions/kupo/aa4c4cc980579ee4d4146c1fc44b8c35a44e9df0/src/Kupo/Data/ChainSync.hs
haskell
| Exception thrown when creating a chain-sync client from an invalid list of points. ^ Provided points for intersection. ^ Current known tip of the chain. ^ Forced intersection point | A number of slots between the current cursor and the node's tip. | Decision has to whether pipeline an extra message. This is meant to create an 'elastic' pipelining where we do pipeline many messages when catching up from a point far in the past, but do not needlessly pipeline too many messages when close to the tip. This may sound like a needless "optimization" but it is actually crucial in order to support forced-rollback from clients. Indeed, if we've pipelined too many messages, we can't simply ask for a new intersection before all responses to these messages have been collected! When the client is so.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. module Kupo.Data.ChainSync ( ForcedRollbackHandler (..) , IntersectionNotFoundException (..) , HandshakeException (..) * , DistanceFromTip , mkDistanceFromTip , maxInFlight ) where import Kupo.Prelude import Kupo.Data.Cardano ( Point , SlotNo , Tip , WithOrigin (..) , distanceToTip , getPointSlotNo ) data ForcedRollbackHandler (m :: Type -> Type) = ForcedRollbackHandler { onSuccess :: !(m ()) , onFailure :: !(m ()) } | Exception thrown when first establishing a connection with a remote cardano - node . data HandshakeException = HandshakeException Text deriving (Show) instance Exception HandshakeException data IntersectionNotFoundException = IntersectionNotFound { requestedPoints :: ![WithOrigin SlotNo] , tip :: !(WithOrigin SlotNo) } | ForcedIntersectionNotFound { point :: !(WithOrigin SlotNo) } deriving (Show) instance Exception IntersectionNotFoundException newtype DistanceFromTip = DistanceFromTip Integer deriving (Generic, Show) | A smart constructor for constructing ' ' mkDistanceFromTip :: Tip -> Point -> DistanceFromTip mkDistanceFromTip tip = DistanceFromTip . toInteger . distanceToTip tip . getPointSlotNo already synchronized , this means it can take a long time as responses come one - by - one every ~20s or maxInFlight :: DistanceFromTip -> Integer maxInFlight (DistanceFromTip d) | d > 6000 = 100 | d > 1000 = 5 | otherwise = 1
e3522f2256d69e1ae6266a89aed7cfda597ba2bf686e561f2fca146e1020e489
cirodrig/triolet
GenerateCHeader.hs
{-| Generation of header files for exported C symbols. -} module LowLevel.GenerateCHeader(generateCHeader) where import Data.Maybe import Language.C.Data.Ident import Language.C.Data.Node import Language.C.Pretty import Language.C.Syntax.AST import Language.C.Syntax.Constants import Common.Error import Export import LowLevel.Syntax import LowLevel.GenerateCUtils -- | Get the declaration components to use to declare a function parameter. -- A parameter might occupy multiple C parameters, hence a list is returned. exportParamDeclSpecs :: ExportDataType -> [DeclSpecs] exportParamDeclSpecs export_type = case export_type of ListET False _ -> [ptrDeclSpecs $ nameDeclSpecs "TrioletList"] ArrayET 2 False _ -> [ptrDeclSpecs $ nameDeclSpecs "TrioletMatrix"] CSizeArrayET et -> case exportParamDeclSpecs et of [spec] -> [nameDeclSpecs "TrioletInt", ptrDeclSpecs spec] _ -> Can not make an array of something that is n't one parameter internalError "exportParamDeclSpecs" NoneType parameters are removed TrioletIntET -> [nameDeclSpecs "TrioletInt"] TrioletFloatET -> [nameDeclSpecs "TrioletFloat"] TrioletBoolET -> [nameDeclSpecs "TrioletBool"] FunctionET _ _ -> [nameDeclSpecs "TrioletClosure"] -- | Get the declaration components to use to declare a function return type. -- The return type might occupy parameters and/or the return value. If there's -- no return, the return type will be \"void\". exportReturnDeclSpecs :: ExportDataType -> ([DeclSpecs], DeclSpecs) exportReturnDeclSpecs export_type = case export_type of ListET False _ -> ([], ptrDeclSpecs $ nameDeclSpecs "TrioletList") ArrayET 2 False _ -> ([], ptrDeclSpecs $ nameDeclSpecs "TrioletMatrix") CSizeArrayET et -> case exportParamDeclSpecs et of [spec] -> ([nameDeclSpecs "TrioletInt"], ptrDeclSpecs spec) _ -> Can not make an array of something that is n't one parameter internalError "exportReturnDeclSpecs" TrioletNoneET -> ([], voidDeclSpecs) TrioletIntET -> ([], nameDeclSpecs "TrioletInt") TrioletFloatET -> ([], nameDeclSpecs "TrioletFloat") TrioletBoolET -> ([], nameDeclSpecs "TrioletBool") FunctionET _ _ -> ([], nameDeclSpecs "TrioletClosure") -- | Get the declaration components to use to declare an exported function exportSigDeclSpecs :: CSignature -> DeclSpecs exportSigDeclSpecs (CSignature dom rng) = let dom_specs = map exportParamDeclSpecs dom (rng_param_specs, rng_ret_specs) = exportReturnDeclSpecs rng param_specs = concat dom_specs ++ rng_param_specs -- Create a derived function type from the return type fun_deriv = CFunDeclr (Right (map anonymousDecl param_specs, False)) [] internalNode in case rng_ret_specs of (rng_decl, rng_deriv) -> (rng_decl, fun_deriv : rng_deriv) -- | Create a C external function declaration for the given variable, with the -- given function signature. generateExportDecl :: (Var, CSignature) -> CDecl generateExportDecl (v, sig) = case exportSigDeclSpecs sig of (specs, derivs) -> let ident = varIdent v export_specs = CStorageSpec (CExtern internalNode) : specs declr = CDeclr (Just ident) derivs Nothing [] internalNode in CDecl export_specs [(Just declr, Nothing, Nothing)] internalNode -- | Create the text of a C header file if there are any exported C functions generateCHeader :: Module -> Maybe String generateCHeader mod = let export_decls = [generateExportDecl (v, sig) | (v, CExportSig sig) <- moduleExports mod] decls = map CDeclExt export_decls transl_module = CTranslUnit decls internalNode header_body_text = show $ pretty transl_module header_text = cModuleHeader ++ header_body_text in if null export_decls then Nothing else Just header_text cModuleHeader = "#include <inttypes.h>\n\ \#include <triolet.h>\n"
null
https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/src/program/LowLevel/GenerateCHeader.hs
haskell
| Generation of header files for exported C symbols. | Get the declaration components to use to declare a function parameter. A parameter might occupy multiple C parameters, hence a list is returned. | Get the declaration components to use to declare a function return type. The return type might occupy parameters and/or the return value. If there's no return, the return type will be \"void\". | Get the declaration components to use to declare an exported function Create a derived function type from the return type | Create a C external function declaration for the given variable, with the given function signature. | Create the text of a C header file if there are any exported C functions
module LowLevel.GenerateCHeader(generateCHeader) where import Data.Maybe import Language.C.Data.Ident import Language.C.Data.Node import Language.C.Pretty import Language.C.Syntax.AST import Language.C.Syntax.Constants import Common.Error import Export import LowLevel.Syntax import LowLevel.GenerateCUtils exportParamDeclSpecs :: ExportDataType -> [DeclSpecs] exportParamDeclSpecs export_type = case export_type of ListET False _ -> [ptrDeclSpecs $ nameDeclSpecs "TrioletList"] ArrayET 2 False _ -> [ptrDeclSpecs $ nameDeclSpecs "TrioletMatrix"] CSizeArrayET et -> case exportParamDeclSpecs et of [spec] -> [nameDeclSpecs "TrioletInt", ptrDeclSpecs spec] _ -> Can not make an array of something that is n't one parameter internalError "exportParamDeclSpecs" NoneType parameters are removed TrioletIntET -> [nameDeclSpecs "TrioletInt"] TrioletFloatET -> [nameDeclSpecs "TrioletFloat"] TrioletBoolET -> [nameDeclSpecs "TrioletBool"] FunctionET _ _ -> [nameDeclSpecs "TrioletClosure"] exportReturnDeclSpecs :: ExportDataType -> ([DeclSpecs], DeclSpecs) exportReturnDeclSpecs export_type = case export_type of ListET False _ -> ([], ptrDeclSpecs $ nameDeclSpecs "TrioletList") ArrayET 2 False _ -> ([], ptrDeclSpecs $ nameDeclSpecs "TrioletMatrix") CSizeArrayET et -> case exportParamDeclSpecs et of [spec] -> ([nameDeclSpecs "TrioletInt"], ptrDeclSpecs spec) _ -> Can not make an array of something that is n't one parameter internalError "exportReturnDeclSpecs" TrioletNoneET -> ([], voidDeclSpecs) TrioletIntET -> ([], nameDeclSpecs "TrioletInt") TrioletFloatET -> ([], nameDeclSpecs "TrioletFloat") TrioletBoolET -> ([], nameDeclSpecs "TrioletBool") FunctionET _ _ -> ([], nameDeclSpecs "TrioletClosure") exportSigDeclSpecs :: CSignature -> DeclSpecs exportSigDeclSpecs (CSignature dom rng) = let dom_specs = map exportParamDeclSpecs dom (rng_param_specs, rng_ret_specs) = exportReturnDeclSpecs rng param_specs = concat dom_specs ++ rng_param_specs fun_deriv = CFunDeclr (Right (map anonymousDecl param_specs, False)) [] internalNode in case rng_ret_specs of (rng_decl, rng_deriv) -> (rng_decl, fun_deriv : rng_deriv) generateExportDecl :: (Var, CSignature) -> CDecl generateExportDecl (v, sig) = case exportSigDeclSpecs sig of (specs, derivs) -> let ident = varIdent v export_specs = CStorageSpec (CExtern internalNode) : specs declr = CDeclr (Just ident) derivs Nothing [] internalNode in CDecl export_specs [(Just declr, Nothing, Nothing)] internalNode generateCHeader :: Module -> Maybe String generateCHeader mod = let export_decls = [generateExportDecl (v, sig) | (v, CExportSig sig) <- moduleExports mod] decls = map CDeclExt export_decls transl_module = CTranslUnit decls internalNode header_body_text = show $ pretty transl_module header_text = cModuleHeader ++ header_body_text in if null export_decls then Nothing else Just header_text cModuleHeader = "#include <inttypes.h>\n\ \#include <triolet.h>\n"
7eb8c2f40a573cfff65058950a0ca1af25e840f50326917faa67fd5051d3e4b3
serokell/universum
Monad.hs
{-# LANGUAGE Safe #-} -- | Reexporting useful monadic stuff. module Universum.Monad ( module Universum.Monad.Container , module Universum.Monad.Either , module Universum.Monad.Maybe , module Universum.Monad.Reexport , module Universum.Monad.Trans ) where import Universum.Monad.Container import Universum.Monad.Either import Universum.Monad.Maybe import Universum.Monad.Reexport import Universum.Monad.Trans
null
https://raw.githubusercontent.com/serokell/universum/7fc5dd3951d1177d1873e36b0678c759aeb5dc08/src/Universum/Monad.hs
haskell
# LANGUAGE Safe # | Reexporting useful monadic stuff.
module Universum.Monad ( module Universum.Monad.Container , module Universum.Monad.Either , module Universum.Monad.Maybe , module Universum.Monad.Reexport , module Universum.Monad.Trans ) where import Universum.Monad.Container import Universum.Monad.Either import Universum.Monad.Maybe import Universum.Monad.Reexport import Universum.Monad.Trans
394241d04ad7a4a11aed68eb605d97a2c7611d91f938d3019213e5ac2d779d43
RamV13/scrabble
index.ml
open Dom open Lwt open ScrabbleClient (* [fail] is a failure callback *) let fail = fun _ -> assert false [ get_element_by_id i d ] gets a DOM element by [ i d ] let get_element_by_id id = Js.Opt.get Dom_html.document##getElementById (Js.string id) fail [ get_input_by_id i d ] gets a DOM input element by [ i d ] let get_input_by_id id = match Dom_html.tagged (get_element_by_id id) with | Dom_html.Input elt -> elt | _ -> raise (Failure ("Element with id " ^ id ^ " is not an input")) (* [local_storage] is the localStorage javascript object *) let local_storage = match (Js.Optdef.to_option Dom_html.window##localStorage) with | Some value -> value | None -> assert false [ ] saves the [ player_name ] and [ game_name ] to * localStorage * localStorage *) let save_info player_name game_name = local_storage##setItem (Js.string "playerName",Js.string player_name); local_storage##setItem (Js.string "gameName",Js.string game_name) (* [save_game game_state] saves the game state [game_state] in local storage *) let save_game game_state = let json = Game.state_to_json game_state in local_storage##setItem (Js.string "gameState",Js.string json) (* [notify msg] displays a snackbar notification with a [msg] body *) let notify msg = " var notification = document.querySelector('.mdl-js-snackbar'); notification.MaterialSnackbar.showSnackbar({message: \"" ^ msg ^ "\"}); " |> Js.Unsafe.eval_string |> ignore (* [handle_btn_join btn ()] is the callback to handle the click events of the * join button [btn] *) let handle_btn_join btn _ = let player_name = Js.to_string (get_input_by_id "text_name")##value in let game_name = Js.to_string (get_input_by_id "text_game")##value in ScrabbleClient.join_game player_name game_name >>= (fun result -> begin ( match result with | Val state -> begin save_info player_name game_name; save_game state; Dom_html.window##location##href <- Js.string "scrabble.html" end | Not_found msg -> notify msg | Full msg -> notify msg | Exists msg -> notify msg | Server_error msg -> Dom_html.window##alert (Js.string msg) | _ -> assert false ); return () end) |> ignore; Js._false (* [handle_btn_create btn ()] is the callback to handle the click events of the * create button [btn] *) let handle_btn_create btn _ = let player_name = Js.to_string (get_input_by_id "text_name")##value in let game_name = Js.to_string (get_input_by_id "text_game")##value in ScrabbleClient.create_game player_name game_name >>= (fun result -> begin ( match result with | Val state -> begin save_info player_name game_name; save_game state; Dom_html.window##location##href <- Js.string "scrabble.html" end | Exists msg -> notify msg | Server_error msg -> Dom_html.window##alert (Js.string msg) | _ -> assert false ); Lwt.return () end) |> ignore; Js._false (* [onload ()] is the callback for when the window is loaded *) let onload _ = let btn_join = get_element_by_id "btn_join" in let btn_create = get_element_by_id "btn_create" in btn_join##onclick <- Dom_html.handler (handle_btn_join btn_join); btn_create##onclick <- Dom_html.handler (handle_btn_create btn_create); Js._false let _ = Dom_html.window##onload <- Dom_html.handler onload
null
https://raw.githubusercontent.com/RamV13/scrabble/07731680eaadf51c6b5cb3fc329056743f015215/public/js/index.ml
ocaml
[fail] is a failure callback [local_storage] is the localStorage javascript object [save_game game_state] saves the game state [game_state] in local storage [notify msg] displays a snackbar notification with a [msg] body [handle_btn_join btn ()] is the callback to handle the click events of the * join button [btn] [handle_btn_create btn ()] is the callback to handle the click events of the * create button [btn] [onload ()] is the callback for when the window is loaded
open Dom open Lwt open ScrabbleClient let fail = fun _ -> assert false [ get_element_by_id i d ] gets a DOM element by [ i d ] let get_element_by_id id = Js.Opt.get Dom_html.document##getElementById (Js.string id) fail [ get_input_by_id i d ] gets a DOM input element by [ i d ] let get_input_by_id id = match Dom_html.tagged (get_element_by_id id) with | Dom_html.Input elt -> elt | _ -> raise (Failure ("Element with id " ^ id ^ " is not an input")) let local_storage = match (Js.Optdef.to_option Dom_html.window##localStorage) with | Some value -> value | None -> assert false [ ] saves the [ player_name ] and [ game_name ] to * localStorage * localStorage *) let save_info player_name game_name = local_storage##setItem (Js.string "playerName",Js.string player_name); local_storage##setItem (Js.string "gameName",Js.string game_name) let save_game game_state = let json = Game.state_to_json game_state in local_storage##setItem (Js.string "gameState",Js.string json) let notify msg = " var notification = document.querySelector('.mdl-js-snackbar'); notification.MaterialSnackbar.showSnackbar({message: \"" ^ msg ^ "\"}); " |> Js.Unsafe.eval_string |> ignore let handle_btn_join btn _ = let player_name = Js.to_string (get_input_by_id "text_name")##value in let game_name = Js.to_string (get_input_by_id "text_game")##value in ScrabbleClient.join_game player_name game_name >>= (fun result -> begin ( match result with | Val state -> begin save_info player_name game_name; save_game state; Dom_html.window##location##href <- Js.string "scrabble.html" end | Not_found msg -> notify msg | Full msg -> notify msg | Exists msg -> notify msg | Server_error msg -> Dom_html.window##alert (Js.string msg) | _ -> assert false ); return () end) |> ignore; Js._false let handle_btn_create btn _ = let player_name = Js.to_string (get_input_by_id "text_name")##value in let game_name = Js.to_string (get_input_by_id "text_game")##value in ScrabbleClient.create_game player_name game_name >>= (fun result -> begin ( match result with | Val state -> begin save_info player_name game_name; save_game state; Dom_html.window##location##href <- Js.string "scrabble.html" end | Exists msg -> notify msg | Server_error msg -> Dom_html.window##alert (Js.string msg) | _ -> assert false ); Lwt.return () end) |> ignore; Js._false let onload _ = let btn_join = get_element_by_id "btn_join" in let btn_create = get_element_by_id "btn_create" in btn_join##onclick <- Dom_html.handler (handle_btn_join btn_join); btn_create##onclick <- Dom_html.handler (handle_btn_create btn_create); Js._false let _ = Dom_html.window##onload <- Dom_html.handler onload
8f1f42ceb73bfd5fe68b2fa6196957ae60c01e50aa82442bb4b52c7337bea002
polyfy/polylith
toolsdeps2_test.clj
(ns polylith.clj.core.validator.datashape.toolsdeps2-test (:require [clojure.test :refer :all] [malli.core :as m] [polylith.clj.core.validator.datashape.toolsdeps2 :as sut])) (defn validate-test-runner-config [v] (m/validate sut/test-runner-config-schema v)) (deftest test-runner-config-is-optional (is (validate-test-runner-config {}))) (deftest valid-create-test-runner (are [candidate] (validate-test-runner-config {:create-test-runner candidate}) :default 'my.runner/create ['my.runner/create] ['my.runner/create :default] ['my.runner/create :default 'my.runner/create :default])) (deftest invalid-create-test-runner (are [candidate] (not (validate-test-runner-config {:create-test-runner candidate})) :not-default 'unqualified 123 "my.runner/create" [] {} [:not-default] ['unqualified] ['unqualified :default]))
null
https://raw.githubusercontent.com/polyfy/polylith/abd20bb656e2cdd712732d80e1238316d3ea1b7f/components/validator/test/polylith/clj/core/validator/datashape/toolsdeps2_test.clj
clojure
(ns polylith.clj.core.validator.datashape.toolsdeps2-test (:require [clojure.test :refer :all] [malli.core :as m] [polylith.clj.core.validator.datashape.toolsdeps2 :as sut])) (defn validate-test-runner-config [v] (m/validate sut/test-runner-config-schema v)) (deftest test-runner-config-is-optional (is (validate-test-runner-config {}))) (deftest valid-create-test-runner (are [candidate] (validate-test-runner-config {:create-test-runner candidate}) :default 'my.runner/create ['my.runner/create] ['my.runner/create :default] ['my.runner/create :default 'my.runner/create :default])) (deftest invalid-create-test-runner (are [candidate] (not (validate-test-runner-config {:create-test-runner candidate})) :not-default 'unqualified 123 "my.runner/create" [] {} [:not-default] ['unqualified] ['unqualified :default]))
05121b70915b0dbb37173ff6c60b30010ac70fde307853e8b7551c38ae70a40a
mariorz/covid19-mx-time-series
core_test.clj
(ns covid19-mx-time-series.core-test (:require [clojure.test :refer :all] [covid19-mx-time-series.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/mariorz/covid19-mx-time-series/dde1183e8be502a85f7d1abf3aff25abdb176156/test/covid19_mx_time_series/core_test.clj
clojure
(ns covid19-mx-time-series.core-test (:require [clojure.test :refer :all] [covid19-mx-time-series.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
e22107463535f05c99468ffee68cbed4dc4055e6d58d5edf19e39978a227d74f
lehins/primal
GC.hs
# LANGUAGE FlexibleContexts # -- | Module : Primal . Memory . GC Copyright : ( c ) 2020 - 2022 -- License : BSD3 Maintainer : < > -- Stability : experimental -- Portability : non-portable -- module Primal.Memory.GC ( -- * Garbage collection performGC , performMajorGC , performMinorGC -- * Allocation counter and limits , setAllocationCounter , getAllocationCounter , enableAllocationLimit , disableAllocationLimit ) where import qualified System.Mem as Mem import Primal.Monad import Data.Int -- | Lifted version of `Mem.performGC` -- -- @since 1.0.0 performGC :: PrimalIO m => m () performGC = liftIO Mem.performGC | Lifted version of ` ` -- -- @since 1.0.0 performMajorGC :: PrimalIO m => m () performMajorGC = liftIO Mem.performMajorGC | Lifted version of ` Mem.performMinorGC ` -- -- @since 1.0.0 performMinorGC :: PrimalIO m => m () performMinorGC = liftIO Mem.performMinorGC | Lifted version of ` Mem.setAllocationCounter ` -- -- @since 1.0.0 setAllocationCounter :: PrimalIO m => Int64 -> m () setAllocationCounter = liftIO . Mem.setAllocationCounter -- | Lifted version of `Mem.getAllocationCounter` -- -- @since 1.0.0 getAllocationCounter :: PrimalIO m => m Int64 getAllocationCounter = liftIO Mem.getAllocationCounter -- | Lifted version of `Mem.enableAllocationLimit` -- -- @since 1.0.0 enableAllocationLimit :: PrimalIO m => m () enableAllocationLimit = liftIO Mem.enableAllocationLimit | Lifted version of ` Mem.disableAllocationLimit ` -- -- @since 1.0.0 disableAllocationLimit :: PrimalIO m => m () disableAllocationLimit = liftIO Mem.disableAllocationLimit
null
https://raw.githubusercontent.com/lehins/primal/c620bfd4f2a6475f1c12183fbe8138cf29ab1dad/primal/src/Primal/Memory/GC.hs
haskell
| License : BSD3 Stability : experimental Portability : non-portable * Garbage collection * Allocation counter and limits | Lifted version of `Mem.performGC` @since 1.0.0 @since 1.0.0 @since 1.0.0 @since 1.0.0 | Lifted version of `Mem.getAllocationCounter` @since 1.0.0 | Lifted version of `Mem.enableAllocationLimit` @since 1.0.0 @since 1.0.0
# LANGUAGE FlexibleContexts # Module : Primal . Memory . GC Copyright : ( c ) 2020 - 2022 Maintainer : < > module Primal.Memory.GC performGC , performMajorGC , performMinorGC , setAllocationCounter , getAllocationCounter , enableAllocationLimit , disableAllocationLimit ) where import qualified System.Mem as Mem import Primal.Monad import Data.Int performGC :: PrimalIO m => m () performGC = liftIO Mem.performGC | Lifted version of ` ` performMajorGC :: PrimalIO m => m () performMajorGC = liftIO Mem.performMajorGC | Lifted version of ` Mem.performMinorGC ` performMinorGC :: PrimalIO m => m () performMinorGC = liftIO Mem.performMinorGC | Lifted version of ` Mem.setAllocationCounter ` setAllocationCounter :: PrimalIO m => Int64 -> m () setAllocationCounter = liftIO . Mem.setAllocationCounter getAllocationCounter :: PrimalIO m => m Int64 getAllocationCounter = liftIO Mem.getAllocationCounter enableAllocationLimit :: PrimalIO m => m () enableAllocationLimit = liftIO Mem.enableAllocationLimit | Lifted version of ` Mem.disableAllocationLimit ` disableAllocationLimit :: PrimalIO m => m () disableAllocationLimit = liftIO Mem.disableAllocationLimit
68f8bfbe90e8636747cb826a59044f91f7b8998b2219392bd17428ebff95033b
pirapira/coq2rust
session.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (** A session is a script buffer + proof + messages, interacting with a coqtop, and a few other elements around *) class type ['a] page = object inherit GObj.widget method update : 'a -> unit method on_update : callback:('a -> unit) -> unit end class type control = object method detach : unit -> unit end type errpage = (int * string) list page type jobpage = string CString.Map.t page type session = { buffer : GText.buffer; script : Wg_ScriptView.script_view; proof : Wg_ProofView.proof_view; messages : Wg_MessageView.message_view; fileops : FileOps.ops; coqops : CoqOps.ops; coqtop : Coq.coqtop; command : Wg_Command.command_window; finder : Wg_Find.finder; tab_label : GMisc.label; errpage : errpage; jobpage : jobpage; mutable control : control; } (** [create filename coqtop_args] *) val create : string option -> string list -> session val kill : session -> unit val build_layout : session -> GObj.widget option * GObj.widget option * GObj.widget
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/ide/session.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * A session is a script buffer + proof + messages, interacting with a coqtop, and a few other elements around * [create filename coqtop_args]
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * class type ['a] page = object inherit GObj.widget method update : 'a -> unit method on_update : callback:('a -> unit) -> unit end class type control = object method detach : unit -> unit end type errpage = (int * string) list page type jobpage = string CString.Map.t page type session = { buffer : GText.buffer; script : Wg_ScriptView.script_view; proof : Wg_ProofView.proof_view; messages : Wg_MessageView.message_view; fileops : FileOps.ops; coqops : CoqOps.ops; coqtop : Coq.coqtop; command : Wg_Command.command_window; finder : Wg_Find.finder; tab_label : GMisc.label; errpage : errpage; jobpage : jobpage; mutable control : control; } val create : string option -> string list -> session val kill : session -> unit val build_layout : session -> GObj.widget option * GObj.widget option * GObj.widget
afa819bb4d20a44ae119751ae4cddc533bb2128670ae0feaf173d2560573d2f6
uw-unsat/leanette-popl22-artifact
quadrilateral-by-hand.rkt
#lang s-exp rosette ; Version of the quadrilateral demo with event handling written by hand. ; See reactive/quadrilateral.rkt for a version that uses 'when' and 'while' constraints for selection and dragging. (require racket/draw) (require "../core/wallingford.rkt") (require "../applications/geothings.rkt") (define picture (new thing%)) (define side1 (make-midpointline picture)) (define side2 (make-midpointline picture)) (define side3 (make-midpointline picture)) (define side4 (make-midpointline picture)) (define mid1 (make-line)) (define mid2 (make-line)) (define mid3 (make-line)) (define mid4 (make-line)) ; connect everything up (always (equal? (line-end2 (midpointline-line side1)) (line-end1 (midpointline-line side2))) #:owner picture) (always (equal? (line-end2 (midpointline-line side2)) (line-end1 (midpointline-line side3))) #:owner picture) (always (equal? (line-end2 (midpointline-line side3)) (line-end1 (midpointline-line side4))) #:owner picture) (always (equal? (line-end2 (midpointline-line side4)) (line-end1 (midpointline-line side1))) #:owner picture) (always (equal? (midpointline-midpoint side1) (line-end1 mid1)) #:owner picture) (always (equal? (midpointline-midpoint side1) (line-end2 mid4)) #:owner picture) (always (equal? (midpointline-midpoint side2) (line-end1 mid2)) #:owner picture) (always (equal? (midpointline-midpoint side2) (line-end2 mid1)) #:owner picture) (always (equal? (midpointline-midpoint side3) (line-end1 mid3)) #:owner picture) (always (equal? (midpointline-midpoint side3) (line-end2 mid2)) #:owner picture) (always (equal? (midpointline-midpoint side4) (line-end1 mid4)) #:owner picture) (always (equal? (midpointline-midpoint side4) (line-end2 mid3)) #:owner picture) ; use explicit stays so that we can provide unambiguous behavior (stay (line-end1 (midpointline-line side1)) #:priority 1 #:owner picture) (stay (line-end1 (midpointline-line side2)) #:priority 2 #:owner picture) (stay (line-end1 (midpointline-line side3)) #:priority 3 #:owner picture) (stay (line-end1 (midpointline-line side4)) #:priority 4 #:owner picture) ; initialize the locations of the sides (the midpoints and parallelogram sides can take care of themselves) (assert (equal? (line-end1 (midpointline-line side1)) (point 250 50))) (assert (equal? (line-end1 (midpointline-line side2)) (point 550 250))) (assert (equal? (line-end1 (midpointline-line side3)) (point 250 550))) (assert (equal? (line-end1 (midpointline-line side4)) (point 50 250))) (send picture solve) ; Hack for dragging - make a list of all the corners and midpoints (define points (list (line-end1 (midpointline-line side1)) (line-end1 (midpointline-line side2)) (line-end1 (midpointline-line side3)) (line-end1 (midpointline-line side4)) (midpointline-midpoint side1) (midpointline-midpoint side2) (midpointline-midpoint side3) (midpointline-midpoint side4))) (define frame (new frame% [label "Interactive quadrilateral demo"] [width 700] [height 700] [x 150] [y 100])) ; Derive a new canvas (a drawing window) class to handle events (define my-canvas% (class canvas% ; The base class is canvas% ; Define overriding method to handle mouse events (define/override (on-event event) (when (send event button-down?) (select-point event)) (when (send event button-up?) (unselect-point event)) (when (send event dragging?) (drag-point event))) ; Call the superclass init, passing on all init args (super-new))) (define selected-point #f) (define (select-point event) (define x (send event get-x)) (define y (send event get-y)) (set! selected-point (findf (lambda (p) (close x y p)) points))) (define (close x y p) (define gap 10) (define ev-p (send picture wally-evaluate p)) (and (< (abs (- x (point-x ev-p))) gap) (< (abs (- y (point-y ev-p))) gap))) (define (unselect-point event) (set! selected-point null)) (define (drag-point event) (when selected-point (assert (equal? selected-point (point (send event get-x) (send event get-y)))) (send picture solve) (showquad))) (define canv (new my-canvas% [parent frame] [paint-callback (lambda (canvas dc) (send dc set-pen "black" 1 'solid) (send dc set-brush "black" 'solid) (showquad))])) (define dc (send canv get-dc)) (define (showquad) (define s1 (send picture wally-evaluate (midpointline-line side1))) (define s2 (send picture wally-evaluate (midpointline-line side2))) (define s3 (send picture wally-evaluate (midpointline-line side3))) (define s4 (send picture wally-evaluate (midpointline-line side4))) (define mp1 (send picture wally-evaluate mid1)) (define mp2 (send picture wally-evaluate mid2)) (define mp3 (send picture wally-evaluate mid3)) (define mp4 (send picture wally-evaluate mid4)) (send dc clear) (showthing s1 dc) (showthing s2 dc) (showthing s3 dc) (showthing s4 dc) (showthing mp1 dc) (showthing mp2 dc) (showthing mp3 dc) (showthing mp4 dc)) (send frame show #t)
null
https://raw.githubusercontent.com/uw-unsat/leanette-popl22-artifact/80fea2519e61b45a283fbf7903acdf6d5528dbe7/rosette-benchmarks-4/wallingford/applications/quadrilateral-by-hand.rkt
racket
Version of the quadrilateral demo with event handling written by hand. See reactive/quadrilateral.rkt for a version that uses 'when' and 'while' constraints for selection and dragging. connect everything up use explicit stays so that we can provide unambiguous behavior initialize the locations of the sides (the midpoints and parallelogram sides can take care of themselves) Hack for dragging - make a list of all the corners and midpoints Derive a new canvas (a drawing window) class to handle events The base class is canvas% Define overriding method to handle mouse events Call the superclass init, passing on all init args
#lang s-exp rosette (require racket/draw) (require "../core/wallingford.rkt") (require "../applications/geothings.rkt") (define picture (new thing%)) (define side1 (make-midpointline picture)) (define side2 (make-midpointline picture)) (define side3 (make-midpointline picture)) (define side4 (make-midpointline picture)) (define mid1 (make-line)) (define mid2 (make-line)) (define mid3 (make-line)) (define mid4 (make-line)) (always (equal? (line-end2 (midpointline-line side1)) (line-end1 (midpointline-line side2))) #:owner picture) (always (equal? (line-end2 (midpointline-line side2)) (line-end1 (midpointline-line side3))) #:owner picture) (always (equal? (line-end2 (midpointline-line side3)) (line-end1 (midpointline-line side4))) #:owner picture) (always (equal? (line-end2 (midpointline-line side4)) (line-end1 (midpointline-line side1))) #:owner picture) (always (equal? (midpointline-midpoint side1) (line-end1 mid1)) #:owner picture) (always (equal? (midpointline-midpoint side1) (line-end2 mid4)) #:owner picture) (always (equal? (midpointline-midpoint side2) (line-end1 mid2)) #:owner picture) (always (equal? (midpointline-midpoint side2) (line-end2 mid1)) #:owner picture) (always (equal? (midpointline-midpoint side3) (line-end1 mid3)) #:owner picture) (always (equal? (midpointline-midpoint side3) (line-end2 mid2)) #:owner picture) (always (equal? (midpointline-midpoint side4) (line-end1 mid4)) #:owner picture) (always (equal? (midpointline-midpoint side4) (line-end2 mid3)) #:owner picture) (stay (line-end1 (midpointline-line side1)) #:priority 1 #:owner picture) (stay (line-end1 (midpointline-line side2)) #:priority 2 #:owner picture) (stay (line-end1 (midpointline-line side3)) #:priority 3 #:owner picture) (stay (line-end1 (midpointline-line side4)) #:priority 4 #:owner picture) (assert (equal? (line-end1 (midpointline-line side1)) (point 250 50))) (assert (equal? (line-end1 (midpointline-line side2)) (point 550 250))) (assert (equal? (line-end1 (midpointline-line side3)) (point 250 550))) (assert (equal? (line-end1 (midpointline-line side4)) (point 50 250))) (send picture solve) (define points (list (line-end1 (midpointline-line side1)) (line-end1 (midpointline-line side2)) (line-end1 (midpointline-line side3)) (line-end1 (midpointline-line side4)) (midpointline-midpoint side1) (midpointline-midpoint side2) (midpointline-midpoint side3) (midpointline-midpoint side4))) (define frame (new frame% [label "Interactive quadrilateral demo"] [width 700] [height 700] [x 150] [y 100])) (define my-canvas% (define/override (on-event event) (when (send event button-down?) (select-point event)) (when (send event button-up?) (unselect-point event)) (when (send event dragging?) (drag-point event))) (super-new))) (define selected-point #f) (define (select-point event) (define x (send event get-x)) (define y (send event get-y)) (set! selected-point (findf (lambda (p) (close x y p)) points))) (define (close x y p) (define gap 10) (define ev-p (send picture wally-evaluate p)) (and (< (abs (- x (point-x ev-p))) gap) (< (abs (- y (point-y ev-p))) gap))) (define (unselect-point event) (set! selected-point null)) (define (drag-point event) (when selected-point (assert (equal? selected-point (point (send event get-x) (send event get-y)))) (send picture solve) (showquad))) (define canv (new my-canvas% [parent frame] [paint-callback (lambda (canvas dc) (send dc set-pen "black" 1 'solid) (send dc set-brush "black" 'solid) (showquad))])) (define dc (send canv get-dc)) (define (showquad) (define s1 (send picture wally-evaluate (midpointline-line side1))) (define s2 (send picture wally-evaluate (midpointline-line side2))) (define s3 (send picture wally-evaluate (midpointline-line side3))) (define s4 (send picture wally-evaluate (midpointline-line side4))) (define mp1 (send picture wally-evaluate mid1)) (define mp2 (send picture wally-evaluate mid2)) (define mp3 (send picture wally-evaluate mid3)) (define mp4 (send picture wally-evaluate mid4)) (send dc clear) (showthing s1 dc) (showthing s2 dc) (showthing s3 dc) (showthing s4 dc) (showthing mp1 dc) (showthing mp2 dc) (showthing mp3 dc) (showthing mp4 dc)) (send frame show #t)
df9fc8220e8ab9c054e14688e64a8e49511d081862b5b2ce5e9e27b16b5c9e53
leptonyu/salak
Val.hs
module Salak.Internal.Val where import Data.ByteString (ByteString) import Data.Heap (Heap) import qualified Data.Heap as H import Data.Int import Data.List (intercalate) import Data.Scientific import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.Time import Salak.Internal.Key import Text.Megaparsec import Text.Megaparsec.Char #if __GLASGOW_HASKELL__ < 808 import Control.Applicative ((<|>)) #endif #if __GLASGOW_HASKELL__ < 804 import Data.Semigroup ((<>)) #endif data Val v = Val !Int !v deriving (Eq, Show) data ModType = Add | Mod | Del | Noop deriving (Eq, Show) type Priority = Int # INLINE priority # priority :: Val v -> Int priority (Val i _) = i data VRef = VRT !Text | VRR !Keys ![VRef] deriving Eq instance Show VRef where show (VRT t) = T.unpack t show (VRR k m) = "${" <> show k <> (if null m then go m else ":" <> go m) <> "}" where # INLINE go # go = foldr ((<>) . show) "" data Value = VT !Text | VI !Scientific | VB !Bool | VLT !LocalTime | VD !Day | VH !TimeOfDay | VU !UTCTime | VR ![VRef] deriving Eq # INLINE nullValue # nullValue :: Value -> Bool nullValue (VT x) = T.null x nullValue (VR []) = True nullValue _ = False instance Show Value where show v = let (a,b) = typeOfV v in b ++ "::" ++ a # INLINE typeOfV # typeOfV :: Value -> (String, String) typeOfV (VT b) = ("Str", show b) typeOfV (VI b) = ("Num", show b) typeOfV (VB b) = ("Bool", show b) typeOfV (VLT b) = ("LocalTime", show b) typeOfV (VD b) = ("Day", show b) typeOfV (VH b) = ("TimeOfDay", show b) typeOfV (VU b) = ("UTCTime", show b) typeOfV (VR b) = ("Ref", show b) # INLINE getType # getType :: Value -> String getType = fst . typeOfV # INLINE mkValue # mkValue :: Value -> Either String Value mkValue (VT v) = if T.null v then Right (VT v) else case parse vref "" v of Left e -> Left (errorBundlePretty e) Right y -> Right $ case y of [VRT x] -> VT x vs -> VR vs mkValue v = Right v # INLINE exprChar # exprChar :: Parser Char exprChar = noneOf go <|> (char '\\' >> oneOf go) where go :: [Token Text] go = "${}\\" vref :: Parser [VRef] vref = some (go <|> (VRT . T.pack <$> some exprChar)) where # INLINE go # go = do _ <- string "${" k <- keyExpr v <- option [] $ char ':' >> option [VRT ""] vref _ <- char '}' return (VRR (fromKeys k) v) newtype Vals = Vals { unVals :: Heap (Val Value) } deriving Eq instance Show Vals where show (Vals v) = intercalate "," $ go <$> H.toUnsortedList v where go (Val i x) = '#' : show i ++ ('.' : show x) instance Eq v => Ord (Val v) where compare (Val a _) (Val b _) = compare a b # INLINE nullVals # nullVals :: Vals -> Bool nullVals (Vals v) = H.null v # INLINE minimumVals # minimumVals :: Vals -> Val Value minimumVals (Vals h) = H.minimum h # INLINE emptyVals # emptyVals :: Vals emptyVals = Vals H.empty # INLINE deleteVals # deleteVals :: Int -> Vals -> (Bool, Vals) deleteVals i (Vals v) = let (a,b) = H.partition ((==i) . priority) v in (H.null a, Vals b) # INLINE getVal # getVal :: Vals -> Maybe Value getVal (Vals v) | H.null v = Nothing | otherwise = let Val _ x = H.minimum v in Just x class ToValue a where toVal :: a -> Value instance ToValue Value where # INLINE toVal # toVal = id instance ToValue Text where # INLINE toVal # toVal = VT instance ToValue ByteString where # INLINE toVal # toVal = VT . decodeUtf8 instance ToValue String where # INLINE toVal # toVal = VT . T.pack instance ToValue Scientific where # INLINE toVal # toVal = VI instance ToValue Integer where # INLINE toVal # toVal = VI . fromInteger instance ToValue Int where # INLINE toVal # toVal = VI . fromInteger . toInteger instance ToValue Int64 where # INLINE toVal # toVal = VI . fromInteger . toInteger instance ToValue Double where # INLINE toVal # toVal = VI . realToFrac instance ToValue Bool where # INLINE toVal # toVal = VB instance ToValue UTCTime where # INLINE toVal # toVal = VU # INLINE delVals # delVals :: Int -> Vals -> Vals delVals p (Vals v) = Vals $ H.filter ((/=p) . priority) v modVals :: Val Value -> Vals -> Either String Vals modVals (Val p x) (Vals v) = case mkValue x of Left e -> Left e Right y -> Right $ Vals $ H.insert (Val p y) $ H.filter ((/=p) . priority) v # INLINE singletonVals # singletonVals :: Val Value -> Either String Vals singletonVals (Val p x) = case mkValue x of Left e -> Left e Right y -> Right $ Vals $ H.singleton $ Val p y modVals' :: Vals -> Vals -> Either String Vals modVals' (Vals v) vals = if H.null v then Right vals else modVals (H.minimum v) vals
null
https://raw.githubusercontent.com/leptonyu/salak/0976e3f0792913df259e9bcaaee02f13d2b501f7/salak/src/Salak/Internal/Val.hs
haskell
module Salak.Internal.Val where import Data.ByteString (ByteString) import Data.Heap (Heap) import qualified Data.Heap as H import Data.Int import Data.List (intercalate) import Data.Scientific import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.Time import Salak.Internal.Key import Text.Megaparsec import Text.Megaparsec.Char #if __GLASGOW_HASKELL__ < 808 import Control.Applicative ((<|>)) #endif #if __GLASGOW_HASKELL__ < 804 import Data.Semigroup ((<>)) #endif data Val v = Val !Int !v deriving (Eq, Show) data ModType = Add | Mod | Del | Noop deriving (Eq, Show) type Priority = Int # INLINE priority # priority :: Val v -> Int priority (Val i _) = i data VRef = VRT !Text | VRR !Keys ![VRef] deriving Eq instance Show VRef where show (VRT t) = T.unpack t show (VRR k m) = "${" <> show k <> (if null m then go m else ":" <> go m) <> "}" where # INLINE go # go = foldr ((<>) . show) "" data Value = VT !Text | VI !Scientific | VB !Bool | VLT !LocalTime | VD !Day | VH !TimeOfDay | VU !UTCTime | VR ![VRef] deriving Eq # INLINE nullValue # nullValue :: Value -> Bool nullValue (VT x) = T.null x nullValue (VR []) = True nullValue _ = False instance Show Value where show v = let (a,b) = typeOfV v in b ++ "::" ++ a # INLINE typeOfV # typeOfV :: Value -> (String, String) typeOfV (VT b) = ("Str", show b) typeOfV (VI b) = ("Num", show b) typeOfV (VB b) = ("Bool", show b) typeOfV (VLT b) = ("LocalTime", show b) typeOfV (VD b) = ("Day", show b) typeOfV (VH b) = ("TimeOfDay", show b) typeOfV (VU b) = ("UTCTime", show b) typeOfV (VR b) = ("Ref", show b) # INLINE getType # getType :: Value -> String getType = fst . typeOfV # INLINE mkValue # mkValue :: Value -> Either String Value mkValue (VT v) = if T.null v then Right (VT v) else case parse vref "" v of Left e -> Left (errorBundlePretty e) Right y -> Right $ case y of [VRT x] -> VT x vs -> VR vs mkValue v = Right v # INLINE exprChar # exprChar :: Parser Char exprChar = noneOf go <|> (char '\\' >> oneOf go) where go :: [Token Text] go = "${}\\" vref :: Parser [VRef] vref = some (go <|> (VRT . T.pack <$> some exprChar)) where # INLINE go # go = do _ <- string "${" k <- keyExpr v <- option [] $ char ':' >> option [VRT ""] vref _ <- char '}' return (VRR (fromKeys k) v) newtype Vals = Vals { unVals :: Heap (Val Value) } deriving Eq instance Show Vals where show (Vals v) = intercalate "," $ go <$> H.toUnsortedList v where go (Val i x) = '#' : show i ++ ('.' : show x) instance Eq v => Ord (Val v) where compare (Val a _) (Val b _) = compare a b # INLINE nullVals # nullVals :: Vals -> Bool nullVals (Vals v) = H.null v # INLINE minimumVals # minimumVals :: Vals -> Val Value minimumVals (Vals h) = H.minimum h # INLINE emptyVals # emptyVals :: Vals emptyVals = Vals H.empty # INLINE deleteVals # deleteVals :: Int -> Vals -> (Bool, Vals) deleteVals i (Vals v) = let (a,b) = H.partition ((==i) . priority) v in (H.null a, Vals b) # INLINE getVal # getVal :: Vals -> Maybe Value getVal (Vals v) | H.null v = Nothing | otherwise = let Val _ x = H.minimum v in Just x class ToValue a where toVal :: a -> Value instance ToValue Value where # INLINE toVal # toVal = id instance ToValue Text where # INLINE toVal # toVal = VT instance ToValue ByteString where # INLINE toVal # toVal = VT . decodeUtf8 instance ToValue String where # INLINE toVal # toVal = VT . T.pack instance ToValue Scientific where # INLINE toVal # toVal = VI instance ToValue Integer where # INLINE toVal # toVal = VI . fromInteger instance ToValue Int where # INLINE toVal # toVal = VI . fromInteger . toInteger instance ToValue Int64 where # INLINE toVal # toVal = VI . fromInteger . toInteger instance ToValue Double where # INLINE toVal # toVal = VI . realToFrac instance ToValue Bool where # INLINE toVal # toVal = VB instance ToValue UTCTime where # INLINE toVal # toVal = VU # INLINE delVals # delVals :: Int -> Vals -> Vals delVals p (Vals v) = Vals $ H.filter ((/=p) . priority) v modVals :: Val Value -> Vals -> Either String Vals modVals (Val p x) (Vals v) = case mkValue x of Left e -> Left e Right y -> Right $ Vals $ H.insert (Val p y) $ H.filter ((/=p) . priority) v # INLINE singletonVals # singletonVals :: Val Value -> Either String Vals singletonVals (Val p x) = case mkValue x of Left e -> Left e Right y -> Right $ Vals $ H.singleton $ Val p y modVals' :: Vals -> Vals -> Either String Vals modVals' (Vals v) vals = if H.null v then Right vals else modVals (H.minimum v) vals
bcdef48c430a957eb1e4ae36aaaac1fc896bd31a81d5fd3079db80e8494b7b60
plops/cl-cpp-generator
test.lisp
/ 16.3 sb - cover . load this file with C - c ;; C-l in slime if there are assert errors, the tests fail the section " How to fix a broke test " in README.org explains how the tests can ;; be corrected. ;; if all tests run successfull, you can see a code coverage report in ;; coverage/*.html. This will tell which code lines were ;; checked. Please note that highlighted green in this report not ;; necessarily means that all cases are checked, e.g format calls with ;; ~^ in the format string will need to be checked with different ;; arguments. Any calls of member may also need many tests for full ;; coverage. ;; Note: You can use C-u C-M-x to execute individual test forms and ;; print the output in the current buffer. (require :sb-cover) (declaim (optimize sb-cover:store-coverage-data (speed 0) (safety 3) (debug 3))) #+nil (push :ispc *features*) ;; for now i have to open cp.lisp and compile it again with C-c C-k, so that foreach works #+nil(compile-file "cp.lisp") #+nil(load "cp.fasl") (in-package :cl-cpp-generator) (defun clang-format (str &optional (fn "/dev/shm/o.cpp") ) (with-open-file (s fn :direction :output :if-exists :supersede :if-does-not-exist :create) (write-sequence str s)) (sb-ext:run-program "/usr/bin/clang-format" '("-i" "/dev/shm/o.cpp")) (sleep .1) (with-open-file (s fn) (let ((str (make-string (file-length s)))) (read-sequence str s) str))) (defun test (num code string) (if (string= (clang-format (emit-cpp :str nil :code code)) (clang-format string) ) num (progn (clang-format (emit-cpp :str nil :code code) "/dev/shm/1") (clang-format string "/dev/shm/2") (assert (eq nil (with-output-to-string (s) (sb-ext:run-program "/usr/bin/diff" '("/dev/shm/1" "/dev/shm/2") :output s))))))) (progn ;; for loop (test 0 '(for ((i a :type int) (< i n) (+= i 1)) (+= b q)) ( i < n ) ; i + = 1 ) { b += q; } ") (test 1 '(for (() (< i n) (+= i 1)) (+= b q)) ( i < n ) ; i + = 1 ) { b += q; } ") (test 2 '(for ((i a :type int) () (+= i 1)) (+= b q)) ; i + = 1 ) { b += q; } ") (test 3 '(for ((i a :type int) (< i n) ()) (+= b q)) "for (int i = a; (i < n);) { b += q; } ") (test 4 '(for ((i a) (< i n) ()) (+= b q)) "for (auto i = a; (i < n);) { b += q; } ")) (progn ;; if (test 5 '(if (== a b) (+= a b) (-= a b)) "if ((a == b)) { a += b; } else { a -= b; } ") (test 6 '(if (== a b) (+= a b)) "if ((a == b)) { a += b; } ")) setf (test 7 '(setf q (+ 1 2 3) l (+ 1 2 3)) "q = (1 + 2 + 3); l = (1 + 2 + 3); ") (test 8 '(setf q (+ 1 2 3)) "q = (1 + 2 + 3);") ) (progn ;; decl (test 9 '(decl ((i :type int :init 0) (f :type float :init 3.2s-7) (d :type double :init 7.2d-31) (z :type "complex float" :init #.(complex 2s0 1s0)) (w :type "complex double" :init #.(complex 2d0 1d0)))) "int i = 0; float f = (3.2e-7f); double d = (7.2e-31); complex float z = ((2.e+0f) + (1.e+0fi)); complex double w = ((2.e+0) + (1.e+0i)); ")) (progn ;; let (test 10 '(let ((i :type int :init 0) (f :type float :init 3.2s-7) (d :type double :init 7.2d-31) (z :type "complex float" :init #.(complex 2s0 1s0)) (w :type "complex double" :init #.(complex 2d0 1d0))) (setf i (+ f d) j (- 3 j)) (+= j (+ 32 q))) "{ int i = 0; float f = (3.2e-7f); double d = (7.2e-31); complex float z = ((2.e+0f) + (1.e+0fi)); complex double w = ((2.e+0) + (1.e+0i)); i = (f + d);j = (3 - j); j += (32 + q); } ") ) (progn ;; computed assignment with complicated variable (test 11 '(+= "a::b" 3) "a::b += 3")) (progn ;; class, struct and union; function declaration (test 12 '(with-compilation-unit (include <stdio.h>) (include "bla.h") (with-namespace N (class "gug::senso" () (access-specifier public) (function (f ((a :type int)) int :specifier const) (return i)) (function (h ((a :type int)) int)) (access-specifier private) (function (f2 ((a :type int)) int)) (function (h2 ((a :type int)) int)) (decl ((i :type int) (resetBus :type "Reset::BusCb")))) (class sensor ("public p::pipeline" "virtual public qqw::q" "virtual public qq::q") (function (sensor ((a :type char)))) (decl ((j :type int)))) (union "lag::sensor2" ("private p::pipeline2") (decl ((j :type int) (f :type float)))) (struct "lag::sensor2" ("private p::pipeline2") (access-specifier public) (decl ((j :type int) (f :type float)))) )) "#include <stdio.h> #include \"bla.h\" namespace N { class gug::senso { public: int f(int a) const{ return i; } int h(int a); private: int f2(int a); int h2(int a); int i; Reset::BusCb resetBus; }; class sensor : public p::pipeline, virtual public qqw::q, virtual public qq::q{ sensor(char a); int j; }; union lag::sensor2 : private p::pipeline2{ int j; float f; }; struct lag::sensor2 : private p::pipeline2{ public: int j; float f; }; } // namespace N ")) (progn ;; function definition (test 13 '(function (g ((a :type char) (b :type int*)) "complex double::blub") (decl ((q :init b))) (setf "blub::q" (+ 1 2 3) l (+ 1 2 3))) "complex double::blub g(char a,int* b){ auto q = b; blub::q = (1 + 2 + 3); l = (1 + 2 + 3); } ") ;; constructor with initializers (test 14 '(function (bla ((a :type char) (b :type int*)) () :ctor ((a 3) (sendToSensorCb sendToSensorCb_))) (+= a b) ) "bla(char a,int* b): a( 3 ), sendToSensorCb( sendToSensorCb_ ) { a += b; } ")) (progn ;; function call (test 15 '(function (g ((a :type char) (b :type int*)) "complex double::blub") (funcall add a b)) "complex double ::blub g(char a, int *b) { add(a, b); } ")) (progn ;; default parameter (test 16 `(function (blah ((a :type int :default 3))) (raw "// ")) "blah(int a = 3){ // ; } ")) (progn ;; terniary operator (test 17 `(statements (? a b c) (? (< a b) x) (? (&& (<= 0 h) (< h 24)) (= hour h) (comma-list (<< cout (string "bla")) (= hour 0)) )) "( a ) ? ( b ): ( c ); ( (a < b) ) ? ( x ); ( ((0 <= h) && (h < 24)) ) ? ( hour = h ): ( (cout << \"bla\"),hour = 0 ); ")) (progn (test 18 ;; for-range (c++) `(statements (for-range (e (funcall make_iterator_range (string ".") (list )))) (for-range ((e :type "auto&&") (funcall make_iterator_range (string ".") (list ))))) " for(auto e : make_iterator_range(\".\",{})) { } for(auto&& e : make_iterator_range(\".\",{})) { } ")) (progn (test 19 ;; new, delete[] `(let ((buf :type "unsigned char*" :init (new (aref "unsigned char" size)))) (delete[] buf)) "{ unsigned char* buf = new unsigned char[size]; delete [] buf; } ") (test 20 ;; new, delete `(let ((buf :type "unsigned char*" :init (new "unsigned char"))) (delete buf)) "{ unsigned char* buf = new unsigned char; delete buf; } ")) (progn alignment on 64 byte boundary `(let (((aref buf (* width height)) :type "static int" :extra (raw " __attribute__((aligned(64)))")))) "{ static int buf[(width * height)] __attribute__((aligned(64))); } ")) (progn (test 22 ;; enum class `(with-compilation-unit (enum-class (ProtocolType) IP ICMP RAW) (enum-class (fruit :type uint8_t) apple melon)) "enum class ProtocolType { IP, ICMP, RAW}; enum class fruit : uint8_t { apple, melon}; ")) (progn (test 23 ;; lambda (c++) `(lambda (((i :type int)) :ret "->int") ) "[](int i)->int { } ")) (progn (test 24 ;; do-while while `(statements (while (< 1 a) (+= 1 a) (setf a b)) (do-while (< 1 a) (+= 1 a) (setf a b))) " while((1 < a)) { 1 += a; a = b; } do { 1 += a; a = b; } while ( (1 < a) ); ")) (progn (test 25 ;; || `(if (|\|\|| a b) (statements (funcall bal))) "if ( (a || b) ) { bal(); } ")) (progn ispc `(with-compilation-unit (dotimes (i (funcall max 2 3)) (funcall bla)) (foreach (i (funcall max 1 0) (funcall min m n)) (funcall ata)) (foreach ((i (funcall max 1 0) (funcall min m n)) (j 0 n)) (funcall ata)) (foreach-active (i) (+= (aref a index) (bit #b0110))) (function (func ((v :type "uniform int")) "extern void")) (foreach-unique (val x) (funcall func val)) (let ((dx :type float :init (/ (- x1 x0) width)) (dy :type float :init (/ (- y1 y0) height)) ) (foreach (i (funcall max 1 0) (funcall min m n)) (funcall ata)) #+nil (foreach (i 0 width) (let ((x :type float :init (+ x0 (* i dx))) (y :type float :init (+ y0 (* i dy))) (index :type int :init (+ i (* j width))) ) (setf (aref output index) (funcall mandel x y #+nil max_iterations)))))) ( i < ) ) ; i + = 1 ) { bla(); } foreach(i = max(1,0) ... min(m,n)) { ata(); } foreach(i = max(1,0) ... min(m,n),j = 0 ... n) { ata(); } foreach_active(i) { a[index] += 0b110; } extern void func(uniform int v); foreach_uniq(val in x) { func(val); } { float dx = ((x1 - x0) / width); float dy = ((y1 - y0) / height); foreach(i = max(1,0) ... min(m,n)) { ata(); } } ")) (progn (test 27 ;; default member -features-i-like-the-most-in-c11-part-2/ `(class MyClassType () (access-specifier private) (decl ((privateInt :type int :extra "{ 1 }")))) "class MyClassType { private: int privateInt{ 1 }; }; ")) (progn (test 28 ;; struct inside of function `(function (bla () void) (struct b () (decl ((q :type int) (w :type float))))) "void bla(){ struct b { int q; float w; }; } ")) (progn (test 29 ;; operator `(function (operator= ((a :type "const Array<T>&")) Array<T>&)) "Array<T>& operator=(const Array<T>& a);")) (progn (defmacro with-fopen ((handle fn) &body body) `(let ((,handle :type FILE* :init (funcall fopen ,fn (string "wb")))) ,@body (funcall fclose ,handle))) (test 30 ;; macro `(function (frame_store ((frame_data :type "char*") (frame_length :type int) (filename :type "const char*")) void) (macroexpand (with-fopen (o filename) (funcall fwrite frame_data frame_length 1 o)))) "void frame_store(char* frame_data,int frame_length,const char* filename){ { FILE* o = fopen(filename,\"wb\"); fwrite(frame_data,frame_length,1,o); fclose(o); } } ")) ;;(sb-introspect:who-calls ) (progn (macrolet ((with-fopen ((handle fn) &body body) `(let ((,handle :type FILE* :init (funcall fopen ,fn (string "wb")))) ,@body (funcall fclose ,handle)))) (test 30 ;; macrolet `(function (frame_store ((frame_data :type "char*") (frame_length :type int) (filename :type "const char*")) void) (macroexpand (with-fopen (o filename) (funcall fwrite frame_data frame_length 1 o)))) "void frame_store(char* frame_data,int frame_length,const char* filename){ { FILE* o = fopen(filename,\"wb\"); fwrite(frame_data,frame_length,1,o); fclose(o); } } "))) (test 31 ;; constructor inheritance `(function (CustomRectItem ((x :type qreal) (y :type qreal) (w :type qreal) (h :type qreal) (parent :type QGraphicsItem* :default nullptr)) explicit :parent-ctor ((QGraphicsRectItem x y w h parent))) (raw "//")) "explicit CustomRectItem(qreal x,qreal y,qreal w,qreal h,QGraphicsItem* parent = nullptr):QGraphicsRectItem(x,y,w,h,parent) { //; } ") (test 32 ;; multi dimensonal array `(with-compilation-unit (aref buf) (aref buf 1) (aref buf (+ 1 2) (* i j)) (aref bta (+ 3 2) 1 1)) "buf[] buf[1] buf[(1 + 2)][(i * j)] bta[(3 + 2)][1][1]") #+nil (emit-cpp :str nil :code '(with-compilation-unit (include <stdio.h>) (include "bla.h") (with-namespace N (class "gug::senso" () (access-specifier public) (function (f ((a :type int)) int :specifier const) (return i)) (function (h ((a :type int)) int)) (access-specifier private) (function (f2 ((a :type int)) int)) (function (h2 ((a :type int)) int)) (decl ((i :type int) (resetBus :type "Reset::BusCb")))) (class sensor ("public p::pipeline" "virtual public qqw::q" "virtual public qq::q") (function (sensor ((a :type char)))) (decl ((j :type int)))) (union "lag::sensor2" ("private p::pipeline2") (decl ((j :type int) (f :type float)))) (struct "lag::sensor2" ("private p::pipeline2") (access-specifier public) (decl ((j :type int) (f :type float)))) ))) (sb-cover:report "/home/martin/stage/cl-cpp-generator/cover/") #+nil (sb-cover:reset-coverage)
null
https://raw.githubusercontent.com/plops/cl-cpp-generator/a0bba0a6e0e8f34e3e4459508ada1cd0036d9068/test.lisp
lisp
C-l in slime if there are assert errors, the tests fail the section be corrected. if all tests run successfull, you can see a code coverage report in coverage/*.html. This will tell which code lines were checked. Please note that highlighted green in this report not necessarily means that all cases are checked, e.g format calls with ~^ in the format string will need to be checked with different arguments. Any calls of member may also need many tests for full coverage. Note: You can use C-u C-M-x to execute individual test forms and print the output in the current buffer. for now i have to open cp.lisp and compile it again with C-c C-k, so that foreach works for loop i + = 1 ) { i + = 1 ) { i + = 1 ) { (i < n);) { (i < n);) { if decl let j = (3 - j); computed assignment with complicated variable class, struct and union; function declaration function definition constructor with initializers function call } default parameter terniary operator for-range (c++) new, delete[] new, delete enum class lambda (c++) do-while while || i + = 1 ) { default member -features-i-like-the-most-in-c11-part-2/ struct inside of function operator macro (sb-introspect:who-calls ) macrolet constructor inheritance multi dimensonal array
/ 16.3 sb - cover . load this file with C - c " How to fix a broke test " in README.org explains how the tests can (require :sb-cover) (declaim (optimize sb-cover:store-coverage-data (speed 0) (safety 3) (debug 3))) #+nil(compile-file "cp.lisp") #+nil(load "cp.fasl") (in-package :cl-cpp-generator) (defun clang-format (str &optional (fn "/dev/shm/o.cpp") ) (with-open-file (s fn :direction :output :if-exists :supersede :if-does-not-exist :create) (write-sequence str s)) (sb-ext:run-program "/usr/bin/clang-format" '("-i" "/dev/shm/o.cpp")) (sleep .1) (with-open-file (s fn) (let ((str (make-string (file-length s)))) (read-sequence str s) str))) (defun test (num code string) (if (string= (clang-format (emit-cpp :str nil :code code)) (clang-format string) ) num (progn (clang-format (emit-cpp :str nil :code code) "/dev/shm/1") (clang-format string "/dev/shm/2") (assert (eq nil (with-output-to-string (s) (sb-ext:run-program "/usr/bin/diff" '("/dev/shm/1" "/dev/shm/2") :output s))))))) (test 0 '(for ((i a :type int) (< i n) (+= i 1)) (+= b q)) } ") (test 1 '(for (() (< i n) (+= i 1)) (+= b q)) } ") (test 2 '(for ((i a :type int) () (+= i 1)) (+= b q)) } ") (test 3 '(for ((i a :type int) (< i n) ()) (+= b q)) } ") (test 4 '(for ((i a) (< i n) ()) (+= b q)) } ")) (test 5 '(if (== a b) (+= a b) (-= a b)) "if ((a == b)) { } else { } ") (test 6 '(if (== a b) (+= a b)) "if ((a == b)) { } ")) setf (test 7 '(setf q (+ 1 2 3) l (+ 1 2 3)) ") (test 8 '(setf q (+ 1 2 3)) "q = (1 + 2 + 3);") ) (test 9 '(decl ((i :type int :init 0) (f :type float :init 3.2s-7) (d :type double :init 7.2d-31) (z :type "complex float" :init #.(complex 2s0 1s0)) (w :type "complex double" :init #.(complex 2d0 1d0)))) ")) (test 10 '(let ((i :type int :init 0) (f :type float :init 3.2s-7) (d :type double :init 7.2d-31) (z :type "complex float" :init #.(complex 2s0 1s0)) (w :type "complex double" :init #.(complex 2d0 1d0))) (setf i (+ f d) j (- 3 j)) (+= j (+ 32 q))) "{ } ") ) (test 11 '(+= "a::b" 3) "a::b += 3")) (test 12 '(with-compilation-unit (include <stdio.h>) (include "bla.h") (with-namespace N (class "gug::senso" () (access-specifier public) (function (f ((a :type int)) int :specifier const) (return i)) (function (h ((a :type int)) int)) (access-specifier private) (function (f2 ((a :type int)) int)) (function (h2 ((a :type int)) int)) (decl ((i :type int) (resetBus :type "Reset::BusCb")))) (class sensor ("public p::pipeline" "virtual public qqw::q" "virtual public qq::q") (function (sensor ((a :type char)))) (decl ((j :type int)))) (union "lag::sensor2" ("private p::pipeline2") (decl ((j :type int) (f :type float)))) (struct "lag::sensor2" ("private p::pipeline2") (access-specifier public) (decl ((j :type int) (f :type float)))) )) "#include <stdio.h> #include \"bla.h\" namespace N { class gug::senso { public: int f(int a) const{ } private: class sensor : public p::pipeline, virtual public qqw::q, virtual public qq::q{ union lag::sensor2 : private p::pipeline2{ struct lag::sensor2 : private p::pipeline2{ public: } // namespace N ")) (test 13 '(function (g ((a :type char) (b :type int*)) "complex double::blub") (decl ((q :init b))) (setf "blub::q" (+ 1 2 3) l (+ 1 2 3))) "complex double::blub g(char a,int* b){ } ") (test 14 '(function (bla ((a :type char) (b :type int*)) () :ctor ((a 3) (sendToSensorCb sendToSensorCb_))) (+= a b) ) "bla(char a,int* b): a( 3 ), sendToSensorCb( sendToSensorCb_ ) { } ")) (test 15 '(function (g ((a :type char) (b :type int*)) "complex double::blub") (funcall add a b)) ")) (test 16 `(function (blah ((a :type int :default 3))) (raw "// ")) "blah(int a = 3){ } ")) (test 17 `(statements (? a b c) (? (< a b) x) (? (&& (<= 0 h) (< h 24)) (= hour h) (comma-list (<< cout (string "bla")) (= hour 0)) )) ")) (progn `(statements (for-range (e (funcall make_iterator_range (string ".") (list )))) (for-range ((e :type "auto&&") (funcall make_iterator_range (string ".") (list ))))) " for(auto e : make_iterator_range(\".\",{})) { } for(auto&& e : make_iterator_range(\".\",{})) { } ")) (progn `(let ((buf :type "unsigned char*" :init (new (aref "unsigned char" size)))) (delete[] buf)) "{ } ") `(let ((buf :type "unsigned char*" :init (new "unsigned char"))) (delete buf)) "{ } ")) (progn alignment on 64 byte boundary `(let (((aref buf (* width height)) :type "static int" :extra (raw " __attribute__((aligned(64)))")))) "{ } ")) (progn `(with-compilation-unit (enum-class (ProtocolType) IP ICMP RAW) (enum-class (fruit :type uint8_t) apple melon)) ")) (progn `(lambda (((i :type int)) :ret "->int") ) "[](int i)->int { } ")) (progn `(statements (while (< 1 a) (+= 1 a) (setf a b)) (do-while (< 1 a) (+= 1 a) (setf a b))) " while((1 < a)) { } do { } ")) (progn `(if (|\|\|| a b) (statements (funcall bal))) "if ( (a || b) ) { } ")) (progn ispc `(with-compilation-unit (dotimes (i (funcall max 2 3)) (funcall bla)) (foreach (i (funcall max 1 0) (funcall min m n)) (funcall ata)) (foreach ((i (funcall max 1 0) (funcall min m n)) (j 0 n)) (funcall ata)) (foreach-active (i) (+= (aref a index) (bit #b0110))) (function (func ((v :type "uniform int")) "extern void")) (foreach-unique (val x) (funcall func val)) (let ((dx :type float :init (/ (- x1 x0) width)) (dy :type float :init (/ (- y1 y0) height)) ) (foreach (i (funcall max 1 0) (funcall min m n)) (funcall ata)) #+nil (foreach (i 0 width) (let ((x :type float :init (+ x0 (* i dx))) (y :type float :init (+ y0 (* i dy))) (index :type int :init (+ i (* j width))) ) (setf (aref output index) (funcall mandel x y #+nil max_iterations)))))) } foreach(i = max(1,0) ... min(m,n)) { } foreach(i = max(1,0) ... min(m,n),j = 0 ... n) { } foreach_active(i) { } foreach_uniq(val in x) { } { foreach(i = max(1,0) ... min(m,n)) { } } ")) (progn `(class MyClassType () (access-specifier private) (decl ((privateInt :type int :extra "{ 1 }")))) "class MyClassType { private: ")) (progn `(function (bla () void) (struct b () (decl ((q :type int) (w :type float))))) "void bla(){ struct b { } ")) (progn `(function (operator= ((a :type "const Array<T>&")) Array<T>&)) "Array<T>& operator=(const Array<T>& a);")) (progn (defmacro with-fopen ((handle fn) &body body) `(let ((,handle :type FILE* :init (funcall fopen ,fn (string "wb")))) ,@body (funcall fclose ,handle))) `(function (frame_store ((frame_data :type "char*") (frame_length :type int) (filename :type "const char*")) void) (macroexpand (with-fopen (o filename) (funcall fwrite frame_data frame_length 1 o)))) "void frame_store(char* frame_data,int frame_length,const char* filename){ { } } ")) (progn (macrolet ((with-fopen ((handle fn) &body body) `(let ((,handle :type FILE* :init (funcall fopen ,fn (string "wb")))) ,@body (funcall fclose ,handle)))) `(function (frame_store ((frame_data :type "char*") (frame_length :type int) (filename :type "const char*")) void) (macroexpand (with-fopen (o filename) (funcall fwrite frame_data frame_length 1 o)))) "void frame_store(char* frame_data,int frame_length,const char* filename){ { } } "))) `(function (CustomRectItem ((x :type qreal) (y :type qreal) (w :type qreal) (h :type qreal) (parent :type QGraphicsItem* :default nullptr)) explicit :parent-ctor ((QGraphicsRectItem x y w h parent))) (raw "//")) "explicit CustomRectItem(qreal x,qreal y,qreal w,qreal h,QGraphicsItem* parent = nullptr):QGraphicsRectItem(x,y,w,h,parent) { } ") `(with-compilation-unit (aref buf) (aref buf 1) (aref buf (+ 1 2) (* i j)) (aref bta (+ 3 2) 1 1)) "buf[] buf[1] buf[(1 + 2)][(i * j)] bta[(3 + 2)][1][1]") #+nil (emit-cpp :str nil :code '(with-compilation-unit (include <stdio.h>) (include "bla.h") (with-namespace N (class "gug::senso" () (access-specifier public) (function (f ((a :type int)) int :specifier const) (return i)) (function (h ((a :type int)) int)) (access-specifier private) (function (f2 ((a :type int)) int)) (function (h2 ((a :type int)) int)) (decl ((i :type int) (resetBus :type "Reset::BusCb")))) (class sensor ("public p::pipeline" "virtual public qqw::q" "virtual public qq::q") (function (sensor ((a :type char)))) (decl ((j :type int)))) (union "lag::sensor2" ("private p::pipeline2") (decl ((j :type int) (f :type float)))) (struct "lag::sensor2" ("private p::pipeline2") (access-specifier public) (decl ((j :type int) (f :type float)))) ))) (sb-cover:report "/home/martin/stage/cl-cpp-generator/cover/") #+nil (sb-cover:reset-coverage)
4f587c49c03b1b02001cc73bba1cdd3397bfadb62e94bdc4ab339c95878c5119
fare/fare-scripts
repl.lisp
;;; REPL utilities (uiop:define-package :fare-scripts/repl (:use :cl :fare-utils :uiop :inferior-shell :optima :optima.ppcre :cl-scripting :cl-launch/dispatch) (:import-from :swank) (:export #:read-eval-print #:rep)) (in-package :fare-scripts/repl) ;; From -new-favorite-slimesbclccl-trick #+sbcl (push (lambda (&rest args) (apply #'swank:ed-in-emacs args) t) sb-ext:*ed-functions*) #+ccl (setq ccl:*resident-editor-hook* #'swank:ed-in-emacs) (exporting-definitions (defun read-eval-print (s &optional (package :fare-scripts/repl)) (with-standard-io-syntax (let ((*package* (find-package (standard-case-symbol-name package)))) (format t "~W~%" (eval-input s))))) (defun rep (a &optional b) (if b (read-eval-print b a) (read-eval-print a)))) (register-commands :fare-scripts/repl) (eval-when (:compile-toplevel) (uiop:println "COMPILE-TOPLEVEL")) (eval-when (:load-toplevel) (uiop:println "LOAD-TOPLEVEL")) (eval-when (:execute) (uiop:println "EXECUTE"))
null
https://raw.githubusercontent.com/fare/fare-scripts/fee32edbbe4ca486e63922d94305027a8b5603a5/repl.lisp
lisp
REPL utilities From -new-favorite-slimesbclccl-trick
(uiop:define-package :fare-scripts/repl (:use :cl :fare-utils :uiop :inferior-shell :optima :optima.ppcre :cl-scripting :cl-launch/dispatch) (:import-from :swank) (:export #:read-eval-print #:rep)) (in-package :fare-scripts/repl) #+sbcl (push (lambda (&rest args) (apply #'swank:ed-in-emacs args) t) sb-ext:*ed-functions*) #+ccl (setq ccl:*resident-editor-hook* #'swank:ed-in-emacs) (exporting-definitions (defun read-eval-print (s &optional (package :fare-scripts/repl)) (with-standard-io-syntax (let ((*package* (find-package (standard-case-symbol-name package)))) (format t "~W~%" (eval-input s))))) (defun rep (a &optional b) (if b (read-eval-print b a) (read-eval-print a)))) (register-commands :fare-scripts/repl) (eval-when (:compile-toplevel) (uiop:println "COMPILE-TOPLEVEL")) (eval-when (:load-toplevel) (uiop:println "LOAD-TOPLEVEL")) (eval-when (:execute) (uiop:println "EXECUTE"))
4d6a402602cf6b61dfaebc2859d0b12968642e115802bc982a23f577b1a18e08
CSCfi/rems
json.clj
(ns rems.json (:require [clj-time.core :as time] [clj-time.format :as time-format] [clojure.test :refer [deftest is testing]] [cognitect.transit :as transit] [jsonista.core :as j] [muuntaja.core :as muuntaja] [schema.coerce :as coerce] [schema.core :as s]) (:import [com.fasterxml.jackson.datatype.joda JodaModule] [org.joda.time DateTime ReadableInstant DateTimeZone] [org.joda.time.format ISODateTimeFormat])) (def joda-time-writer (transit/write-handler "t" (fn [v] (-> (ISODateTimeFormat/dateTime) (.print ^ReadableInstant v))))) (def joda-time-reader (transit/read-handler time-format/parse)) (def joda-unix-time-reader (transit/read-handler #(DateTime. (Long/parseLong %) time/utc))) (def muuntaja (muuntaja/create (-> muuntaja/default-options (assoc-in [:formats "application/json" :encoder-opts :modules] [(JodaModule.)]) (assoc-in [:formats "application/transit+json" :encoder-opts :handlers] {DateTime joda-time-writer}) (assoc-in [:formats "application/transit+json" :decoder-opts :handlers] {"t" joda-time-reader "m" joda-unix-time-reader})))) (def mapper (j/object-mapper {:modules [(JodaModule.)] :decode-key-fn keyword})) (def mapper-pretty (j/object-mapper {:modules [(JodaModule.)] :pretty true :decode-key-fn keyword})) (defn generate-string [obj] (j/write-value-as-string obj mapper)) (defn generate-string-pretty [obj] (j/write-value-as-string obj mapper-pretty)) (defn parse-string [json] (j/read-value json mapper)) (deftest test-muuntaja (let [format "application/json"] (testing format (testing "encoding" (is (= "{\"date-time\":\"2000-01-01T12:00:00.000Z\"}" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)})))) (is (= "{\"date-time\":\"2000-01-01T10:00:00.000Z\"}" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 (DateTimeZone/forID "Europe/Helsinki"))}))))) (testing "decoding" ;; decoding dates from JSON requires coercion, so it's passed through as just plain string (is (= {:date-time "2000-01-01T10:00:00.000Z"} (muuntaja/decode muuntaja format "{\"date-time\":\"2000-01-01T10:00:00.000Z\"}")))))) (let [format "application/transit+json"] (testing format (testing "encoding" (is (= "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000Z\"]" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)})))) (is (= "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000+02:00\"]" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 (DateTimeZone/forID "Europe/Helsinki"))}))))) (testing "decoding" (is (= {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)} (muuntaja/decode muuntaja format "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000Z\"]"))) (is (= {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)} (muuntaja/decode muuntaja format "[\"^ \",\"~:date-time\",\"~m946728000000\"]"))))))) ;;; Utils for schema-based coercion (defn- datestring->datetime [s] (if (string? s) (time-format/parse s) s)) (def datestring-coercion-matcher {DateTime datestring->datetime}) (defn coercion-matcher [schema] (or (datestring-coercion-matcher schema) (coerce/string-coercion-matcher schema))) (deftest test-coercion-matcher (let [coercer (coerce/coercer! {:time DateTime :type s/Keyword} coercion-matcher)] (is (= {:type :foo :time (time/date-time 2019 03 04 10)} (coercer {:type "foo" :time "2019-03-04T10:00:00.000Z"})))))
null
https://raw.githubusercontent.com/CSCfi/rems/644ef6df4518b8e382cdfeadd7719e29508a26f0/src/clj/rems/json.clj
clojure
decoding dates from JSON requires coercion, so it's passed through as just plain string Utils for schema-based coercion
(ns rems.json (:require [clj-time.core :as time] [clj-time.format :as time-format] [clojure.test :refer [deftest is testing]] [cognitect.transit :as transit] [jsonista.core :as j] [muuntaja.core :as muuntaja] [schema.coerce :as coerce] [schema.core :as s]) (:import [com.fasterxml.jackson.datatype.joda JodaModule] [org.joda.time DateTime ReadableInstant DateTimeZone] [org.joda.time.format ISODateTimeFormat])) (def joda-time-writer (transit/write-handler "t" (fn [v] (-> (ISODateTimeFormat/dateTime) (.print ^ReadableInstant v))))) (def joda-time-reader (transit/read-handler time-format/parse)) (def joda-unix-time-reader (transit/read-handler #(DateTime. (Long/parseLong %) time/utc))) (def muuntaja (muuntaja/create (-> muuntaja/default-options (assoc-in [:formats "application/json" :encoder-opts :modules] [(JodaModule.)]) (assoc-in [:formats "application/transit+json" :encoder-opts :handlers] {DateTime joda-time-writer}) (assoc-in [:formats "application/transit+json" :decoder-opts :handlers] {"t" joda-time-reader "m" joda-unix-time-reader})))) (def mapper (j/object-mapper {:modules [(JodaModule.)] :decode-key-fn keyword})) (def mapper-pretty (j/object-mapper {:modules [(JodaModule.)] :pretty true :decode-key-fn keyword})) (defn generate-string [obj] (j/write-value-as-string obj mapper)) (defn generate-string-pretty [obj] (j/write-value-as-string obj mapper-pretty)) (defn parse-string [json] (j/read-value json mapper)) (deftest test-muuntaja (let [format "application/json"] (testing format (testing "encoding" (is (= "{\"date-time\":\"2000-01-01T12:00:00.000Z\"}" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)})))) (is (= "{\"date-time\":\"2000-01-01T10:00:00.000Z\"}" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 (DateTimeZone/forID "Europe/Helsinki"))}))))) (testing "decoding" (is (= {:date-time "2000-01-01T10:00:00.000Z"} (muuntaja/decode muuntaja format "{\"date-time\":\"2000-01-01T10:00:00.000Z\"}")))))) (let [format "application/transit+json"] (testing format (testing "encoding" (is (= "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000Z\"]" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)})))) (is (= "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000+02:00\"]" (slurp (muuntaja/encode muuntaja format {:date-time (DateTime. 2000 1 1 12 0 (DateTimeZone/forID "Europe/Helsinki"))}))))) (testing "decoding" (is (= {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)} (muuntaja/decode muuntaja format "[\"^ \",\"~:date-time\",\"~t2000-01-01T12:00:00.000Z\"]"))) (is (= {:date-time (DateTime. 2000 1 1 12 0 DateTimeZone/UTC)} (muuntaja/decode muuntaja format "[\"^ \",\"~:date-time\",\"~m946728000000\"]"))))))) (defn- datestring->datetime [s] (if (string? s) (time-format/parse s) s)) (def datestring-coercion-matcher {DateTime datestring->datetime}) (defn coercion-matcher [schema] (or (datestring-coercion-matcher schema) (coerce/string-coercion-matcher schema))) (deftest test-coercion-matcher (let [coercer (coerce/coercer! {:time DateTime :type s/Keyword} coercion-matcher)] (is (= {:type :foo :time (time/date-time 2019 03 04 10)} (coercer {:type "foo" :time "2019-03-04T10:00:00.000Z"})))))
9e1940a123d93694c63aa13850365dff188069d7149e47d63cf3e46cd26b2984
imandra-ai/ocaml-opentelemetry
logs_service_pb.mli
(** logs_service.proto Binary Encoding *) * { 2 Protobuf Encoding } val encode_export_logs_service_request : Logs_service_types.export_logs_service_request -> Pbrt.Encoder.t -> unit (** [encode_export_logs_service_request v encoder] encodes [v] with the given [encoder] *) val encode_export_logs_partial_success : Logs_service_types.export_logs_partial_success -> Pbrt.Encoder.t -> unit (** [encode_export_logs_partial_success v encoder] encodes [v] with the given [encoder] *) val encode_export_logs_service_response : Logs_service_types.export_logs_service_response -> Pbrt.Encoder.t -> unit (** [encode_export_logs_service_response v encoder] encodes [v] with the given [encoder] *) * { 2 Protobuf Decoding } val decode_export_logs_service_request : Pbrt.Decoder.t -> Logs_service_types.export_logs_service_request (** [decode_export_logs_service_request decoder] decodes a [export_logs_service_request] value from [decoder] *) val decode_export_logs_partial_success : Pbrt.Decoder.t -> Logs_service_types.export_logs_partial_success (** [decode_export_logs_partial_success decoder] decodes a [export_logs_partial_success] value from [decoder] *) val decode_export_logs_service_response : Pbrt.Decoder.t -> Logs_service_types.export_logs_service_response (** [decode_export_logs_service_response decoder] decodes a [export_logs_service_response] value from [decoder] *)
null
https://raw.githubusercontent.com/imandra-ai/ocaml-opentelemetry/3dc7d63c7d2c345ba13e50b67b56aff878b6d0bb/src/logs_service_pb.mli
ocaml
* logs_service.proto Binary Encoding * [encode_export_logs_service_request v encoder] encodes [v] with the given [encoder] * [encode_export_logs_partial_success v encoder] encodes [v] with the given [encoder] * [encode_export_logs_service_response v encoder] encodes [v] with the given [encoder] * [decode_export_logs_service_request decoder] decodes a [export_logs_service_request] value from [decoder] * [decode_export_logs_partial_success decoder] decodes a [export_logs_partial_success] value from [decoder] * [decode_export_logs_service_response decoder] decodes a [export_logs_service_response] value from [decoder]
* { 2 Protobuf Encoding } val encode_export_logs_service_request : Logs_service_types.export_logs_service_request -> Pbrt.Encoder.t -> unit val encode_export_logs_partial_success : Logs_service_types.export_logs_partial_success -> Pbrt.Encoder.t -> unit val encode_export_logs_service_response : Logs_service_types.export_logs_service_response -> Pbrt.Encoder.t -> unit * { 2 Protobuf Decoding } val decode_export_logs_service_request : Pbrt.Decoder.t -> Logs_service_types.export_logs_service_request val decode_export_logs_partial_success : Pbrt.Decoder.t -> Logs_service_types.export_logs_partial_success val decode_export_logs_service_response : Pbrt.Decoder.t -> Logs_service_types.export_logs_service_response
09e3703b8c93cd82fdf9ff820d6c56bb52c40944beba1aab32b8a7d1d0263d55
static-analysis-engineering/codehawk
bCHFunctionStub.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 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) 2005-2019 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021 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 CHPretty (* bchlib *) open BCHLibTypes open BCHUtilities let function_stub_to_string (s:function_stub_t) = match s with | SOFunction name -> name | DllFunction (dll,name) -> "(" ^ dll ^ ":" ^ name ^ ")" | JniFunction i -> "jni(" ^ (string_of_int i) ^ ")" | LinuxSyscallFunction i -> "linux_syscall(" ^ (string_of_int i) ^ ")" | PckFunction (lib,pckgs,name) -> "(" ^ lib ^ ":" ^ (String.concat "::" pckgs) ^ ":" ^ name let function_stub_to_pretty (s:function_stub_t) = match s with | SOFunction name -> STR name | DllFunction (dll,name) -> LBLOCK [ STR "(" ; STR dll ; STR ":" ; STR name ; STR ")" ] | JniFunction i -> LBLOCK [ STR "jni(" ; INT i ; STR ")" ] | LinuxSyscallFunction i -> LBLOCK [ STR "linux_syscall(" ; INT i ; STR ")" ] | PckFunction (lib,pckgs,name) -> LBLOCK [ STR "lib:" ; STR lib ; STR ":" ; pretty_print_list pckgs (fun s -> STR s) "" "::" "" ; STR name ; STR " (static)" ] let function_stub_compare (s1:function_stub_t) (s2:function_stub_t) = match (s1,s2) with | (SOFunction n1, SOFunction n2) -> Stdlib.compare n1 n2 | (SOFunction _, _) -> -1 | (_, SOFunction _) -> 1 | (DllFunction (l1,n1), DllFunction (l2,n2)) -> let l0 = Stdlib.compare l1 l2 in if l0 = 0 then Stdlib.compare n1 n2 else l0 | (DllFunction _, _) -> -1 | (_, DllFunction _) -> 1 | (JniFunction i1, JniFunction i2) -> Stdlib.compare i1 i2 | (JniFunction _, _) -> -1 | (_, JniFunction _) -> 1 | (LinuxSyscallFunction i1, LinuxSyscallFunction i2) -> Stdlib.compare i1 i2 | (LinuxSyscallFunction _, _) -> -1 | (_, LinuxSyscallFunction _) -> 1 | (PckFunction (lib1,p1,n1),PckFunction (lib2,p2,n2)) -> let l0 = Stdlib.compare lib1 lib2 in if l0 = 0 then let l1 = list_compare p1 p2 Stdlib.compare in if l1 = 0 then Stdlib.compare n1 n2 else l1 else l0
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/f2891d9120d5a776ea9ac1feec7bf98cce335e12/CodeHawk/CHB/bchlib/bCHFunctionStub.ml
ocaml
bchlib
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 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) 2005-2019 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021 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 CHPretty open BCHLibTypes open BCHUtilities let function_stub_to_string (s:function_stub_t) = match s with | SOFunction name -> name | DllFunction (dll,name) -> "(" ^ dll ^ ":" ^ name ^ ")" | JniFunction i -> "jni(" ^ (string_of_int i) ^ ")" | LinuxSyscallFunction i -> "linux_syscall(" ^ (string_of_int i) ^ ")" | PckFunction (lib,pckgs,name) -> "(" ^ lib ^ ":" ^ (String.concat "::" pckgs) ^ ":" ^ name let function_stub_to_pretty (s:function_stub_t) = match s with | SOFunction name -> STR name | DllFunction (dll,name) -> LBLOCK [ STR "(" ; STR dll ; STR ":" ; STR name ; STR ")" ] | JniFunction i -> LBLOCK [ STR "jni(" ; INT i ; STR ")" ] | LinuxSyscallFunction i -> LBLOCK [ STR "linux_syscall(" ; INT i ; STR ")" ] | PckFunction (lib,pckgs,name) -> LBLOCK [ STR "lib:" ; STR lib ; STR ":" ; pretty_print_list pckgs (fun s -> STR s) "" "::" "" ; STR name ; STR " (static)" ] let function_stub_compare (s1:function_stub_t) (s2:function_stub_t) = match (s1,s2) with | (SOFunction n1, SOFunction n2) -> Stdlib.compare n1 n2 | (SOFunction _, _) -> -1 | (_, SOFunction _) -> 1 | (DllFunction (l1,n1), DllFunction (l2,n2)) -> let l0 = Stdlib.compare l1 l2 in if l0 = 0 then Stdlib.compare n1 n2 else l0 | (DllFunction _, _) -> -1 | (_, DllFunction _) -> 1 | (JniFunction i1, JniFunction i2) -> Stdlib.compare i1 i2 | (JniFunction _, _) -> -1 | (_, JniFunction _) -> 1 | (LinuxSyscallFunction i1, LinuxSyscallFunction i2) -> Stdlib.compare i1 i2 | (LinuxSyscallFunction _, _) -> -1 | (_, LinuxSyscallFunction _) -> 1 | (PckFunction (lib1,p1,n1),PckFunction (lib2,p2,n2)) -> let l0 = Stdlib.compare lib1 lib2 in if l0 = 0 then let l1 = list_compare p1 p2 Stdlib.compare in if l1 = 0 then Stdlib.compare n1 n2 else l1 else l0
c12a8be9f22eb21b936ce21c6cf8d27598a0b3419c4a588afa95fbfd595d35d3
ChaosEternal/guile-scsh
syscalls.scm
;;; POSIX system-call Scheme binding. Copyright ( c ) 1993 by . See file COPYING . ;;; Scheme48 implementation. ;;; Need to rationalise names here. getgid. get-gid. "effective" as morpheme? (define-module (scsh syscalls) :use-module (scsh define-foreign-syntax) :use-module (ice-9 receive) :use-module (ice-9 optargs) :use-module (scsh optional) :use-module (srfi srfi-9) :use-module (srfi srfi-9 gnu) :use-module (scsh utilities) :use-module (scsh fname) :use-module (scsh procobj) :use-module (scsh errno) :use-module (scsh let-optionals-aster) :export (export %exec %%fork cwd user-gid user-effective-gid set-gid user-supplementary-gids user-uid user-effective-uid set-uid user-login-name pid parent-pid set-process-group become-session-leader set-umask process-times cpu-ticks/sec set-file-mode set-file-owner set-file-group read-symlink delete-directory set-file-times file-info file-info:type file-info:gid file-info:inode file-info:atime file-info:mtime file-info:ctime file-info:mode file-info:nlinks file-info:uid file-info:size sync-file sync-file-system seek/set seek/delta seek/end tell vpipe signal-process signal-process-group pause-until-interrupt itimer user-info user-info:name user-info:uid user-info:gid user-info:home-dir user-info:shell name->user-info uid->user-info ->uid ->username %homedir group-info group-info:name group-info:gid group-info:members ->gid ->groupname directory-files env->alist alist->env fdes-flags set-fdes-flags fdes-status set-fdes-status open/read open/write open/read+write open/non-blocking open/append open/exclusive open/create open/truncate open/no-control-tty open/access-mask fdflags/close-on-exec sleep sleep-until system-name)) (foreign-source "#include <sys/signal.h>" "#include <sys/types.h>" "#include <sys/times.h>" "#include <sys/time.h>" "#include <fcntl.h> /* for O_RDWR */" ; ??? "#include <sys/stat.h>" "#include <errno.h>" "#include <netdb.h>" "#include <pwd.h>" "#include <unistd.h>" "" "/* Make sure foreign-function stubs interface to the C funs correctly: */" "#include \"dirstuff1.h\"" "#include \"fdports1.h\"" "#include \"select1.h\"" "#include \"syscalls1.h\"" "#include \"userinfo1.h\"" "" "#define errno_on_zero_or_false(x) ((x) ? SCHFALSE : ENTER_FIXNUM(errno))" "#define errno_or_false(x) (((x) == -1) ? ENTER_FIXNUM(errno) : SCHFALSE)" "#define False_on_zero(x) ((x) ? ENTER_FIXNUM(x) : SCHFALSE)" ; Not a function. "" "") Macro for converting syscalls that return error codes to ones that ;;; raise exceptions on errors. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DEFINE - ERRNO - SYSCALL defines an error - signalling syscall procedure from one that returns an error code as its first return value -- # f for win , ;;; errno for lose. If the error code is ERRNO/INTR (interrupted syscall), ;;; we try again. ;;; ;;; (define-errno-syscall (SYSCALL ARGS) SYSCALL/ERRNO . RET-VALS) ==> ;;; ;;; (define (SYSCALL . ARGS) ;;; (receive (err . RET-VALS) (SYSCALL/ERRNO . ARGS) ;;; (cond ((not err) (values . RET-VALS)) ; Win ( (= err errno / intr ) ( SYSCALL . ARGS ) ) ; Retry ;;; (else (errno-error err SYSCALL . ARGS))))); Lose noop for . (defmacro define-errno-syscall args #f) ;;; Process ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-foreign %%exec/errno (scheme_exec (string prog) (vector-desc argv) string vector or # t. integer) ;(define (%%exec prog argv env) ; (errno-error (%%exec/errno prog argv env) %exec prog argv env)) ; cute. (define (%exec prog arg-list env) (if (eq? env #t) (apply execl prog arg-list) (apply execle prog (alist->env-list env) arg-list))) (define-foreign exit/errno ; errno -- misnomer. (exit (integer status)) ignore) (define-foreign %exit/errno ; errno -- misnomer (_exit (integer status)) ignore) ;; (define (%exit . maybe-status) ;; (%exit/errno (:optional maybe-status 0)) ;; (error "Yikes! %exit returned.")) (define-foreign %%fork/errno (fork) (multi-rep (to-scheme pid_t errno_or_false) pid_t)) ;;; If the fork fails, and we are doing early zombie reaping, then reap ;;; some zombies to try and free up a some space in the process table, ;;; and try again. ;;; ;;; This ugly little hack will have to stay in until I do early zombie reaping with SIGCHLD interrupts . ;(define (%%fork-with-retry/errno) ; (receive (err pid) (%%fork/errno) ( cond ( ( and err ( eq ? ' early ( autoreap - policy ) ) ) ; (reap-zombies) ; (%%fork/errno)) ; (else (values err pid))))) (define (%%fork) (let ((pid (false-if-exception (primitive-fork)))) (cond ((and (not pid) (eq? 'early (autoreap-policy))) (reap-zombies) (primitive-fork)) (else pid)))) (define-errno-syscall (%%fork) %%fork-with-retry/errno pid) waitpid(2 ) call . (define-foreign %wait-pid/errno (wait_pid (integer pid) (integer options)) errno or # f integer ; process' id integer) ; process' status ;;; Miscellaneous process state ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Working directory (define-foreign %chdir/errno (chdir (string directory)) (to-scheme integer errno_or_false)) (define-errno-syscall (%chdir dir) %chdir/errno) primitive in . ( define ( chdir . ) ( let ( ( dir (: optional maybe - dir ( home - dir ) ) ) ) ( ( ensure - file - name - is - nondirectory dir ) ) ) ) (define-foreign cwd/errno (scheme_cwd) errno or # f string) ; directory (or #f on error) (define-errno-syscall (cwd) cwd/errno dir) (define cwd getcwd) GID (define-foreign user-gid (getgid) gid_t) (define user-gid getgid) (define-foreign user-effective-gid (getegid) gid_t) (define user-effective-gid getegid) (define-foreign set-gid/errno (setgid (gid_t id)) no-declare ; for SunOS 4.x (to-scheme integer errno_or_false)) (define-errno-syscall (set-gid gid) set-gid/errno) (define set-gid setgid) (define-foreign %num-supplementary-gids/errno (num_supp_groups) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign load-groups/errno (get_groups (vector-desc group-vec)) (multi-rep (to-scheme integer errno_or_false) integer)) (define (user-supplementary-gids) (vector->list (getgroups))) UID (define-foreign user-uid (getuid) uid_t) (define user-uid getuid) (define-foreign user-effective-uid (geteuid) uid_t) (define user-effective-uid geteuid) (define-foreign set-uid/errno (setuid (uid_t id)) no-declare ; for SunOS 4.x (to-scheme integer errno_or_false)) (define-errno-syscall (set-uid uid_t) set-uid/errno) (define set-uid setuid) (define-foreign %user-login-name (my_username) static-string) (define (user-login-name) (vector-ref (getpwuid (getuid)) 0)) ;;; PID (define-foreign pid (getpid) pid_t) (define pid getpid) (define-foreign parent-pid (getppid) pid_t) (define parent-pid getppid) ;;; Process groups and session ids ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-foreign process-group (getpgrp) pid_t) (define process-group getpgrp) (define-foreign %set-process-group/errno (setpgid (pid_t pid) (pid_t groupid)) (to-scheme integer errno_or_false)) (define-errno-syscall (%set-process-group pid pgrp) %set-process-group/errno) (define (set-process-group arg1 . maybe-arg2) (receive (pid pgrp) (if (null? maybe-arg2) (values (pid) arg1) (values arg1 (car maybe-arg2))) (setpgid pid pgrp))) (define-foreign become-session-leader/errno (setsid) (multi-rep (to-scheme pid_t errno_or_false) pid_t)) (define-errno-syscall (become-session-leader) become-session-leader/errno sid) (define become-session-leader setsid) ;;; UMASK integer on SunOS mode_t) primitive in . ;;(define (umask) ;; (let ((m (set-umask 0))) ;; (set-umask m) ;; m)) (define (set-umask newmask) (umask newmask)) ;;; PROCESS TIMES OOPS : The POSIX times ( ) has a mildly useful ret value we are throwing away . OOPS : The ret values should be clock_t , not int , but cig ca n't handle it . (define-foreign process-times/errno (process_times) (to-scheme integer errno_or_false) integer ; user cpu time integer ; system cpu time integer ; user cpu time for me and all my descendants. integer) ; system cpu time for me and all my descendants. (define-errno-syscall (process-times) process-times/errno utime stime cutime cstime) (define (process-times) (let ((obj (times))) (values (tms:utime obj) (tms:stime obj) (tms:cutime obj) (tms:cstime obj)))) (define-foreign cpu-ticks/sec (cpu_clock_ticks_per_sec) integer) (define cpu-ticks/sec internal-time-units-per-second) ;;; File system ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Useful little utility for generic ops that work on filenames, fd's or ;;; ports. ;(define (generic-file-op thing fd-op fname-op) ; (if (string? thing) (fname-op thing) ; (call/fdes thing fd-op))) (define-foreign set-file-mode/errno integer on SunOS (to-scheme integer errno_or_false)) IBM 's AIX include files declare fchmod(char * , mode_t ) . ; Amazing, but true. So we must prevent this def-foreign from issuing the conflicting , correct declaration . Hence the NO - DECLARE . (define-foreign set-fdes-mode/errno integer on SunOS Workaround for AIX bug . (to-scheme integer errno_or_false)) (define-errno-syscall (set-file-mode thing mode) (lambda (thing mode) (generic-file-op thing (lambda (fd) (set-fdes-mode/errno fd mode)) (lambda (fname) (set-file-mode/errno fname mode))))) (define set-file-mode chmod) NO - DECLARE : gcc unistd.h bogusness . (define-foreign set-file-uid&gid/errno (chown (string path) (uid_t uid) (gid_t gid)) no-declare (to-scheme integer errno_or_false)) (define-foreign set-fdes-uid&gid/errno for NT (to-scheme integer errno_or_false)) (define-errno-syscall (set-file-owner thing uid) (lambda (thing uid) (generic-file-op thing (lambda (fd) (set-fdes-uid&gid/errno fd uid -1)) (lambda (fname) (set-file-uid&gid/errno fname uid -1))))) (define (set-file-owner thing uid) (chown thing uid -1)) (define-errno-syscall (set-file-group thing gid) (lambda (thing gid) (generic-file-op thing (lambda (fd) (set-fdes-uid&gid/errno fd -1 gid)) (lambda (fname) (set-file-uid&gid/errno fname -1 gid))))) (define (set-file-group thing gid) (chown thing -1 gid)) ;;; Uses real uid and gid, not effective. I don't use this anywhere. (define-foreign %file-ruid-access-not? (access (string path) (integer perms)) bool) ;(define (file-access? path perms) ; (not (%file-access-not? path perms))) ; ;(define (file-executable? fname) ( file - access ? fname 1 ) ) ; ;(define (file-writable? fname) ( file - access ? fname 2 ) ) ; ;(define (file-readable? fname) ( file - access ? fname 4 ) ) ;; defined in filesys.scm. (define-foreign create-hard-link/errno (link (string original-name) (string new-name)) (to-scheme integer errno_or_false)) (define-errno-syscall (create-hard-link original-name new-name) create-hard-link/errno) (define-foreign create-fifo/errno (mkfifo (string path) (mode_t mode)) integer on SunOS (to-scheme integer errno_or_false)) (define-errno-syscall (create-fifo path mode) create-fifo/errno) (define-foreign create-directory/errno integer on SunOS . (to-scheme integer errno_or_false)) ;;(define (create-directory path . maybe-mode) ;; (let ((mode (:optional maybe-mode #o777)) ;; (fname (ensure-file-name-is-nondirectory path))) ;; (cond ((create-directory/errno fname mode) => ;; (lambda (err) ;; (if err (errno-error err create-directory path mode))))))) (define-foreign read-symlink/errno (scm_readlink (string path)) NULL = , otw # f static-string)) (define-errno-syscall (read-symlink path) read-symlink/errno new-path) (define read-symlink readlink) (define-foreign %rename-file/errno (rename (string old-name) (string new-name)) (to-scheme integer errno_or_false)) (define-errno-syscall (%rename-file old-name new-name) %rename-file/errno) (define-foreign delete-directory/errno (rmdir (string path)) (to-scheme integer errno_or_false)) (define-errno-syscall (delete-directory path) delete-directory/errno) (define delete-directory rmdir) (define-foreign %utime/errno (scm_utime (string path) (integer ac_hi) (integer ac_lo) (integer m_hi) (integer m_lo)) (to-scheme integer errno_or_false)) (define-foreign %utime-now/errno (scm_utime_now (string path)) (to-scheme integer errno_or_false)) ( SET - FILE - TIMES / ERRNO path [ access - time mod - time ] ) (define (set-file-times path . maybe-times) (if (pair? maybe-times) (let* ((access-time (real->exact-integer (car maybe-times))) (mod-time (if (pair? (cddr maybe-times)) (error "Too many arguments to set-file-times/errno" (cons path maybe-times)) (real->exact-integer (cadr maybe-times))))) (utime path access-time mod-time)) (utime path))) (define-errno-syscall (set-file-times . args) set-file-times/errno) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; STAT (define-foreign stat-file/errno (scheme_stat (string path) (vector-desc data) (bool chase?)) errno or # f ;(define-errno-syscall (stat-file fd data chase?) stat-file/errno) (define-foreign stat-fdes/errno (scheme_fstat (integer fd) (vector-desc data)) errno or # f ;(define-errno-syscall (stat-fdes fd data) stat-fdes/errno) (define-record-type file-info-type (make-file-info type device inode mode nlinks uid gid size atime mtime ctime ) file-info? (type file-info:type) (device file-info:device) (inode file-info:inode) (mode file-info:mode) (nlinks file-info:nlinks) (uid file-info:uid) (gid file-info:gid) (size file-info:size) (atime file-info:atime) (mtime file-info:mtime) (ctime file-info:ctime)) (define (file-info fd/port/fname . maybe-chase?) (let ((chase? (:optional maybe-chase? #t))) (let ((info (if (or chase? (not (string? fd/port/fname))) (stat fd/port/fname) (lstat fd/port/fname)))) (make-file-info (stat:type info) (stat:dev info) (stat:ino info) (stat:mode info) (stat:nlink info) (stat:uid info) (stat:gid info) (stat:size info) (stat:atime info) (stat:mtime info) (stat:ctime info))))) ;;; "no-declare" as there is no agreement among the OS's as to whether or not ;;; the OLD-NAME arg is "const". It *should* be const. (define-foreign create-symlink/errno (symlink (string old-name) (string new-name)) no-declare (to-scheme integer errno_or_false)) ;(define-errno-syscall (create-symlink old-name new-name) ; create-symlink/errno) ;;; "no-declare" as there is no agreement among the OS's as to whether or not ;;; the PATH arg is "const". It *should* be const. (define-foreign truncate-file/errno (truncate (string path) (off_t length)) no-declare (to-scheme integer errno_or_false)) (define-foreign truncate-fdes/errno Indigo bogosity . (to-scheme integer errno_or_false)) (define-errno-syscall (truncate-file path length) (lambda (thing length) (generic-file-op thing (lambda (fd) (truncate-fdes/errno fd length)) (lambda (fname) (truncate-file/errno fname length))))) (define-foreign delete-file/errno (unlink (string path)) (to-scheme integer errno_or_false)) (define-errno-syscall (delete-file path) delete-file/errno) (define-foreign sync-file/errno (fsync (integer fd)) (to-scheme integer errno_or_false)) (define sync-file fsync) ;;; Amazingly bogus syscall -- doesn't *actually* sync the filesys. Linux sux - says int ignore) (define sync-file-system sync) ;;; I/O ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-foreign %close-fdes/errno (close (integer fd)) (to-scheme integer "errno_or_false")) ;;(define (%close-fdes fd) ;; (let lp () ;; (let ((errno (%close-fdes/errno fd))) ;; (cond ((not errno) #t) ; Successful close. ;; ((= errno errno/badf) #f) ; File descriptor already closed. ;; ((= errno errno/intr) (lp)) ; Retry. ;; (else ;; (errno-error errno %close-fdes fd)))))) ; You lose. (define-foreign %dup/errno (dup (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%dup fd) %dup/errno new-fd) (define-foreign %dup2/errno (dup2 (integer fd-from) (integer fd-to)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%dup2 fd-from fd-to) %dup2/errno new-fd) (define-foreign %fd-seek/errno (lseek (integer fd) (off_t offset) (integer whence)) (multi-rep (to-scheme off_t errno_or_false) off_t)) (define seek/set SEEK_SET) ;Unix codes for "whence" (define seek/delta SEEK_CUR) (define seek/end SEEK_END) ;(define (seek fd/port offset . maybe-whence) ; (let ((whence (:optional maybe-whence seek/set))) ; (receive (err cursor) ; ((if (integer? fd/port) %fd-seek/errno %fdport-seek/errno) ; fd/port ; offset ; whence) ; (if err (errno-error err seek fd/port offset whence) cursor)))) (define tell ftell) (define-foreign %char-ready-fdes?/errno (char_ready_fdes (integer fd)) desc) ; errno, #t, or #f ;;(define (%char-ready-fdes? fd) ;; (let ((retval (%char-ready-fdes?/errno fd))) ;; (if (integer? retval) (errno-error retval %char-ready-fdes? fd) ;; retval))) (define-foreign %open/errno (open (string path) (integer flags) integer on SunOS no-declare ; NOTE (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%open path flags mode) %open/errno fd) ( define ( open - fdes path flags . maybe - mode ) ; mode defaults to 0666 ;; (%open path flags (:optional maybe-mode #o666))) (define-foreign pipe-fdes/errno (scheme_pipe) (to-scheme integer "False_on_zero") ; Win: #f, lose: errno integer ; r integer) ; w (define-errno-syscall (pipe-fdes) pipe-fdes/errno r w) (define vpipe (lambda () (let ((rv (pipe))) (values (car rv) (cdr rv))))) (define-foreign %read-fdes-char (read_fdes_char (integer fd)) or errno or # f ( eof ) . ;;(define (read-fdes-char fd) ;; (let ((c (%read-fdes-char fd))) ;; (if (integer? c) (errno-error c read-fdes-char fd) c))) (define-foreign write-fdes-char/errno (write_fdes_char (char char) (integer fd)) (to-scheme integer errno_or_false)) (define-errno-syscall (write-fdes-char char fd) write-fdes-char/errno) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Read and write (define-foreign read-fdes-substring!/errno (read_fdes_substring (string-desc buf) (integer start) (integer end) (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign write-fdes-substring/errno (write_fdes_substring (string-desc buf) (integer start) (integer end) (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) ;;; Signals (rather incomplete) ;;; --------------------------- (define-foreign signal-pid/errno (kill (pid_t pid) (integer signal)) (to-scheme integer errno_or_false)) (define-errno-syscall (signal-pid pid signal) signal-pid/errno) (define (signal-process proc signal) (kill (cond ((proc? proc) (proc:pid proc)) ((integer? proc) proc) (else (error "Illegal proc passed to signal-process" proc))) signal)) (define (signal-process-group proc-group signal) (kill (- (cond ((proc? proc-group) (proc:pid proc-group)) ((integer? proc-group) proc-group) (else (error "Illegal proc passed to signal-process-group" proc-group)))) signal)) ;;; SunOS, not POSIX: ;;; (define-foreign signal-process-group/errno ( killpg ( integer proc - group ) ( integer signal ) ) ;;; (to-scheme integer errno_or_false)) ;;; ;;; (define-errno-syscall (signal-process-group proc-group signal) ;;; signal-process-group/errno) (define-foreign pause-until-interrupt (pause) no-declare ignore) (define pause-until-interrupt pause) (define-foreign itimer (alarm (uint_t secs)) uint_t) (define itimer alarm) ;;; User info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-record-type user-info-type (make-user-info name uid gid home-dir shell) user-info? (name user-info:name) (uid user-info:uid) (gid user-info:gid) (home-dir user-info:home-dir) (shell user-info:shell)) (set-record-type-printer! user-info-type (lambda (ui port) (format port "#{user-info ~a}" (user-info:name ui)))) (define-foreign %uid->user-info (user_info_uid (uid_t uid)) bool ; win? static-string ; name gid_t ; gid static-string ; home-dir static-string); shell (define-foreign %name->user-info (user_info_name (string name)) bool ; win? uid gid_t ; gid static-string ; home-dir static-string); shell (define (user-info uid/name) (let ((info (getpw uid/name))) (make-user-info (passwd:name info) (passwd:uid info) (passwd:gid info) (passwd:dir info) (passwd:shell info)))) (define name->user-info user-info) (define uid->user-info user-info) ;;; Derived functions (define (->uid uid/name) (user-info:uid (user-info uid/name))) (define (->username uid/name) (user-info:name (user-info uid/name))) (define (%homedir uid/name) (user-info:home-dir (user-info uid/name))) ;;; Group info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-record-type group-info-type (make-group-info name gid members) group-info? (name user-info:name) (gid user-info:gid) (members user-info:members)) (set-record-type-printer! user-info-type (lambda (gi port) (format port "#{group-info ~a}" (user-info:name gi)))) ;;; These guys return static structs, so they aren't reentrant. ;;; Must be fixed for threaded version. (define-foreign %gid->group-info (group_info_gid (integer gid)) bool ; win? static-string ; name (C char**) ; members integer) ; num members (define-foreign %name->group-info (group_info_name (string name)) bool ; win? integer ; gid (C char**) ; members integer) ; num members (define (group-info gid/name) (let ((info (getgr gid/name))) (make-group-info (group:name info) (group:gid info) (group:mem info)))) ;;; Derived functions (define (->gid name) (group-info:gid (group-info name))) (define (->groupname gid) (group-info:name (group-info gid))) ;;; Directory stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-foreign %open-dir (open_dir (string dir-name)) (to-scheme integer "False_on_zero") ; Win: #f, lose: errno (C char**) ; Vector of strings integer) ; Length of strings ;;; Takes a null-terminated C vector of strings -- filenames. ;;; Sorts them in place by the Unix filename order: ., .., dotfiles, others. (define-foreign %sort-file-vector (scm_sort_filevec ((C "const char** ~a") cvec) (integer veclen)) ignore) (define (directory-files . args) (let-optionals* args ((dir ".") (dotfiles? #f)) (check-arg string? dir directory-files) (let ((dport (opendir (ensure-file-name-is-nondirectory dir)))) (let loop ((result '())) (let ((entry (readdir dport))) (cond ((eof-object? entry) (closedir dport) (sort! result string<?)) ((or (and (not dotfiles?) (char=? #\. (string-ref entry 0))) (string=? "." entry) (string=? ".." entry)) (loop result)) (else (loop (cons entry result))))))))) ;;; I do this one in C, I'm not sure why: ;;; It is used by MATCH-FILES. ;;; 99/7: No one is using this function, so I'm commenting it out. Later , we could tune up the globber or regexp file - matcher to use ;;; it (but should shift it into the rx directory). But I should also go ;;; to a file-at-a-time cursor model for directory fetching. -Olin ;(define-foreign %filter-C-strings! ( filter_stringvec ( string - desc pattern ) ( ( C " char const * * ~a " ) cvec ) ) ; integer) ; number of files that pass the filter. ; guile version. ( define ( % filter - C - strings ! ) ; (let ((rx (make-regexp pattern)) ; (len (vector-length vec))) ; (let loop ((i 0) (j 0)) ; (if (= i len) ( values # f j ) ; (loop (+ i 1) ( if ( regexp - exec rx ( vector - ref vec i ) ) ; (begin ( vector - set ! j ( vector - ref vec i ) ) ; (+ j 1)) ; j)))))) ;(define (match-files regexp . maybe-dir) ( let ( ( dir (: optional maybe - dir " . " ) ) ) ; (check-arg string? dir match-files) ( receive ( err ) ; (%open-dir (ensure-file-name-is-nondirectory dir)) ( if err ( errno - error err match - files regexp ) ) ( receive ( numfiles ) ( % filter - C - strings ! ) ; ;(if err (error err match-files)) ( % sort - file - vector ) ( let ( ( files ( C - string - ) ) ) ; (vector->list files)))))) ;;; Environment manipulation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( var . ) / " var = val " rep conversion : (define (split-env-string var=val) (let ((i (string-index var=val #\=))) (if i (values (substring var=val 0 i) (substring var=val (+ i 1) (string-length var=val))) (error "No \"=\" in environment string" var=val)))) (define (env-list->alist env-list) (map (lambda (var=val) (call-with-values (lambda () (split-env-string var=val)) cons)) env-list)) ;; guile version uses lists instead of vectors. ; (define (alist->env-vec alist) (define (alist->env-list alist) (map (lambda (var.val) (string-append (car var.val) "=" (cdr var.val))) alist)) ;;; ENV->ALIST (define-foreign %load-env (scm_envvec) (C char**) ; char **environ fixnum) ; & its length. ;(define (env->list) ; (receive (C-env nelts) (%load-env) ; (vector->list (C-string-vec->Scheme C-env nelts)))) (define (env->alist) (env-list->alist (environ))) ;;; ALIST->ENV (define-foreign %install-env/errno (install_env (vector-desc env-vec)) (to-scheme integer errno_or_false)) (define-errno-syscall (%install-env env-vec) %install-env/errno) (define (alist->env alist) (environ (alist->env-list alist))) , PUTENV , SETENV (define-foreign getenv (getenv (string var)) static-string) (foreign-source "#define errno_on_nonzero_or_false(x) ((x) ? ENTER_FIXNUM(errno) : SCHFALSE)" "" "") ( define - foreign putenv / errno ( put_env ( string var = ) ) ; desc) ; #f or errno ;;; putenv takes a constant: const char *, cig can't figure that out.. (define-foreign putenv/errno (putenv (string-copy var=val)) no-declare (to-scheme integer errno_on_nonzero_or_false)) ; #f or errno (define-foreign delete-env (delete_env (string var)) ignore) primitive in . ;; (define (putenv var=val) ( if ( putenv / errno var = ) ( error " malloc failure in putenv " var = ) ) ) ;; in 's boot-9.scm . ;; (define (setenv var val) ;; (if val ( putenv ( string - append var " = " ) ) ;; (delete-env var))) ;;; Fd-ports ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-foreign close-fdport*/errno (close_fdport (desc data)) (to-scheme integer "False_on_zero")) ; Win: #f, lose: errno ;;(define (close-fdport* data) ;; (let lp () ;; (let ((errno (close-fdport*/errno data))) ;; (cond ((not errno) #t) ; Successful close. ;; ((= errno errno/badf) #f) ; File descriptor already closed. ;; ((= errno errno/intr) (lp)) ; Retry. ;; (else ;; (errno-error errno close-fdport* data)))))) ; You lose. (define-foreign %fdport*-read-char/errno (fdport_getchar (desc data)) desc) ; char, errno, or #f for end-of-file. ;;(define (%fdport*-read-char data) ;; (let ((c (%fdport*-read-char/errno data))) ;; (if (integer? c) ( if (= c errno / intr ) ;; (%fdport*-read-char data) ; Retry ( errno - error c % fdport*-read - char data ) ) ; Lose ;; (or c eof-object)))) ; Win (define-foreign %fdport*-char-ready?/errno (fdport_char_readyp (desc data)) desc) ( define ( % fdport*-char - ready ? data ) ( let ( ( ( % fdport*-char - ready?/errno data ) ) ) ( if ( integer ? ) ( errno - error val % fdport*-char - ready ? data ) ;; val))) (define-foreign %fdport*-write-char/errno (fdport_putchar (desc data) (char c)) (to-scheme integer "False_on_zero")) ; Win: #f, lose: errno (define-errno-syscall (%fdport*-write-char desc c) %fdport*-write-char/errno) (define-foreign flush-fdport*/errno (flush_fdport (desc data)) (to-scheme integer "False_on_zero")) ; Win: #f, lose: errno FLUSH - FDPORT * is n't defined with DEFINE - ERRNO - SYSCALL because that would ;;; return 0 values, which blows up S48's extended-port machinery. This version returns # f. ;;; ??? ;;(define (flush-fdport* data) ;; (cond ((flush-fdport*/errno data) => ( lambda ( err ) ( if (= err errno / intr ) ;; (flush-fdport* data) ;; (errno-error err flush-fdport* data)))) ;; (else #f))) (define-foreign flush-all-ports/errno (flush_all_ports) (to-scheme integer errno_or_false)) (define-errno-syscall (flush-all-ports) flush-all-ports/errno) (define-foreign %fdport*-seek/errno (seek_fdport (desc data) (off_t offset) (integer whence)) (to-scheme integer "False_on_zero") ; errno integer) ; new position (define-foreign %fdport*-tell/errno (tell_fdport (desc data)) (to-scheme integer "False_on_zero") ; errno integer) (define-foreign %fdport*-set-buffering/errno (set_fdbuf (desc data) (integer policy) (integer size)) (to-scheme integer "False_on_zero")) ; errno (define-foreign %set-cloexec (set_cloexec (integer fd) (bool val)) (to-scheme integer "errno_or_false")) (define-foreign %init-fdports! (init_fdports) ignore) (define-foreign %install-port/errno (install_port (integer fd) (desc port) (integer revealed)) (to-scheme integer "False_on_zero")) ; Win: #f, lose: errno (define-errno-syscall (%install-port fd port revealed) %install-port/errno) (define-foreign %maybe-fdes->port (maybe_fdes2port (integer fd)) desc) ; fd or #f ;;; Doesn't signal on error. Clients must check return value. (define-foreign %move-fdport (move_fdport (integer fd) (desc port) (integer new-revealed-count)) bool) ; Win: #f, lose: #t (define-foreign read-fdport*-substring!/errno (read_fdport_substring (string-desc buf) (integer start) (integer end) (desc data)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign write-fdport*-substring/errno (write_fdport_substring (string-desc buf) (integer start) (integer end) (desc fdport)) (multi-rep (to-scheme integer errno_or_false) integer)) ;;; Some of fcntl() ;;;;;;;;;;;;;;;;;;; (define-foreign %fcntl-read/errno (fcntl_read (fixnum fd) (fixnum command)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign %fcntl-write/errno (fcntl_write (fixnum fd) (fixnum command) (fixnum val)) (to-scheme integer errno_or_false)) (define-errno-syscall (%fcntl-read fd command) %fcntl-read/errno value) (define-errno-syscall (%fcntl-write fd command val) %fcntl-write/errno) ;;; fcntl()'s F_GETFD and F_SETFD. Note that the SLEAZY- prefix on the ;;; CALL/FDES isn't an optimisation; it's *required* for the correct behaviour ;;; of these procedures. Straight CALL/FDES modifies unrevealed file descriptors by clearing their CLOEXEC bit when it reveals them -- so it ;;; would interfere with the reading and writing of that bit! (define (fdes-flags fd/port) (fcntl fd/port F_GETFD)) (define (set-fdes-flags fd/port flags) (fcntl fd/port F_SETFD flags)) fcntl ( ) 's F_GETFL and F_SETFL . ;;; Get: Returns open flags + get-status flags (below) Set : append , sync , async , nbio , nonblocking , no - delay (define (fdes-status fd/port) (fcntl fd/port F_GETFL)) (define (set-fdes-status fd/port flags) (fcntl fd/port F_SETFL flags)) (define open/read O_RDONLY) (define open/write O_WRONLY) (define open/read+write O_RDWR) (define open/non-blocking O_NONBLOCK) (define open/append O_APPEND) (define open/exclusive O_EXCL) (define open/create O_CREAT) (define open/truncate O_TRUNC) (define open/no-control-tty O_NOCTTY) (define open/access-mask (logior open/read open/write open/read+write)) (define fdflags/close-on-exec FD_CLOEXEC) ;;; Miscellaneous ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; usleep(3 ): Try to sleep for USECS microseconds . sleep(3 ): Try to sleep for SECS seconds . De - released -- not POSIX and not on SGI systems . ( define - foreign usleep ( usleep ( integer usecs ) ) integer ) 's sleep can be interrupted so define using sleep - until . (define (sleep secs) (sleep-until (+ secs (current-time)))) (define guile-sleep (module-ref (resolve-module '(guile)) 'sleep)) (define (sleep-until when) (let ((now (current-time)) (iwhen (inexact->exact when))) (if (> iwhen now) (if (> (guile-sleep (- iwhen now)) 0) (sleep-until when))))) (define-foreign %sleep-until (sleep_until (fixnum hi) (fixnum lo)) desc) (define-foreign %gethostname (scm_gethostname) static-string) (define (system-name) (utsname:nodename (uname))) (define-foreign errno-msg (errno_msg (integer i)) static-string) (define errno-msg strerror)
null
https://raw.githubusercontent.com/ChaosEternal/guile-scsh/1a76e006e193a6a8c9f93d23bacb9e51a1ff6c4c/scsh/syscalls.scm
scheme
POSIX system-call Scheme binding. Scheme48 implementation. Need to rationalise names here. getgid. get-gid. "effective" as morpheme? ??? Not a function. raise exceptions on errors. errno for lose. If the error code is ERRNO/INTR (interrupted syscall), we try again. (define-errno-syscall (SYSCALL ARGS) SYSCALL/ERRNO . RET-VALS) ==> (define (SYSCALL . ARGS) (receive (err . RET-VALS) (SYSCALL/ERRNO . ARGS) (cond ((not err) (values . RET-VALS)) ; Win Retry (else (errno-error err SYSCALL . ARGS))))); Lose Process (define (%%exec prog argv env) (errno-error (%%exec/errno prog argv env) %exec prog argv env)) ; cute. errno -- misnomer. errno -- misnomer (define (%exit . maybe-status) (%exit/errno (:optional maybe-status 0)) (error "Yikes! %exit returned.")) If the fork fails, and we are doing early zombie reaping, then reap some zombies to try and free up a some space in the process table, and try again. This ugly little hack will have to stay in until I do early (define (%%fork-with-retry/errno) (receive (err pid) (%%fork/errno) (reap-zombies) (%%fork/errno)) (else (values err pid))))) process' id process' status Miscellaneous process state Working directory directory (or #f on error) for SunOS 4.x for SunOS 4.x PID Process groups and session ids UMASK (define (umask) (let ((m (set-umask 0))) (set-umask m) m)) PROCESS TIMES user cpu time system cpu time user cpu time for me and all my descendants. system cpu time for me and all my descendants. File system Useful little utility for generic ops that work on filenames, fd's or ports. (define (generic-file-op thing fd-op fname-op) (if (string? thing) (fname-op thing) (call/fdes thing fd-op))) Amazing, but true. So we must prevent this def-foreign from issuing Uses real uid and gid, not effective. I don't use this anywhere. (define (file-access? path perms) (not (%file-access-not? path perms))) (define (file-executable? fname) (define (file-writable? fname) (define (file-readable? fname) defined in filesys.scm. (define (create-directory path . maybe-mode) (let ((mode (:optional maybe-mode #o777)) (fname (ensure-file-name-is-nondirectory path))) (cond ((create-directory/errno fname mode) => (lambda (err) (if err (errno-error err create-directory path mode))))))) STAT (define-errno-syscall (stat-file fd data chase?) stat-file/errno) (define-errno-syscall (stat-fdes fd data) stat-fdes/errno) "no-declare" as there is no agreement among the OS's as to whether or not the OLD-NAME arg is "const". It *should* be const. (define-errno-syscall (create-symlink old-name new-name) create-symlink/errno) "no-declare" as there is no agreement among the OS's as to whether or not the PATH arg is "const". It *should* be const. Amazingly bogus syscall -- doesn't *actually* sync the filesys. I/O (define (%close-fdes fd) (let lp () (let ((errno (%close-fdes/errno fd))) (cond ((not errno) #t) ; Successful close. ((= errno errno/badf) #f) ; File descriptor already closed. ((= errno errno/intr) (lp)) ; Retry. (else (errno-error errno %close-fdes fd)))))) ; You lose. Unix codes for "whence" (define (seek fd/port offset . maybe-whence) (let ((whence (:optional maybe-whence seek/set))) (receive (err cursor) ((if (integer? fd/port) %fd-seek/errno %fdport-seek/errno) fd/port offset whence) (if err (errno-error err seek fd/port offset whence) cursor)))) errno, #t, or #f (define (%char-ready-fdes? fd) (let ((retval (%char-ready-fdes?/errno fd))) (if (integer? retval) (errno-error retval %char-ready-fdes? fd) retval))) NOTE mode defaults to 0666 (%open path flags (:optional maybe-mode #o666))) Win: #f, lose: errno r w (define (read-fdes-char fd) (let ((c (%read-fdes-char fd))) (if (integer? c) (errno-error c read-fdes-char fd) c))) Read and write Signals (rather incomplete) --------------------------- SunOS, not POSIX: (define-foreign signal-process-group/errno (to-scheme integer errno_or_false)) (define-errno-syscall (signal-process-group proc-group signal) signal-process-group/errno) User info win? name gid home-dir shell win? gid home-dir shell Derived functions Group info These guys return static structs, so they aren't reentrant. Must be fixed for threaded version. win? name members num members win? gid members num members Derived functions Directory stuff Win: #f, lose: errno Vector of strings Length of strings Takes a null-terminated C vector of strings -- filenames. Sorts them in place by the Unix filename order: ., .., dotfiles, others. I do this one in C, I'm not sure why: It is used by MATCH-FILES. 99/7: No one is using this function, so I'm commenting it out. it (but should shift it into the rx directory). But I should also go to a file-at-a-time cursor model for directory fetching. -Olin (define-foreign %filter-C-strings! integer) ; number of files that pass the filter. guile version. (let ((rx (make-regexp pattern)) (len (vector-length vec))) (let loop ((i 0) (j 0)) (if (= i len) (loop (+ i 1) (begin (+ j 1)) j)))))) (define (match-files regexp . maybe-dir) (check-arg string? dir match-files) (%open-dir (ensure-file-name-is-nondirectory dir)) ;(if err (error err match-files)) (vector->list files)))))) Environment manipulation guile version uses lists instead of vectors. (define (alist->env-vec alist) ENV->ALIST char **environ & its length. (define (env->list) (receive (C-env nelts) (%load-env) (vector->list (C-string-vec->Scheme C-env nelts)))) ALIST->ENV desc) ; #f or errno putenv takes a constant: const char *, cig can't figure that out.. #f or errno (define (putenv var=val) (define (setenv var val) (if val (delete-env var))) Fd-ports Win: #f, lose: errno (define (close-fdport* data) (let lp () (let ((errno (close-fdport*/errno data))) (cond ((not errno) #t) ; Successful close. ((= errno errno/badf) #f) ; File descriptor already closed. ((= errno errno/intr) (lp)) ; Retry. (else (errno-error errno close-fdport* data)))))) ; You lose. char, errno, or #f for end-of-file. (define (%fdport*-read-char data) (let ((c (%fdport*-read-char/errno data))) (if (integer? c) (%fdport*-read-char data) ; Retry Lose (or c eof-object)))) ; Win val))) Win: #f, lose: errno Win: #f, lose: errno return 0 values, which blows up S48's extended-port machinery. This ??? (define (flush-fdport* data) (cond ((flush-fdport*/errno data) => (flush-fdport* data) (errno-error err flush-fdport* data)))) (else #f))) errno new position errno errno Win: #f, lose: errno fd or #f Doesn't signal on error. Clients must check return value. Win: #f, lose: #t Some of fcntl() fcntl()'s F_GETFD and F_SETFD. Note that the SLEAZY- prefix on the CALL/FDES isn't an optimisation; it's *required* for the correct behaviour of these procedures. Straight CALL/FDES modifies unrevealed file would interfere with the reading and writing of that bit! Get: Returns open flags + get-status flags (below) Miscellaneous
Copyright ( c ) 1993 by . See file COPYING . (define-module (scsh syscalls) :use-module (scsh define-foreign-syntax) :use-module (ice-9 receive) :use-module (ice-9 optargs) :use-module (scsh optional) :use-module (srfi srfi-9) :use-module (srfi srfi-9 gnu) :use-module (scsh utilities) :use-module (scsh fname) :use-module (scsh procobj) :use-module (scsh errno) :use-module (scsh let-optionals-aster) :export (export %exec %%fork cwd user-gid user-effective-gid set-gid user-supplementary-gids user-uid user-effective-uid set-uid user-login-name pid parent-pid set-process-group become-session-leader set-umask process-times cpu-ticks/sec set-file-mode set-file-owner set-file-group read-symlink delete-directory set-file-times file-info file-info:type file-info:gid file-info:inode file-info:atime file-info:mtime file-info:ctime file-info:mode file-info:nlinks file-info:uid file-info:size sync-file sync-file-system seek/set seek/delta seek/end tell vpipe signal-process signal-process-group pause-until-interrupt itimer user-info user-info:name user-info:uid user-info:gid user-info:home-dir user-info:shell name->user-info uid->user-info ->uid ->username %homedir group-info group-info:name group-info:gid group-info:members ->gid ->groupname directory-files env->alist alist->env fdes-flags set-fdes-flags fdes-status set-fdes-status open/read open/write open/read+write open/non-blocking open/append open/exclusive open/create open/truncate open/no-control-tty open/access-mask fdflags/close-on-exec sleep sleep-until system-name)) (foreign-source "#include <sys/signal.h>" "#include <sys/types.h>" "#include <sys/times.h>" "#include <sys/time.h>" "#include <sys/stat.h>" "#include <errno.h>" "#include <netdb.h>" "#include <pwd.h>" "#include <unistd.h>" "" "/* Make sure foreign-function stubs interface to the C funs correctly: */" "#include \"dirstuff1.h\"" "#include \"fdports1.h\"" "#include \"select1.h\"" "#include \"syscalls1.h\"" "#include \"userinfo1.h\"" "" "#define errno_on_zero_or_false(x) ((x) ? SCHFALSE : ENTER_FIXNUM(errno))" "#define errno_or_false(x) (((x) == -1) ? ENTER_FIXNUM(errno) : SCHFALSE)" "" "") Macro for converting syscalls that return error codes to ones that DEFINE - ERRNO - SYSCALL defines an error - signalling syscall procedure from one that returns an error code as its first return value -- # f for win , noop for . (defmacro define-errno-syscall args #f) (define-foreign %%exec/errno (scheme_exec (string prog) (vector-desc argv) string vector or # t. integer) (define (%exec prog arg-list env) (if (eq? env #t) (apply execl prog arg-list) (apply execle prog (alist->env-list env) arg-list))) (exit (integer status)) ignore) (_exit (integer status)) ignore) (define-foreign %%fork/errno (fork) (multi-rep (to-scheme pid_t errno_or_false) pid_t)) zombie reaping with SIGCHLD interrupts . ( cond ( ( and err ( eq ? ' early ( autoreap - policy ) ) ) (define (%%fork) (let ((pid (false-if-exception (primitive-fork)))) (cond ((and (not pid) (eq? 'early (autoreap-policy))) (reap-zombies) (primitive-fork)) (else pid)))) (define-errno-syscall (%%fork) %%fork-with-retry/errno pid) waitpid(2 ) call . (define-foreign %wait-pid/errno (wait_pid (integer pid) (integer options)) errno or # f (define-foreign %chdir/errno (chdir (string directory)) (to-scheme integer errno_or_false)) (define-errno-syscall (%chdir dir) %chdir/errno) primitive in . ( define ( chdir . ) ( let ( ( dir (: optional maybe - dir ( home - dir ) ) ) ) ( ( ensure - file - name - is - nondirectory dir ) ) ) ) (define-foreign cwd/errno (scheme_cwd) errno or # f (define-errno-syscall (cwd) cwd/errno dir) (define cwd getcwd) GID (define-foreign user-gid (getgid) gid_t) (define user-gid getgid) (define-foreign user-effective-gid (getegid) gid_t) (define user-effective-gid getegid) (to-scheme integer errno_or_false)) (define-errno-syscall (set-gid gid) set-gid/errno) (define set-gid setgid) (define-foreign %num-supplementary-gids/errno (num_supp_groups) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign load-groups/errno (get_groups (vector-desc group-vec)) (multi-rep (to-scheme integer errno_or_false) integer)) (define (user-supplementary-gids) (vector->list (getgroups))) UID (define-foreign user-uid (getuid) uid_t) (define user-uid getuid) (define-foreign user-effective-uid (geteuid) uid_t) (define user-effective-uid geteuid) (to-scheme integer errno_or_false)) (define-errno-syscall (set-uid uid_t) set-uid/errno) (define set-uid setuid) (define-foreign %user-login-name (my_username) static-string) (define (user-login-name) (vector-ref (getpwuid (getuid)) 0)) (define-foreign pid (getpid) pid_t) (define pid getpid) (define-foreign parent-pid (getppid) pid_t) (define parent-pid getppid) (define-foreign process-group (getpgrp) pid_t) (define process-group getpgrp) (define-foreign %set-process-group/errno (setpgid (pid_t pid) (pid_t groupid)) (to-scheme integer errno_or_false)) (define-errno-syscall (%set-process-group pid pgrp) %set-process-group/errno) (define (set-process-group arg1 . maybe-arg2) (receive (pid pgrp) (if (null? maybe-arg2) (values (pid) arg1) (values arg1 (car maybe-arg2))) (setpgid pid pgrp))) (define-foreign become-session-leader/errno (setsid) (multi-rep (to-scheme pid_t errno_or_false) pid_t)) (define-errno-syscall (become-session-leader) become-session-leader/errno sid) (define become-session-leader setsid) integer on SunOS mode_t) primitive in . (define (set-umask newmask) (umask newmask)) OOPS : The POSIX times ( ) has a mildly useful ret value we are throwing away . OOPS : The ret values should be clock_t , not int , but cig ca n't handle it . (define-foreign process-times/errno (process_times) (to-scheme integer errno_or_false) (define-errno-syscall (process-times) process-times/errno utime stime cutime cstime) (define (process-times) (let ((obj (times))) (values (tms:utime obj) (tms:stime obj) (tms:cutime obj) (tms:cstime obj)))) (define-foreign cpu-ticks/sec (cpu_clock_ticks_per_sec) integer) (define cpu-ticks/sec internal-time-units-per-second) (define-foreign set-file-mode/errno integer on SunOS (to-scheme integer errno_or_false)) IBM 's AIX include files declare fchmod(char * , mode_t ) . the conflicting , correct declaration . Hence the NO - DECLARE . (define-foreign set-fdes-mode/errno integer on SunOS Workaround for AIX bug . (to-scheme integer errno_or_false)) (define-errno-syscall (set-file-mode thing mode) (lambda (thing mode) (generic-file-op thing (lambda (fd) (set-fdes-mode/errno fd mode)) (lambda (fname) (set-file-mode/errno fname mode))))) (define set-file-mode chmod) NO - DECLARE : gcc unistd.h bogusness . (define-foreign set-file-uid&gid/errno (chown (string path) (uid_t uid) (gid_t gid)) no-declare (to-scheme integer errno_or_false)) (define-foreign set-fdes-uid&gid/errno for NT (to-scheme integer errno_or_false)) (define-errno-syscall (set-file-owner thing uid) (lambda (thing uid) (generic-file-op thing (lambda (fd) (set-fdes-uid&gid/errno fd uid -1)) (lambda (fname) (set-file-uid&gid/errno fname uid -1))))) (define (set-file-owner thing uid) (chown thing uid -1)) (define-errno-syscall (set-file-group thing gid) (lambda (thing gid) (generic-file-op thing (lambda (fd) (set-fdes-uid&gid/errno fd -1 gid)) (lambda (fname) (set-file-uid&gid/errno fname -1 gid))))) (define (set-file-group thing gid) (chown thing -1 gid)) (define-foreign %file-ruid-access-not? (access (string path) (integer perms)) bool) ( file - access ? fname 1 ) ) ( file - access ? fname 2 ) ) ( file - access ? fname 4 ) ) (define-foreign create-hard-link/errno (link (string original-name) (string new-name)) (to-scheme integer errno_or_false)) (define-errno-syscall (create-hard-link original-name new-name) create-hard-link/errno) (define-foreign create-fifo/errno (mkfifo (string path) (mode_t mode)) integer on SunOS (to-scheme integer errno_or_false)) (define-errno-syscall (create-fifo path mode) create-fifo/errno) (define-foreign create-directory/errno integer on SunOS . (to-scheme integer errno_or_false)) (define-foreign read-symlink/errno (scm_readlink (string path)) NULL = , otw # f static-string)) (define-errno-syscall (read-symlink path) read-symlink/errno new-path) (define read-symlink readlink) (define-foreign %rename-file/errno (rename (string old-name) (string new-name)) (to-scheme integer errno_or_false)) (define-errno-syscall (%rename-file old-name new-name) %rename-file/errno) (define-foreign delete-directory/errno (rmdir (string path)) (to-scheme integer errno_or_false)) (define-errno-syscall (delete-directory path) delete-directory/errno) (define delete-directory rmdir) (define-foreign %utime/errno (scm_utime (string path) (integer ac_hi) (integer ac_lo) (integer m_hi) (integer m_lo)) (to-scheme integer errno_or_false)) (define-foreign %utime-now/errno (scm_utime_now (string path)) (to-scheme integer errno_or_false)) ( SET - FILE - TIMES / ERRNO path [ access - time mod - time ] ) (define (set-file-times path . maybe-times) (if (pair? maybe-times) (let* ((access-time (real->exact-integer (car maybe-times))) (mod-time (if (pair? (cddr maybe-times)) (error "Too many arguments to set-file-times/errno" (cons path maybe-times)) (real->exact-integer (cadr maybe-times))))) (utime path access-time mod-time)) (utime path))) (define-errno-syscall (set-file-times . args) set-file-times/errno) (define-foreign stat-file/errno (scheme_stat (string path) (vector-desc data) (bool chase?)) errno or # f (define-foreign stat-fdes/errno (scheme_fstat (integer fd) (vector-desc data)) errno or # f (define-record-type file-info-type (make-file-info type device inode mode nlinks uid gid size atime mtime ctime ) file-info? (type file-info:type) (device file-info:device) (inode file-info:inode) (mode file-info:mode) (nlinks file-info:nlinks) (uid file-info:uid) (gid file-info:gid) (size file-info:size) (atime file-info:atime) (mtime file-info:mtime) (ctime file-info:ctime)) (define (file-info fd/port/fname . maybe-chase?) (let ((chase? (:optional maybe-chase? #t))) (let ((info (if (or chase? (not (string? fd/port/fname))) (stat fd/port/fname) (lstat fd/port/fname)))) (make-file-info (stat:type info) (stat:dev info) (stat:ino info) (stat:mode info) (stat:nlink info) (stat:uid info) (stat:gid info) (stat:size info) (stat:atime info) (stat:mtime info) (stat:ctime info))))) (define-foreign create-symlink/errno (symlink (string old-name) (string new-name)) no-declare (to-scheme integer errno_or_false)) (define-foreign truncate-file/errno (truncate (string path) (off_t length)) no-declare (to-scheme integer errno_or_false)) (define-foreign truncate-fdes/errno Indigo bogosity . (to-scheme integer errno_or_false)) (define-errno-syscall (truncate-file path length) (lambda (thing length) (generic-file-op thing (lambda (fd) (truncate-fdes/errno fd length)) (lambda (fname) (truncate-file/errno fname length))))) (define-foreign delete-file/errno (unlink (string path)) (to-scheme integer errno_or_false)) (define-errno-syscall (delete-file path) delete-file/errno) (define-foreign sync-file/errno (fsync (integer fd)) (to-scheme integer errno_or_false)) (define sync-file fsync) Linux sux - says int ignore) (define sync-file-system sync) (define-foreign %close-fdes/errno (close (integer fd)) (to-scheme integer "errno_or_false")) (define-foreign %dup/errno (dup (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%dup fd) %dup/errno new-fd) (define-foreign %dup2/errno (dup2 (integer fd-from) (integer fd-to)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%dup2 fd-from fd-to) %dup2/errno new-fd) (define-foreign %fd-seek/errno (lseek (integer fd) (off_t offset) (integer whence)) (multi-rep (to-scheme off_t errno_or_false) off_t)) (define seek/delta SEEK_CUR) (define seek/end SEEK_END) (define tell ftell) (define-foreign %char-ready-fdes?/errno (char_ready_fdes (integer fd)) (define-foreign %open/errno (open (string path) (integer flags) integer on SunOS (multi-rep (to-scheme integer errno_or_false) integer)) (define-errno-syscall (%open path flags mode) %open/errno fd) (define-foreign pipe-fdes/errno (scheme_pipe) (define-errno-syscall (pipe-fdes) pipe-fdes/errno r w) (define vpipe (lambda () (let ((rv (pipe))) (values (car rv) (cdr rv))))) (define-foreign %read-fdes-char (read_fdes_char (integer fd)) or errno or # f ( eof ) . (define-foreign write-fdes-char/errno (write_fdes_char (char char) (integer fd)) (to-scheme integer errno_or_false)) (define-errno-syscall (write-fdes-char char fd) write-fdes-char/errno) (define-foreign read-fdes-substring!/errno (read_fdes_substring (string-desc buf) (integer start) (integer end) (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign write-fdes-substring/errno (write_fdes_substring (string-desc buf) (integer start) (integer end) (integer fd)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign signal-pid/errno (kill (pid_t pid) (integer signal)) (to-scheme integer errno_or_false)) (define-errno-syscall (signal-pid pid signal) signal-pid/errno) (define (signal-process proc signal) (kill (cond ((proc? proc) (proc:pid proc)) ((integer? proc) proc) (else (error "Illegal proc passed to signal-process" proc))) signal)) (define (signal-process-group proc-group signal) (kill (- (cond ((proc? proc-group) (proc:pid proc-group)) ((integer? proc-group) proc-group) (else (error "Illegal proc passed to signal-process-group" proc-group)))) signal)) ( killpg ( integer proc - group ) ( integer signal ) ) (define-foreign pause-until-interrupt (pause) no-declare ignore) (define pause-until-interrupt pause) (define-foreign itimer (alarm (uint_t secs)) uint_t) (define itimer alarm) (define-record-type user-info-type (make-user-info name uid gid home-dir shell) user-info? (name user-info:name) (uid user-info:uid) (gid user-info:gid) (home-dir user-info:home-dir) (shell user-info:shell)) (set-record-type-printer! user-info-type (lambda (ui port) (format port "#{user-info ~a}" (user-info:name ui)))) (define-foreign %uid->user-info (user_info_uid (uid_t uid)) (define-foreign %name->user-info (user_info_name (string name)) uid (define (user-info uid/name) (let ((info (getpw uid/name))) (make-user-info (passwd:name info) (passwd:uid info) (passwd:gid info) (passwd:dir info) (passwd:shell info)))) (define name->user-info user-info) (define uid->user-info user-info) (define (->uid uid/name) (user-info:uid (user-info uid/name))) (define (->username uid/name) (user-info:name (user-info uid/name))) (define (%homedir uid/name) (user-info:home-dir (user-info uid/name))) (define-record-type group-info-type (make-group-info name gid members) group-info? (name user-info:name) (gid user-info:gid) (members user-info:members)) (set-record-type-printer! user-info-type (lambda (gi port) (format port "#{group-info ~a}" (user-info:name gi)))) (define-foreign %gid->group-info (group_info_gid (integer gid)) (define-foreign %name->group-info (group_info_name (string name)) (define (group-info gid/name) (let ((info (getgr gid/name))) (make-group-info (group:name info) (group:gid info) (group:mem info)))) (define (->gid name) (group-info:gid (group-info name))) (define (->groupname gid) (group-info:name (group-info gid))) (define-foreign %open-dir (open_dir (string dir-name)) (define-foreign %sort-file-vector (scm_sort_filevec ((C "const char** ~a") cvec) (integer veclen)) ignore) (define (directory-files . args) (let-optionals* args ((dir ".") (dotfiles? #f)) (check-arg string? dir directory-files) (let ((dport (opendir (ensure-file-name-is-nondirectory dir)))) (let loop ((result '())) (let ((entry (readdir dport))) (cond ((eof-object? entry) (closedir dport) (sort! result string<?)) ((or (and (not dotfiles?) (char=? #\. (string-ref entry 0))) (string=? "." entry) (string=? ".." entry)) (loop result)) (else (loop (cons entry result))))))))) Later , we could tune up the globber or regexp file - matcher to use ( filter_stringvec ( string - desc pattern ) ( ( C " char const * * ~a " ) cvec ) ) ( define ( % filter - C - strings ! ) ( values # f j ) ( if ( regexp - exec rx ( vector - ref vec i ) ) ( vector - set ! j ( vector - ref vec i ) ) ( let ( ( dir (: optional maybe - dir " . " ) ) ) ( receive ( err ) ( if err ( errno - error err match - files regexp ) ) ( receive ( numfiles ) ( % filter - C - strings ! ) ( % sort - file - vector ) ( let ( ( files ( C - string - ) ) ) ( var . ) / " var = val " rep conversion : (define (split-env-string var=val) (let ((i (string-index var=val #\=))) (if i (values (substring var=val 0 i) (substring var=val (+ i 1) (string-length var=val))) (error "No \"=\" in environment string" var=val)))) (define (env-list->alist env-list) (map (lambda (var=val) (call-with-values (lambda () (split-env-string var=val)) cons)) env-list)) (define (alist->env-list alist) (map (lambda (var.val) (string-append (car var.val) "=" (cdr var.val))) alist)) (define-foreign %load-env (scm_envvec) (define (env->alist) (env-list->alist (environ))) (define-foreign %install-env/errno (install_env (vector-desc env-vec)) (to-scheme integer errno_or_false)) (define-errno-syscall (%install-env env-vec) %install-env/errno) (define (alist->env alist) (environ (alist->env-list alist))) , PUTENV , SETENV (define-foreign getenv (getenv (string var)) static-string) (foreign-source "#define errno_on_nonzero_or_false(x) ((x) ? ENTER_FIXNUM(errno) : SCHFALSE)" "" "") ( define - foreign putenv / errno ( put_env ( string var = ) ) (define-foreign putenv/errno (putenv (string-copy var=val)) no-declare (define-foreign delete-env (delete_env (string var)) ignore) primitive in . ( if ( putenv / errno var = ) ( error " malloc failure in putenv " var = ) ) ) in 's boot-9.scm . ( putenv ( string - append var " = " ) ) (define-foreign close-fdport*/errno (close_fdport (desc data)) (define-foreign %fdport*-read-char/errno (fdport_getchar (desc data)) ( if (= c errno / intr ) (define-foreign %fdport*-char-ready?/errno (fdport_char_readyp (desc data)) desc) ( define ( % fdport*-char - ready ? data ) ( let ( ( ( % fdport*-char - ready?/errno data ) ) ) ( if ( integer ? ) ( errno - error val % fdport*-char - ready ? data ) (define-foreign %fdport*-write-char/errno (fdport_putchar (desc data) (char c)) (define-errno-syscall (%fdport*-write-char desc c) %fdport*-write-char/errno) (define-foreign flush-fdport*/errno (flush_fdport (desc data)) FLUSH - FDPORT * is n't defined with DEFINE - ERRNO - SYSCALL because that would version returns # f. ( lambda ( err ) ( if (= err errno / intr ) (define-foreign flush-all-ports/errno (flush_all_ports) (to-scheme integer errno_or_false)) (define-errno-syscall (flush-all-ports) flush-all-ports/errno) (define-foreign %fdport*-seek/errno (seek_fdport (desc data) (off_t offset) (integer whence)) (define-foreign %fdport*-tell/errno (tell_fdport (desc data)) integer) (define-foreign %fdport*-set-buffering/errno (set_fdbuf (desc data) (integer policy) (integer size)) (define-foreign %set-cloexec (set_cloexec (integer fd) (bool val)) (to-scheme integer "errno_or_false")) (define-foreign %init-fdports! (init_fdports) ignore) (define-foreign %install-port/errno (install_port (integer fd) (desc port) (integer revealed)) (define-errno-syscall (%install-port fd port revealed) %install-port/errno) (define-foreign %maybe-fdes->port (maybe_fdes2port (integer fd)) (define-foreign %move-fdport (move_fdport (integer fd) (desc port) (integer new-revealed-count)) (define-foreign read-fdport*-substring!/errno (read_fdport_substring (string-desc buf) (integer start) (integer end) (desc data)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign write-fdport*-substring/errno (write_fdport_substring (string-desc buf) (integer start) (integer end) (desc fdport)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign %fcntl-read/errno (fcntl_read (fixnum fd) (fixnum command)) (multi-rep (to-scheme integer errno_or_false) integer)) (define-foreign %fcntl-write/errno (fcntl_write (fixnum fd) (fixnum command) (fixnum val)) (to-scheme integer errno_or_false)) (define-errno-syscall (%fcntl-read fd command) %fcntl-read/errno value) (define-errno-syscall (%fcntl-write fd command val) %fcntl-write/errno) descriptors by clearing their CLOEXEC bit when it reveals them -- so it (define (fdes-flags fd/port) (fcntl fd/port F_GETFD)) (define (set-fdes-flags fd/port flags) (fcntl fd/port F_SETFD flags)) fcntl ( ) 's F_GETFL and F_SETFL . Set : append , sync , async , nbio , nonblocking , no - delay (define (fdes-status fd/port) (fcntl fd/port F_GETFL)) (define (set-fdes-status fd/port flags) (fcntl fd/port F_SETFL flags)) (define open/read O_RDONLY) (define open/write O_WRONLY) (define open/read+write O_RDWR) (define open/non-blocking O_NONBLOCK) (define open/append O_APPEND) (define open/exclusive O_EXCL) (define open/create O_CREAT) (define open/truncate O_TRUNC) (define open/no-control-tty O_NOCTTY) (define open/access-mask (logior open/read open/write open/read+write)) (define fdflags/close-on-exec FD_CLOEXEC) usleep(3 ): Try to sleep for USECS microseconds . sleep(3 ): Try to sleep for SECS seconds . De - released -- not POSIX and not on SGI systems . ( define - foreign usleep ( usleep ( integer usecs ) ) integer ) 's sleep can be interrupted so define using sleep - until . (define (sleep secs) (sleep-until (+ secs (current-time)))) (define guile-sleep (module-ref (resolve-module '(guile)) 'sleep)) (define (sleep-until when) (let ((now (current-time)) (iwhen (inexact->exact when))) (if (> iwhen now) (if (> (guile-sleep (- iwhen now)) 0) (sleep-until when))))) (define-foreign %sleep-until (sleep_until (fixnum hi) (fixnum lo)) desc) (define-foreign %gethostname (scm_gethostname) static-string) (define (system-name) (utsname:nodename (uname))) (define-foreign errno-msg (errno_msg (integer i)) static-string) (define errno-msg strerror)
ee7bf19ff12ca31d4ed0c108fe24b975852d794edec982544cf734df16ea3662
atgreen/wrapilator
wrapilator.lisp
;;; wrapilator.lisp Copyright ( C ) 2017 < > Distrubuted under the terms of the MIT license . (in-package #:wrapilator) (defvar *directory* "obj_dir") (defun read-file-into-string (filename) (with-open-file (stream filename) (let ((contents (make-string (file-length stream)))) (read-sequence contents stream) contents))) ;;; Read all of the template files into strings. (defvar *Makefile-template* (read-file-into-string "Makefile.clt")) (defvar *wrapper.c-template* (read-file-into-string "wrapper.c.clt")) (defvar *package.lisp-template* (read-file-into-string "package.lisp.clt")) (opts:define-opts (:name :help :description "print this help text" :short #\h :long "help") (:name :directory :description "verilator output directory (default: obj_dir)" :arg-parser #'identity :short #\d :long "directory" :meta-var "OBJ_DIR")) (defun unknown-option (condition) (format t "warning: ~s option is unknown!~%" (opts:option condition)) (invoke-restart 'opts:skip-option)) (defmacro when-option ((options opt) &body body) `(let ((it (getf ,options ,opt))) (when it ,@body))) (defun abspath (path-string) (uiop:unix-namestring (uiop:merge-pathnames* (uiop:parse-unix-namestring path-string)))) (defun usage () (opts:describe :prefix "wrapilator - copyright (C) 2017 Anthony Green <>" :suffix "Distributed under the terms of MIT License" :usage-of "wrapilator" :args "module-name")) (defun create-wrapper (module-name) ;; Sanity checks (let ((header (format nil "~A/V~A.h" *directory* module-name))) (if (not (com.gigamonkeys.pathnames:file-exists-p header)) (format t "fatal: verilator output header file ~A does not exist~%" header) (progn (with-open-file (stream (format nil "~A/Makefile.wrap" *directory*) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *Makefile-template*) (list :module-name module-name)))) (let ((input-lines (inferior-shell:run/lines (format nil "grep -h VL_IN ~A" header))) (output-lines (inferior-shell:run/lines (format nil "grep -h VL_OUT ~A" header)))) (with-open-file (stream (format nil "~A/verilated-~A.lisp" *directory* module-name) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *package.lisp-template*) (list :module-name module-name :directory (abspath *directory*) :input-lines input-lines :output-lines output-lines)))) (with-open-file (stream (format nil "~A/wrapper.c" *directory*) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *wrapper.c-template*) (list :module-name module-name :input-lines input-lines :output-lines output-lines))))))))) (defun main (args) (multiple-value-bind (options free-args) (handler-case (handler-bind ((opts:unknown-option #'unknown-option)) (opts:get-opts)) (opts:missing-arg (condition) (format t "fatal: option ~s needs an argument!~%" (opts:option condition))) (opts:arg-parser-failed (condition) (format t "fatal: cannot parse ~s as argument of ~s~%" (opts:raw-arg condition) (opts:option condition)))) (when-option (options :help) (usage)) (when-option (options :directory) (setf *directory* (getf options :directory))) (if (not (eq 1 (length free-args))) (usage) (progn (create-wrapper (car free-args)) (format t "Done.~%")))))
null
https://raw.githubusercontent.com/atgreen/wrapilator/890783971a157b7f615cb9a8bf300cf516be3d49/wrapilator.lisp
lisp
wrapilator.lisp Read all of the template files into strings. Sanity checks
Copyright ( C ) 2017 < > Distrubuted under the terms of the MIT license . (in-package #:wrapilator) (defvar *directory* "obj_dir") (defun read-file-into-string (filename) (with-open-file (stream filename) (let ((contents (make-string (file-length stream)))) (read-sequence contents stream) contents))) (defvar *Makefile-template* (read-file-into-string "Makefile.clt")) (defvar *wrapper.c-template* (read-file-into-string "wrapper.c.clt")) (defvar *package.lisp-template* (read-file-into-string "package.lisp.clt")) (opts:define-opts (:name :help :description "print this help text" :short #\h :long "help") (:name :directory :description "verilator output directory (default: obj_dir)" :arg-parser #'identity :short #\d :long "directory" :meta-var "OBJ_DIR")) (defun unknown-option (condition) (format t "warning: ~s option is unknown!~%" (opts:option condition)) (invoke-restart 'opts:skip-option)) (defmacro when-option ((options opt) &body body) `(let ((it (getf ,options ,opt))) (when it ,@body))) (defun abspath (path-string) (uiop:unix-namestring (uiop:merge-pathnames* (uiop:parse-unix-namestring path-string)))) (defun usage () (opts:describe :prefix "wrapilator - copyright (C) 2017 Anthony Green <>" :suffix "Distributed under the terms of MIT License" :usage-of "wrapilator" :args "module-name")) (defun create-wrapper (module-name) (let ((header (format nil "~A/V~A.h" *directory* module-name))) (if (not (com.gigamonkeys.pathnames:file-exists-p header)) (format t "fatal: verilator output header file ~A does not exist~%" header) (progn (with-open-file (stream (format nil "~A/Makefile.wrap" *directory*) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *Makefile-template*) (list :module-name module-name)))) (let ((input-lines (inferior-shell:run/lines (format nil "grep -h VL_IN ~A" header))) (output-lines (inferior-shell:run/lines (format nil "grep -h VL_OUT ~A" header)))) (with-open-file (stream (format nil "~A/verilated-~A.lisp" *directory* module-name) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *package.lisp-template*) (list :module-name module-name :directory (abspath *directory*) :input-lines input-lines :output-lines output-lines)))) (with-open-file (stream (format nil "~A/wrapper.c" *directory*) :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream (funcall (cl-template:compile-template *wrapper.c-template*) (list :module-name module-name :input-lines input-lines :output-lines output-lines))))))))) (defun main (args) (multiple-value-bind (options free-args) (handler-case (handler-bind ((opts:unknown-option #'unknown-option)) (opts:get-opts)) (opts:missing-arg (condition) (format t "fatal: option ~s needs an argument!~%" (opts:option condition))) (opts:arg-parser-failed (condition) (format t "fatal: cannot parse ~s as argument of ~s~%" (opts:raw-arg condition) (opts:option condition)))) (when-option (options :help) (usage)) (when-option (options :directory) (setf *directory* (getf options :directory))) (if (not (eq 1 (length free-args))) (usage) (progn (create-wrapper (car free-args)) (format t "Done.~%")))))
6ebdf0fb7ea4efc6c455b50d03645cfbbaa724e46be4ffa2ed47e770efe47e6e
lispgames/glop
dwm.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*- (in-package #:glop-win32) (cffi:define-foreign-library dwm (:windows "Dwmapi.dll")) (cffi:use-foreign-library dwm) (cffi:defcfun ("DwmFlush" dwm-flush) :int) (cffi:defcfun ("DwmIsCompositionEnabled" %dwm-is-composition-enabled) :int32 (enabled (:pointer bool))) (defun dwm-is-composition-enabled () (with-foreign-object (p 'bool) (let ((hr (%dwm-is-composition-enabled p))) (if (zerop hr) (not (zerop (mem-ref p 'bool))) (error "dwm-is-composition-enabled failed 0x~x~%" hr)))))
null
https://raw.githubusercontent.com/lispgames/glop/45e722ab4a0cd2944d550bf790206b3326041e38/src/win32/dwm.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*-
(in-package #:glop-win32) (cffi:define-foreign-library dwm (:windows "Dwmapi.dll")) (cffi:use-foreign-library dwm) (cffi:defcfun ("DwmFlush" dwm-flush) :int) (cffi:defcfun ("DwmIsCompositionEnabled" %dwm-is-composition-enabled) :int32 (enabled (:pointer bool))) (defun dwm-is-composition-enabled () (with-foreign-object (p 'bool) (let ((hr (%dwm-is-composition-enabled p))) (if (zerop hr) (not (zerop (mem-ref p 'bool))) (error "dwm-is-composition-enabled failed 0x~x~%" hr)))))
87f5454f0dfa6c7545467e3f8600f768c7975079aa448c9d0deea7417ec5548a
basti1302/elm-lang-de
Validation.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Util.Validation ( HasOptionalEMail(..) , HasOptionalURL(..) , validate , validateEMailEmptyOrWellformed , validateURLEmptyOrWellformed ) where import Database.StatementMap import Control.Monad (foldM) import qualified Data.ByteString.Char8 as BSC8 import qualified Data.Maybe as Maybe import Data.Text (Text) import qualified Data.Text as T import qualified Network.URI as URI import qualified Text.Email.Validate as EmailValidate (isValid) -- |The 'validate' function takes a list of checks and executes them on anentity -- value. Each check has the type -- dbConnection -> entityType -> IO (Maybe Text, entityType) -- that is, it takes a db connection and the entity value and returns an IO -- action that might produce an error message (Maybe Text) and potentially -- updates the entity. Note: Some checks, especially checks for uniquenessor -- existence need to access the database, that is why it is fed to all checks. validate :: forall dbConnection entityType. dbConnection -- ^ the db connection that is fed to all checks -> [dbConnection -> entityType -> IO (Maybe Text, entityType)] -- ^ the list of checks to execute -> entityType -- ^ the entity value that will be validated -> IO ([Text], entityType) -- ^ a list of message and the updated entity validate dbConnection checks entity = do let -- feed db connection to all checks -- checksWithDbConnection :: [entityType -> IO (Maybe Text, entityType)] checksWithDbConnection = map ($ dbConnection) checks -- execute checks validationResults :: ([Text], entityType) <- foldM executeOneValidationCheck ([], entity) checksWithDbConnection return validationResults executeOneValidationCheck :: forall entityType. ([Text], entityType) -> (entityType -> IO (Maybe Text, entityType)) -> IO ([Text], entityType) executeOneValidationCheck (messages, entity) validationCheck = do let nextCheckAction :: IO (Maybe Text, entityType) nextCheckAction = validationCheck entity (maybeNextMessage, updatedEntity) :: (Maybe Text, entityType) <- nextCheckAction let updatedMessages = case maybeNextMessage of Nothing -> messages Just nextMessage -> messages ++ [ nextMessage ] return (updatedMessages, updatedEntity) class HasOptionalEMail a where getEMail :: a -> Maybe Text setEMail :: Maybe Text -> a -> a validateEMailEmptyOrWellformed :: (HasOptionalEMail hasEMail) => DbConnection connection -> hasEMail -> IO (Maybe Text, hasEMail) validateEMailEmptyOrWellformed _ hasEMail = let maybeEMail = getEMail hasEMail in case maybeEMail of Nothing -> return (Nothing, hasEMail) Just email -> if T.null email then return (Nothing, (setEMail Nothing hasEMail)) else if not (EmailValidate.isValid $ BSC8.pack $ T.unpack email) then return $ ( Just "Das ist keine valide E-Mail-Adresse.", hasEMail) else return (Nothing, hasEMail) class HasOptionalURL a where getURL :: a -> Maybe Text setURL :: Maybe Text -> a -> a validateURLEmptyOrWellformed :: (HasOptionalURL hasURL) => DbConnection connection -> hasURL -> IO (Maybe Text, hasURL) validateURLEmptyOrWellformed _ hasURL = let maybeURL = getURL hasURL in case maybeURL of Nothing -> return (Nothing, hasURL) Just url -> if T.null url then return (Nothing, (setURL Nothing hasURL)) else let (message, normalizedUrlText) = validateURLWellformed url in return $ (message, (setURL (Just normalizedUrlText) hasURL)) validateURLWellformed :: Text -> (Maybe Text, Text) validateURLWellformed url = let possibleHttp = T.toLower $ T.take 7 url possibleHttps = T.toLower $ T.take 8 url normalizedUrl = if (possibleHttp /= "http://") && (possibleHttps /= "https://") then "http://" ++ (T.unpack url) else T.unpack url valid = Maybe.isJust $ URI.parseURI normalizedUrl in if valid then (Nothing, T.pack normalizedUrl) else (Just "Das ist keine valide URL.", T.pack normalizedUrl)
null
https://raw.githubusercontent.com/basti1302/elm-lang-de/9654752fb6fb56bc4116483f3bbd412a774e9fb1/backend/app/Util/Validation.hs
haskell
# LANGUAGE OverloadedStrings # |The 'validate' function takes a list of checks and executes them on anentity value. Each check has the type dbConnection -> entityType -> IO (Maybe Text, entityType) that is, it takes a db connection and the entity value and returns an IO action that might produce an error message (Maybe Text) and potentially updates the entity. Note: Some checks, especially checks for uniquenessor existence need to access the database, that is why it is fed to all checks. ^ the db connection that is fed to all checks ^ the list of checks to execute ^ the entity value that will be validated ^ a list of message and the updated entity feed db connection to all checks checksWithDbConnection :: [entityType -> IO (Maybe Text, entityType)] execute checks
# LANGUAGE ScopedTypeVariables # module Util.Validation ( HasOptionalEMail(..) , HasOptionalURL(..) , validate , validateEMailEmptyOrWellformed , validateURLEmptyOrWellformed ) where import Database.StatementMap import Control.Monad (foldM) import qualified Data.ByteString.Char8 as BSC8 import qualified Data.Maybe as Maybe import Data.Text (Text) import qualified Data.Text as T import qualified Network.URI as URI import qualified Text.Email.Validate as EmailValidate (isValid) validate :: forall dbConnection entityType. -> [dbConnection -> entityType -> IO (Maybe Text, entityType)] validate dbConnection checks entity = do let checksWithDbConnection = map ($ dbConnection) checks validationResults :: ([Text], entityType) <- foldM executeOneValidationCheck ([], entity) checksWithDbConnection return validationResults executeOneValidationCheck :: forall entityType. ([Text], entityType) -> (entityType -> IO (Maybe Text, entityType)) -> IO ([Text], entityType) executeOneValidationCheck (messages, entity) validationCheck = do let nextCheckAction :: IO (Maybe Text, entityType) nextCheckAction = validationCheck entity (maybeNextMessage, updatedEntity) :: (Maybe Text, entityType) <- nextCheckAction let updatedMessages = case maybeNextMessage of Nothing -> messages Just nextMessage -> messages ++ [ nextMessage ] return (updatedMessages, updatedEntity) class HasOptionalEMail a where getEMail :: a -> Maybe Text setEMail :: Maybe Text -> a -> a validateEMailEmptyOrWellformed :: (HasOptionalEMail hasEMail) => DbConnection connection -> hasEMail -> IO (Maybe Text, hasEMail) validateEMailEmptyOrWellformed _ hasEMail = let maybeEMail = getEMail hasEMail in case maybeEMail of Nothing -> return (Nothing, hasEMail) Just email -> if T.null email then return (Nothing, (setEMail Nothing hasEMail)) else if not (EmailValidate.isValid $ BSC8.pack $ T.unpack email) then return $ ( Just "Das ist keine valide E-Mail-Adresse.", hasEMail) else return (Nothing, hasEMail) class HasOptionalURL a where getURL :: a -> Maybe Text setURL :: Maybe Text -> a -> a validateURLEmptyOrWellformed :: (HasOptionalURL hasURL) => DbConnection connection -> hasURL -> IO (Maybe Text, hasURL) validateURLEmptyOrWellformed _ hasURL = let maybeURL = getURL hasURL in case maybeURL of Nothing -> return (Nothing, hasURL) Just url -> if T.null url then return (Nothing, (setURL Nothing hasURL)) else let (message, normalizedUrlText) = validateURLWellformed url in return $ (message, (setURL (Just normalizedUrlText) hasURL)) validateURLWellformed :: Text -> (Maybe Text, Text) validateURLWellformed url = let possibleHttp = T.toLower $ T.take 7 url possibleHttps = T.toLower $ T.take 8 url normalizedUrl = if (possibleHttp /= "http://") && (possibleHttps /= "https://") then "http://" ++ (T.unpack url) else T.unpack url valid = Maybe.isJust $ URI.parseURI normalizedUrl in if valid then (Nothing, T.pack normalizedUrl) else (Just "Das ist keine valide URL.", T.pack normalizedUrl)
a9875771819a308359349c3c792e55424699ee7b0e1ca22c558d1f916ea7b2f8
ekmett/machines
Examples.hs
# LANGUAGE CPP # {-# LANGUAGE RankNTypes #-} module Examples where #if !(MIN_VERSION_base(4,8,0)) import Control.Applicative #endif import Control.Exception import Control.Monad.Trans import Data.Machine import Data.Machine.Group.General import System.IO -- this slurp slurps until an eof exception is raised. slurpHandleBad :: Handle -> IO [String] slurpHandleBad h = do s <- hGetLine h (s:) <$> slurpHandleBad h -- this is the good slurp -- it catches the exception, and cleans up. slurpHandle :: Handle -> IO [String] slurpHandle h = clean <$> slurp where clean = either (\(SomeException _) -> []) id slurp = try $ do { s <- hGetLine h; (s:) <$> slurpHandle h } -- read a file, returning each line in a list readLines :: FilePath -> IO [String] readLines f = withFile f ReadMode slurpHandle -- | bad slurping machine crashes :: Handle -> MachineT IO k String crashes h = repeatedly $ do x <- lift (hGetLine h) yield x -- | here is a plan that yields all the lines at once. slurpHandlePlan :: Handle -> PlanT k [String] IO () slurpHandlePlan h = do x <- lift (slurpHandle h) yield x - but we want a plan that will yield one line at a time - until we are done reading the file - but before we can do that , we need a few helper combinators . - but we want a plan that will yield one line at a time - until we are done reading the file - but before we can do that, we need a few helper combinators. -} -- | getFileLines reads each line out of the given file and pumps them into the given process. getFileLines :: FilePath -> ProcessT IO String a -> SourceT IO a getFileLines path proc = src ~> proc where src :: SourceT IO String src = construct $ lift (openFile path ReadMode) >>= slurpLinesPlan slurpLinesPlan :: Handle -> PlanT k String IO () slurpLinesPlan h = exhaust (clean <$> try (hGetLine h)) where clean = either (\(SomeException _) -> Nothing) Just -- | lineCount counts the number of lines in a file lineCount :: FilePath -> IO Int lineCount path = head <$> (runT src) where src = getFileLines path (fold (\a _ -> a + 1) 0) | run a machine and just take the first value out of it . runHead :: (Functor f, Monad f) => MachineT f k b -> f b runHead src = head <$> runT src -- | lineCharCount counts the number of lines, and characters in a file lineCharCount :: FilePath -> IO (Int, Int) lineCharCount path = runHead src where src = getFileLines path (fold (\(l,c) s -> (l+1, c + length s)) (0,0)) | A Process that takes in a String and outputs all the words in that wordsProc :: Process String String wordsProc = repeatedly $ do { s <- await; mapM_ (\x -> yield x) (words s) } -- | A Plan to print all input. printPlan :: PlanT (Is String) () IO () printPlan = await >>= lift . putStrLn >> yield () -- | A Process that prints all its input. printProcess :: ProcessT IO String () printProcess = repeatedly printPlan -- | A machine that prints all the lines in a file. printLines :: FilePath -> IO () printLines path = runT_ $ getFileLines path printProcess -- | A machine that prints all the words in a file. printWords :: FilePath -> IO () printWords path = runT_ $ getFileLines path (wordsProc ~> printProcess) -- | A machine that prints all the lines in a file with the line numbers. printLinesWithLineNumbers :: FilePath -> IO () printLinesWithLineNumbers path = runT_ (t ~> printProcess) where t :: TeeT IO Int String String t = tee (source [1..]) (getFileLines path echo) lineNumsT lineNumsT :: MachineT IO (T Integer String) String lineNumsT = repeatedly $ zipWithT $ \i s -> show i ++ ": " ++ s uniq :: Bool uniq = run (supply xs uniqMachine) == [1,2,3] where | Unix 's " uniq " command using groupingOn _ (= " groups are contiguous values " -- final means "run the 'final' machine over each group" uniqMachine :: (Monad m, Eq a) => ProcessT m a a uniqMachine = groupingOn_ (==) final xs :: [Int] xs = [1,2,2,3,3,3] def lineWordCount(fileName : String ) = getFileLines(new File(fileName ) , ( i d split words ) outmap ( _ .fold ( _ = > ( 1 , 0 ) , _ = > ( 0 , 1 ) ) ) ) execute lineWordCount FilePath - > IO ( Int , Int ) lineWordCount path = runHead lineWordCountSrc where lineWordCountSrc = echo def lineWordCount(fileName: String) = getFileLines(new File(fileName), (id split words) outmap (_.fold(_ => (1, 0), _ => (0, 1)))) execute lineWordCount FilePath -> IO (Int, Int) lineWordCount path = runHead lineWordCountSrc where lineWordCountSrc = echo -}
null
https://raw.githubusercontent.com/ekmett/machines/d76bb4cf5798b495f1648c5f5075209e81e11eac/examples/Examples.hs
haskell
# LANGUAGE RankNTypes # this slurp slurps until an eof exception is raised. this is the good slurp it catches the exception, and cleans up. read a file, returning each line in a list | bad slurping machine | here is a plan that yields all the lines at once. | getFileLines reads each line out of the given file and pumps them into the given process. | lineCount counts the number of lines in a file | lineCharCount counts the number of lines, and characters in a file | A Plan to print all input. | A Process that prints all its input. | A machine that prints all the lines in a file. | A machine that prints all the words in a file. | A machine that prints all the lines in a file with the line numbers. final means "run the 'final' machine over each group"
# LANGUAGE CPP # module Examples where #if !(MIN_VERSION_base(4,8,0)) import Control.Applicative #endif import Control.Exception import Control.Monad.Trans import Data.Machine import Data.Machine.Group.General import System.IO slurpHandleBad :: Handle -> IO [String] slurpHandleBad h = do s <- hGetLine h (s:) <$> slurpHandleBad h slurpHandle :: Handle -> IO [String] slurpHandle h = clean <$> slurp where clean = either (\(SomeException _) -> []) id slurp = try $ do { s <- hGetLine h; (s:) <$> slurpHandle h } readLines :: FilePath -> IO [String] readLines f = withFile f ReadMode slurpHandle crashes :: Handle -> MachineT IO k String crashes h = repeatedly $ do x <- lift (hGetLine h) yield x slurpHandlePlan :: Handle -> PlanT k [String] IO () slurpHandlePlan h = do x <- lift (slurpHandle h) yield x - but we want a plan that will yield one line at a time - until we are done reading the file - but before we can do that , we need a few helper combinators . - but we want a plan that will yield one line at a time - until we are done reading the file - but before we can do that, we need a few helper combinators. -} getFileLines :: FilePath -> ProcessT IO String a -> SourceT IO a getFileLines path proc = src ~> proc where src :: SourceT IO String src = construct $ lift (openFile path ReadMode) >>= slurpLinesPlan slurpLinesPlan :: Handle -> PlanT k String IO () slurpLinesPlan h = exhaust (clean <$> try (hGetLine h)) where clean = either (\(SomeException _) -> Nothing) Just lineCount :: FilePath -> IO Int lineCount path = head <$> (runT src) where src = getFileLines path (fold (\a _ -> a + 1) 0) | run a machine and just take the first value out of it . runHead :: (Functor f, Monad f) => MachineT f k b -> f b runHead src = head <$> runT src lineCharCount :: FilePath -> IO (Int, Int) lineCharCount path = runHead src where src = getFileLines path (fold (\(l,c) s -> (l+1, c + length s)) (0,0)) | A Process that takes in a String and outputs all the words in that wordsProc :: Process String String wordsProc = repeatedly $ do { s <- await; mapM_ (\x -> yield x) (words s) } printPlan :: PlanT (Is String) () IO () printPlan = await >>= lift . putStrLn >> yield () printProcess :: ProcessT IO String () printProcess = repeatedly printPlan printLines :: FilePath -> IO () printLines path = runT_ $ getFileLines path printProcess printWords :: FilePath -> IO () printWords path = runT_ $ getFileLines path (wordsProc ~> printProcess) printLinesWithLineNumbers :: FilePath -> IO () printLinesWithLineNumbers path = runT_ (t ~> printProcess) where t :: TeeT IO Int String String t = tee (source [1..]) (getFileLines path echo) lineNumsT lineNumsT :: MachineT IO (T Integer String) String lineNumsT = repeatedly $ zipWithT $ \i s -> show i ++ ": " ++ s uniq :: Bool uniq = run (supply xs uniqMachine) == [1,2,3] where | Unix 's " uniq " command using groupingOn _ (= " groups are contiguous values " uniqMachine :: (Monad m, Eq a) => ProcessT m a a uniqMachine = groupingOn_ (==) final xs :: [Int] xs = [1,2,2,3,3,3] def lineWordCount(fileName : String ) = getFileLines(new File(fileName ) , ( i d split words ) outmap ( _ .fold ( _ = > ( 1 , 0 ) , _ = > ( 0 , 1 ) ) ) ) execute lineWordCount FilePath - > IO ( Int , Int ) lineWordCount path = runHead lineWordCountSrc where lineWordCountSrc = echo def lineWordCount(fileName: String) = getFileLines(new File(fileName), (id split words) outmap (_.fold(_ => (1, 0), _ => (0, 1)))) execute lineWordCount FilePath -> IO (Int, Int) lineWordCount path = runHead lineWordCountSrc where lineWordCountSrc = echo -}
06ca6f8f4aa50e1318c1df9badecf926eddeffceb0800abb650171099b340103
freizl/dive-into-haskell
Filtering.hs
-- | module Filtering where import Data.List myFilter = filter notArticles . words notArticles xs = xs `notElem` ["a", "the", "an"]
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/09/Filtering.hs
haskell
|
module Filtering where import Data.List myFilter = filter notArticles . words notArticles xs = xs `notElem` ["a", "the", "an"]
f2d1b78e39cf7819b760db428d8faa3798ccabf95ee6d98a97b41d6d97a200ae
evidentsystems/converge
serialize.cljc
Copyright 2020 Evident Systems LLC Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; -2.0 ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns converge.serialize "Handlers for serializing to e.g. Transit." (:require [converge.domain :as domain] [converge.opset.interpret :as interpret] [converge.opset.ref :as opset] [converge.editscript.ref :as editscript])) #?(:clj (set! *warn-on-reflection* true) :cljs (set! *warn-on-infer* true)) (defn write-id [id] [(:actor id) (:counter id)]) (defn read-id [[actor counter]] (domain/->Id actor counter)) (defn write-operation [op] [(:action op) (:data op)]) (defn read-operation [[action data]] (domain/->Op action data)) (defn write-patch [patch] {:ops (into {} (:ops patch)) :source (:source patch)}) (def read-patch domain/map->Patch) (defn write-clock [clock] {:source (:source clock) :clock (:clock clock)}) (def read-clock domain/map->Clock) (defn write-element [element] [(:entity element) (:attribute element) (:value element) (:id element)]) (defn read-element [[entity attribute value id]] (interpret/->Element entity attribute value id)) (defn write-interpretation [interpretation] (into {} (-> interpretation (select-keys [:elements :list-links :entities :keys :values]) (update :elements vec)))) (def read-interpretation interpret/make-interpretation) (defn write-state [state] (-> state :log vec)) (defn read-state [log] (domain/make-state {:log log :dirty? true})) (defn write-ref [r] {:meta (meta r) :state (domain/-state r)}) (defn read-opset-convergent-ref [{:keys [state meta]}] (opset/->OpsetConvergentRef (domain/uuid) state (domain/queue) meta nil nil)) (defn read-editscript-convergent-ref [{:keys [state meta]}] (editscript/->EditscriptConvergentRef (domain/uuid) state (domain/queue) meta nil nil))
null
https://raw.githubusercontent.com/evidentsystems/converge/9954febb85d598042b3d195bdb696268689ea427/converge/src/converge/serialize.cljc
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2020 Evident Systems LLC distributed under the License is distributed on an " AS IS " BASIS , (ns converge.serialize "Handlers for serializing to e.g. Transit." (:require [converge.domain :as domain] [converge.opset.interpret :as interpret] [converge.opset.ref :as opset] [converge.editscript.ref :as editscript])) #?(:clj (set! *warn-on-reflection* true) :cljs (set! *warn-on-infer* true)) (defn write-id [id] [(:actor id) (:counter id)]) (defn read-id [[actor counter]] (domain/->Id actor counter)) (defn write-operation [op] [(:action op) (:data op)]) (defn read-operation [[action data]] (domain/->Op action data)) (defn write-patch [patch] {:ops (into {} (:ops patch)) :source (:source patch)}) (def read-patch domain/map->Patch) (defn write-clock [clock] {:source (:source clock) :clock (:clock clock)}) (def read-clock domain/map->Clock) (defn write-element [element] [(:entity element) (:attribute element) (:value element) (:id element)]) (defn read-element [[entity attribute value id]] (interpret/->Element entity attribute value id)) (defn write-interpretation [interpretation] (into {} (-> interpretation (select-keys [:elements :list-links :entities :keys :values]) (update :elements vec)))) (def read-interpretation interpret/make-interpretation) (defn write-state [state] (-> state :log vec)) (defn read-state [log] (domain/make-state {:log log :dirty? true})) (defn write-ref [r] {:meta (meta r) :state (domain/-state r)}) (defn read-opset-convergent-ref [{:keys [state meta]}] (opset/->OpsetConvergentRef (domain/uuid) state (domain/queue) meta nil nil)) (defn read-editscript-convergent-ref [{:keys [state meta]}] (editscript/->EditscriptConvergentRef (domain/uuid) state (domain/queue) meta nil nil))
75a67813fe477bd51694ef0f89083a17f1e37c42b8aacced6334cbaf4c57f7c2
BillHallahan/G2
Case1.hs
module Case1 where data X = A | B | C f :: Int -> X f x | x < 0 = A | x < -1 = B | otherwise = C
null
https://raw.githubusercontent.com/BillHallahan/G2/dfd377793dcccdc7126a9f4a65b58249673e8a70/tests/TestFiles/Case1.hs
haskell
module Case1 where data X = A | B | C f :: Int -> X f x | x < 0 = A | x < -1 = B | otherwise = C
33342b1eaf0a101fec7c8ee32b2e522a075431b04af1dd9fb3c38b369474165b
re-ops/re-cipes
backup.clj
(ns re-cipes.backup (:require [re-cipes.access :refer (permissions)] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.download :refer (download)] [re-cog.resources.file :refer (rename symlink chmod)] [re-cog.resources.archive :refer (untar bzip2)])) (require-recipe) (def-inline {:depends #'re-cipes.access/permissions} restic "Setting up restic" [] (let [version "0.11.0" release (<< "restic_~{version}_linux_amd64") tmp (<< "/tmp/~{release}.bz2") bin "/usr/local/bin/" expected "f559e774c91f1201ffddba74d5758dec8342ad2b50a3bcd735ccb0c88839045c" url (<< "~{version}/~{release}.bz2")] (download url tmp expected) (bzip2 tmp) (rename (<< "/tmp/~{release}") (<< "~{bin}/restic")) (chmod (<< "~{bin}/restic") "0755" {}))) (def-inline {:depends #'re-cipes.access/permissions} octo "Setting up octo" [] (let [version "0.8.1" tmp "/tmp/octo" expected "c53abdfd81fc5eb48ff138faf3cdcd11acd7a089a44d0d82c05a63a56ef691ee" url (<< "/~{version}/octo")] (download url tmp expected) (rename tmp "/usr/local/bin/octo") (chmod "/usr/local/bin/octo" "0755" {}))) (def-inline zbackup "Setting up zbackup" [] (package "zbackup" :present)) (def-inline rclone "Setting up rclone" [] (package "rclone" :present))
null
https://raw.githubusercontent.com/re-ops/re-cipes/4d53506251e4a61dbd7130d470569fb468d5eba5/src/re_cipes/backup.clj
clojure
(ns re-cipes.backup (:require [re-cipes.access :refer (permissions)] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.download :refer (download)] [re-cog.resources.file :refer (rename symlink chmod)] [re-cog.resources.archive :refer (untar bzip2)])) (require-recipe) (def-inline {:depends #'re-cipes.access/permissions} restic "Setting up restic" [] (let [version "0.11.0" release (<< "restic_~{version}_linux_amd64") tmp (<< "/tmp/~{release}.bz2") bin "/usr/local/bin/" expected "f559e774c91f1201ffddba74d5758dec8342ad2b50a3bcd735ccb0c88839045c" url (<< "~{version}/~{release}.bz2")] (download url tmp expected) (bzip2 tmp) (rename (<< "/tmp/~{release}") (<< "~{bin}/restic")) (chmod (<< "~{bin}/restic") "0755" {}))) (def-inline {:depends #'re-cipes.access/permissions} octo "Setting up octo" [] (let [version "0.8.1" tmp "/tmp/octo" expected "c53abdfd81fc5eb48ff138faf3cdcd11acd7a089a44d0d82c05a63a56ef691ee" url (<< "/~{version}/octo")] (download url tmp expected) (rename tmp "/usr/local/bin/octo") (chmod "/usr/local/bin/octo" "0755" {}))) (def-inline zbackup "Setting up zbackup" [] (package "zbackup" :present)) (def-inline rclone "Setting up rclone" [] (package "rclone" :present))
76ad4669549fe5e2c4d1a49ef9ebd7af1ee593610048e5de5b0d2c9cbc66d887
gregr/experiments
test-basic.rkt
#lang racket/base (require "dk.rkt" "evalo.rkt" racket/pretty) (define-relation (appendo xs ys zs) (conde ((== xs '()) (== zs ys)) ((fresh (a d ws) (== xs (cons a d)) (== zs (cons a ws)) (appendo d ys ws))))) (define-relation (reverseo ys sy) (conde ((== '() ys) (== '() sy)) ((fresh (first rest prefix) (== `(,first . ,rest) ys) ;; With a typical search strategy, there is no refutationally complete ordering of the following two goals . This ordering works well when ;; running in the forward direction, but not in the backward direction. (reverseo rest prefix) (appendo prefix `(,first) sy))))) (define-relation (nevero x) (nevero x)) (define-relation (alwayso x) (conde ((== #t x)) ((alwayso x)))) (define-relation (sometimeso x) (conde ((nevero x)) ((alwayso x)))) (define-relation (color c) (conde ((== c 'red)) ((== c 'green)) ((== c 'blue)) ((== c 'cyan)) ((== c 'magenta)) ((== c 'yellow)) ((== c 'black)) ((== c 'white)))) (define-relation (shape s) (conde ((== s 'circle)) ((== s 'triangle)) ((== s 'rectangle)) ((== s 'pentagon)) ((== s 'hexagon)))) (define-relation (shape-or-color sc) (conde ((shape sc)) ((color sc)))) (define-syntax test (syntax-rules () ((_ name e-actual e-expected) (time (begin (printf "Testing ~s:\n" name) (let ((actual e-actual) (expected e-expected)) (unless (equal? actual expected) (printf "FAILURE\nEXPECTED: ~s\nACTUAL: ~s\n" expected actual)))))))) (test 'basic-1 (run* (q) (== 5 q)) '((5))) (test 'appendo-1 (run* (xs ys) (appendo xs ys '(a b c d))) '((() (a b c d)) ((a) (b c d)) ((a b) (c d)) ((a b c) (d)) ((a b c d) ()))) (test 'reverseo-forward (run* (xs) (reverseo '(1 2 3 4 5) xs)) '(((5 4 3 2 1)))) (test 'reverseo-backward (run* (xs) (reverseo xs '(1 2 3 4 5))) ( run 1 ( xs ) ( reverseo xs ' ( 1 2 3 4 5 ) ) ) '(((5 4 3 2 1)))) (test 'sometimeso-1 (run 5 (q) (sometimeso q)) '((#t) (#t) (#t) (#t) (#t))) (test 'choices-1 (run 20 (sc) (shape-or-color sc)) '((circle) (triangle) (red) (green) (rectangle) (blue) (pentagon) (cyan) (hexagon) (magenta) (yellow) (black) (white))) (test 'choices-2 (run 20 (s c) (shape s) (color c)) '((circle red) (circle green) (triangle red) (circle blue) (triangle green) (circle cyan) (circle magenta) (triangle blue) (circle yellow) (rectangle red) (circle black) (triangle cyan) (circle white) (rectangle green) (triangle magenta) (triangle yellow) (rectangle blue) (pentagon red) (triangle black) (triangle white))) (test 'evalo-literal (run 1 (e) (evalo e 5)) '(((quote 5)))) cpu time : 295 real time : 319 gc time : 97 (test 'evalo-quine (run 1 (e) (evalo e e)) '(((app (lambda (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ()))))) (quote (lambda (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))))))))) (displayln "\nBeginning slower tests...") cpu time : 9776 real time : gc time : 4201 (test 'evalo-twine (run 1 (p q) (evalo p q) (evalo q p)) '(((quote (app (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))))))) (app (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))))))))) (displayln "\nThe next test may take many seconds...") cpu time : 219963 real time : 224929 gc time : 58448 (test 'evalo-thrine (run 1 (p q r) (evalo p q) (evalo q r) (evalo r p)) '(((quote (quote (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))))))) (quote (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ()))))))) (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))))))))
null
https://raw.githubusercontent.com/gregr/experiments/1f476ff137eccd044b89545400d7eb04ee22bacb/mk-misc/micro-dkanren/test-basic.rkt
racket
With a typical search strategy, there is no refutationally complete running in the forward direction, but not in the backward direction.
#lang racket/base (require "dk.rkt" "evalo.rkt" racket/pretty) (define-relation (appendo xs ys zs) (conde ((== xs '()) (== zs ys)) ((fresh (a d ws) (== xs (cons a d)) (== zs (cons a ws)) (appendo d ys ws))))) (define-relation (reverseo ys sy) (conde ((== '() ys) (== '() sy)) ((fresh (first rest prefix) (== `(,first . ,rest) ys) ordering of the following two goals . This ordering works well when (reverseo rest prefix) (appendo prefix `(,first) sy))))) (define-relation (nevero x) (nevero x)) (define-relation (alwayso x) (conde ((== #t x)) ((alwayso x)))) (define-relation (sometimeso x) (conde ((nevero x)) ((alwayso x)))) (define-relation (color c) (conde ((== c 'red)) ((== c 'green)) ((== c 'blue)) ((== c 'cyan)) ((== c 'magenta)) ((== c 'yellow)) ((== c 'black)) ((== c 'white)))) (define-relation (shape s) (conde ((== s 'circle)) ((== s 'triangle)) ((== s 'rectangle)) ((== s 'pentagon)) ((== s 'hexagon)))) (define-relation (shape-or-color sc) (conde ((shape sc)) ((color sc)))) (define-syntax test (syntax-rules () ((_ name e-actual e-expected) (time (begin (printf "Testing ~s:\n" name) (let ((actual e-actual) (expected e-expected)) (unless (equal? actual expected) (printf "FAILURE\nEXPECTED: ~s\nACTUAL: ~s\n" expected actual)))))))) (test 'basic-1 (run* (q) (== 5 q)) '((5))) (test 'appendo-1 (run* (xs ys) (appendo xs ys '(a b c d))) '((() (a b c d)) ((a) (b c d)) ((a b) (c d)) ((a b c) (d)) ((a b c d) ()))) (test 'reverseo-forward (run* (xs) (reverseo '(1 2 3 4 5) xs)) '(((5 4 3 2 1)))) (test 'reverseo-backward (run* (xs) (reverseo xs '(1 2 3 4 5))) ( run 1 ( xs ) ( reverseo xs ' ( 1 2 3 4 5 ) ) ) '(((5 4 3 2 1)))) (test 'sometimeso-1 (run 5 (q) (sometimeso q)) '((#t) (#t) (#t) (#t) (#t))) (test 'choices-1 (run 20 (sc) (shape-or-color sc)) '((circle) (triangle) (red) (green) (rectangle) (blue) (pentagon) (cyan) (hexagon) (magenta) (yellow) (black) (white))) (test 'choices-2 (run 20 (s c) (shape s) (color c)) '((circle red) (circle green) (triangle red) (circle blue) (triangle green) (circle cyan) (circle magenta) (triangle blue) (circle yellow) (rectangle red) (circle black) (triangle cyan) (circle white) (rectangle green) (triangle magenta) (triangle yellow) (rectangle blue) (pentagon red) (triangle black) (triangle white))) (test 'evalo-literal (run 1 (e) (evalo e 5)) '(((quote 5)))) cpu time : 295 real time : 319 gc time : 97 (test 'evalo-quine (run 1 (e) (evalo e e)) '(((app (lambda (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ()))))) (quote (lambda (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))))))))) (displayln "\nBeginning slower tests...") cpu time : 9776 real time : gc time : 4201 (test 'evalo-twine (run 1 (p q) (evalo p q) (evalo q p)) '(((quote (app (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))))))) (app (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))))))))) (displayln "\nThe next test may take many seconds...") cpu time : 219963 real time : 224929 gc time : 58448 (test 'evalo-thrine (run 1 (p q r) (evalo p q) (evalo q r) (evalo r p)) '(((quote (quote (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))))))) (quote (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ()))))))) (app (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))) (quote (lambda (cons (quote quote) (cons (cons (quote quote) (cons (cons (quote app) (cons (var ()) (cons (cons (quote quote) (cons (var ()) (quote ()))) (quote ())))) (quote ()))) (quote ())))))))))
0ed829fe6b619fa4ddc2a40488baecacf21dd4e4c1584fd55570b1ba9d37e065
ocurrent/ocurrent-skeleton
pipeline.mli
val v : repo:Current_git.Local.t -> unit -> unit Current.t (** [v ~repo ()] is a pipeline that monitors Git repository [repo]. *)
null
https://raw.githubusercontent.com/ocurrent/ocurrent-skeleton/327dc23cac5511070a022ae3d5933ef60b4e7b9b/src/pipeline.mli
ocaml
* [v ~repo ()] is a pipeline that monitors Git repository [repo].
val v : repo:Current_git.Local.t -> unit -> unit Current.t
cb276be037fe446928722bec29a538b8796ee7f8106b3d94b920984ba17be28a
SahilKang/cl-avro
mop.lisp
Copyright 2021 - 2022 Google LLC ;;; ;;; This file is part of cl-avro. ;;; ;;; cl-avro is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;; (at your option) any later version. ;;; ;;; cl-avro is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License ;;; along with cl-avro. If not, see </>. (in-package #:cl-user) (defpackage #:cl-avro.internal.mop (:use #:cl) (:export #:definit #:scalar-class #:scalarize #:late-class #:early->late #:schema-class #:all-or-nothing-reinitialization)) (in-package #:cl-avro.internal.mop) ;;; definit (defmacro definit ((instance qualifier &rest initargs) &body body) `(progn (defmethod initialize-instance ,qualifier (,instance ,@initargs) ,@body) (defmethod reinitialize-instance ,qualifier (,instance ,@initargs) ,@body))) ;;; ensure-superclass (declaim (ftype (function (class class) (values boolean &optional)) superclassp)) (defun superclassp (superclass subclass) "True if SUPERCLASS is an inclusive superclass of SUBCLASS." (nth-value 0 (subtypep subclass superclass))) (declaim (ftype (function ((or class symbol) list) (values cons &optional)) ensure-superclass)) (defun ensure-superclass (class initargs) (let ((class (if (symbolp class) (find-class class) class))) (pushnew class (getf initargs :direct-superclasses) :test #'superclassp)) initargs) ;;; all-or-nothing-reinitialization (defclass all-or-nothing-reinitialization () ()) (defmethod reinitialize-instance :around ((instance all-or-nothing-reinitialization) &rest initargs &key &allow-other-keys) (let ((new (apply #'make-instance (class-of instance) initargs)) (instance (call-next-method))) (loop with terminals = (mapcar #'find-class '(standard-class standard-object)) and classes = (list (class-of instance)) while classes for class = (pop classes) unless (member class terminals) do (setf classes (append classes (closer-mop:class-direct-superclasses class))) (loop for slot in (closer-mop:class-direct-slots class) for name = (closer-mop:slot-definition-name slot) if (slot-boundp new name) do (setf (slot-value instance name) (slot-value new name)) else do (slot-makunbound instance name))) (closer-mop:finalize-inheritance instance) instance)) ;;; scalar-class ;; TODO maybe eval-when :compile-toplevel (declaim (ftype (function (list) (values boolean &optional)) keywordsp)) (defun keywordsp (list) (every #'keywordp list)) (deftype list<keyword> () '(and list (satisfies keywordsp))) (defclass scalar-class (standard-class) ((scalars :initarg :scalars :reader scalars :type list<keyword> :documentation "Initargs to scalarize.")) (:default-initargs :scalars nil)) (defmethod closer-mop:validate-superclass ((class scalar-class) (superclass standard-class)) t) (definit ((instance scalar-class) :around &rest initargs) (setf initargs (ensure-superclass 'scalar-object initargs)) (apply #'call-next-method instance initargs)) ;;; scalar-object (defclass scalar-object () ()) (declaim (ftype (function (cons) (values t &optional)) %scalarize)) (defun %scalarize (list) (if (= (length list) 1) (first list) list)) (declaim (ftype (function (t) (values t &optional)) scalarize)) (defun scalarize (value) (if (consp value) (%scalarize value) value)) (declaim (ftype (function (scalar-class) (values list &optional)) initargs-to-scalarize)) (defun initargs-to-scalarize (class) (loop for superclass in (closer-mop:class-precedence-list class) when (typep superclass 'scalar-class) append (scalars superclass) into initargs finally (return (delete-duplicates initargs)))) (definit ((instance scalar-object) :around &rest initargs) (loop with initargs-to-scalarize = (initargs-to-scalarize (class-of instance)) initially (assert (evenp (length initargs))) for (initarg value) on initargs by #'cddr if (member initarg initargs-to-scalarize) nconc (list initarg (scalarize value)) into scalarized-initargs else nconc (list initarg value) into scalarized-initargs finally (return (apply #'call-next-method instance scalarized-initargs)))) ;;; late-slot (defclass late-slot (closer-mop:standard-direct-slot-definition) ((late-type :type (or symbol cons) :reader late-type))) (defmethod initialize-instance :around ((instance late-slot) &rest initargs &key (late-type (error "Must supply LATE-TYPE")) (early-type `(or symbol ,late-type))) (setf (getf initargs :type) early-type) (remf initargs :early-type) (remf initargs :late-type) (let ((instance (apply #'call-next-method instance initargs))) (setf (slot-value instance 'late-type) late-type))) ;;; finalizing-reader (defclass finalizing-reader (closer-mop:standard-reader-method) ()) (defmethod initialize-instance :around ((instance finalizing-reader) &rest initargs &key slot-definition) (let* ((gf (symbol-function (first (closer-mop:slot-definition-readers slot-definition)))) (lambda `(lambda (class) (closer-mop:ensure-finalized class))) (method-lambda (closer-mop:make-method-lambda gf (closer-mop:class-prototype (class-of instance)) lambda nil)) (documentation "Finalizes class before reader method executes.") (primary-method (call-next-method)) (before-method (let ((instance (allocate-instance (class-of instance)))) (setf (getf initargs :qualifiers) '(:before) (getf initargs :documentation) documentation (getf initargs :function) (compile nil method-lambda)) (apply #'call-next-method instance initargs)))) (add-method gf before-method) primary-method)) ;;; late-class (defclass late-class (standard-class) ()) (defmethod closer-mop:validate-superclass ((class late-class) (superclass standard-class)) t) (defmethod closer-mop:direct-slot-definition-class ((class late-class) &rest initargs) (if (or (member :early-type initargs) (member :late-type initargs)) (find-class 'late-slot) (call-next-method))) (defmethod closer-mop:reader-method-class ((class late-class) slot &rest initargs) (declare (ignore class slot initargs)) (find-class 'finalizing-reader)) (definit ((instance late-class) :around &rest initargs) (setf initargs (ensure-superclass 'late-object initargs)) (apply #'call-next-method instance initargs)) ;;; late-object (defclass late-object () ()) (defmethod closer-mop:finalize-inheritance :before ((instance late-object)) (flet ((not-late-slot-p (slot) (not (typep slot 'late-slot))) (process-slot (slot) (process-slot instance slot))) (let ((slots (remove-if #'not-late-slot-p (closer-mop:class-direct-slots (class-of instance))))) (map nil #'process-slot slots)))) (declaim (ftype (function (late-object late-slot) (values &optional)) process-slot)) (defun process-slot (class slot) (let* ((name (closer-mop:slot-definition-name slot)) (type (late-type slot)) (value (early->late class name type (when (slot-boundp class name) (slot-value class name))))) (unless (typep value type) (error "Slot ~S expects type ~S: ~S" name type value)) (setf (slot-value class name) value)) (values)) (defgeneric early->late (class name type value) (:method (class (name symbol) type value) (declare (ignore class name)) (if (and (symbolp value) (not (typep value type))) (find-class value) value))) ;;; schema-class TODO rename this to object - class or something (defclass schema-class (scalar-class late-class) ((object-class :initarg :object-class :reader object-class :type symbol)) (:default-initargs :object-class (error "Must supply OBJECT-CLASS"))) (defmethod closer-mop:validate-superclass ((class schema-class) (superclass scalar-class)) t) (defmethod closer-mop:validate-superclass ((class schema-class) (superclass late-class)) t) (definit ((instance schema-class) :around &rest initargs &key object-class) (setf (getf initargs :object-class) (scalarize object-class) initargs (ensure-superclass 'schema-object initargs)) (apply #'call-next-method instance initargs)) ;;; schema-object (defclass schema-object () ()) (definit ((instance schema-object) :around &rest initargs) (setf initargs (ensure-superclass (object-class (class-of instance)) initargs)) (apply #'call-next-method instance initargs))
null
https://raw.githubusercontent.com/SahilKang/cl-avro/34f227936a303f34a94e46480a7172a6171835fa/src/mop.lisp
lisp
This file is part of cl-avro. cl-avro is free software: you can redistribute it and/or modify (at your option) any later version. cl-avro is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with cl-avro. If not, see </>. definit ensure-superclass all-or-nothing-reinitialization scalar-class TODO maybe eval-when :compile-toplevel scalar-object late-slot finalizing-reader late-class late-object schema-class schema-object
Copyright 2021 - 2022 Google LLC it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package #:cl-user) (defpackage #:cl-avro.internal.mop (:use #:cl) (:export #:definit #:scalar-class #:scalarize #:late-class #:early->late #:schema-class #:all-or-nothing-reinitialization)) (in-package #:cl-avro.internal.mop) (defmacro definit ((instance qualifier &rest initargs) &body body) `(progn (defmethod initialize-instance ,qualifier (,instance ,@initargs) ,@body) (defmethod reinitialize-instance ,qualifier (,instance ,@initargs) ,@body))) (declaim (ftype (function (class class) (values boolean &optional)) superclassp)) (defun superclassp (superclass subclass) "True if SUPERCLASS is an inclusive superclass of SUBCLASS." (nth-value 0 (subtypep subclass superclass))) (declaim (ftype (function ((or class symbol) list) (values cons &optional)) ensure-superclass)) (defun ensure-superclass (class initargs) (let ((class (if (symbolp class) (find-class class) class))) (pushnew class (getf initargs :direct-superclasses) :test #'superclassp)) initargs) (defclass all-or-nothing-reinitialization () ()) (defmethod reinitialize-instance :around ((instance all-or-nothing-reinitialization) &rest initargs &key &allow-other-keys) (let ((new (apply #'make-instance (class-of instance) initargs)) (instance (call-next-method))) (loop with terminals = (mapcar #'find-class '(standard-class standard-object)) and classes = (list (class-of instance)) while classes for class = (pop classes) unless (member class terminals) do (setf classes (append classes (closer-mop:class-direct-superclasses class))) (loop for slot in (closer-mop:class-direct-slots class) for name = (closer-mop:slot-definition-name slot) if (slot-boundp new name) do (setf (slot-value instance name) (slot-value new name)) else do (slot-makunbound instance name))) (closer-mop:finalize-inheritance instance) instance)) (declaim (ftype (function (list) (values boolean &optional)) keywordsp)) (defun keywordsp (list) (every #'keywordp list)) (deftype list<keyword> () '(and list (satisfies keywordsp))) (defclass scalar-class (standard-class) ((scalars :initarg :scalars :reader scalars :type list<keyword> :documentation "Initargs to scalarize.")) (:default-initargs :scalars nil)) (defmethod closer-mop:validate-superclass ((class scalar-class) (superclass standard-class)) t) (definit ((instance scalar-class) :around &rest initargs) (setf initargs (ensure-superclass 'scalar-object initargs)) (apply #'call-next-method instance initargs)) (defclass scalar-object () ()) (declaim (ftype (function (cons) (values t &optional)) %scalarize)) (defun %scalarize (list) (if (= (length list) 1) (first list) list)) (declaim (ftype (function (t) (values t &optional)) scalarize)) (defun scalarize (value) (if (consp value) (%scalarize value) value)) (declaim (ftype (function (scalar-class) (values list &optional)) initargs-to-scalarize)) (defun initargs-to-scalarize (class) (loop for superclass in (closer-mop:class-precedence-list class) when (typep superclass 'scalar-class) append (scalars superclass) into initargs finally (return (delete-duplicates initargs)))) (definit ((instance scalar-object) :around &rest initargs) (loop with initargs-to-scalarize = (initargs-to-scalarize (class-of instance)) initially (assert (evenp (length initargs))) for (initarg value) on initargs by #'cddr if (member initarg initargs-to-scalarize) nconc (list initarg (scalarize value)) into scalarized-initargs else nconc (list initarg value) into scalarized-initargs finally (return (apply #'call-next-method instance scalarized-initargs)))) (defclass late-slot (closer-mop:standard-direct-slot-definition) ((late-type :type (or symbol cons) :reader late-type))) (defmethod initialize-instance :around ((instance late-slot) &rest initargs &key (late-type (error "Must supply LATE-TYPE")) (early-type `(or symbol ,late-type))) (setf (getf initargs :type) early-type) (remf initargs :early-type) (remf initargs :late-type) (let ((instance (apply #'call-next-method instance initargs))) (setf (slot-value instance 'late-type) late-type))) (defclass finalizing-reader (closer-mop:standard-reader-method) ()) (defmethod initialize-instance :around ((instance finalizing-reader) &rest initargs &key slot-definition) (let* ((gf (symbol-function (first (closer-mop:slot-definition-readers slot-definition)))) (lambda `(lambda (class) (closer-mop:ensure-finalized class))) (method-lambda (closer-mop:make-method-lambda gf (closer-mop:class-prototype (class-of instance)) lambda nil)) (documentation "Finalizes class before reader method executes.") (primary-method (call-next-method)) (before-method (let ((instance (allocate-instance (class-of instance)))) (setf (getf initargs :qualifiers) '(:before) (getf initargs :documentation) documentation (getf initargs :function) (compile nil method-lambda)) (apply #'call-next-method instance initargs)))) (add-method gf before-method) primary-method)) (defclass late-class (standard-class) ()) (defmethod closer-mop:validate-superclass ((class late-class) (superclass standard-class)) t) (defmethod closer-mop:direct-slot-definition-class ((class late-class) &rest initargs) (if (or (member :early-type initargs) (member :late-type initargs)) (find-class 'late-slot) (call-next-method))) (defmethod closer-mop:reader-method-class ((class late-class) slot &rest initargs) (declare (ignore class slot initargs)) (find-class 'finalizing-reader)) (definit ((instance late-class) :around &rest initargs) (setf initargs (ensure-superclass 'late-object initargs)) (apply #'call-next-method instance initargs)) (defclass late-object () ()) (defmethod closer-mop:finalize-inheritance :before ((instance late-object)) (flet ((not-late-slot-p (slot) (not (typep slot 'late-slot))) (process-slot (slot) (process-slot instance slot))) (let ((slots (remove-if #'not-late-slot-p (closer-mop:class-direct-slots (class-of instance))))) (map nil #'process-slot slots)))) (declaim (ftype (function (late-object late-slot) (values &optional)) process-slot)) (defun process-slot (class slot) (let* ((name (closer-mop:slot-definition-name slot)) (type (late-type slot)) (value (early->late class name type (when (slot-boundp class name) (slot-value class name))))) (unless (typep value type) (error "Slot ~S expects type ~S: ~S" name type value)) (setf (slot-value class name) value)) (values)) (defgeneric early->late (class name type value) (:method (class (name symbol) type value) (declare (ignore class name)) (if (and (symbolp value) (not (typep value type))) (find-class value) value))) TODO rename this to object - class or something (defclass schema-class (scalar-class late-class) ((object-class :initarg :object-class :reader object-class :type symbol)) (:default-initargs :object-class (error "Must supply OBJECT-CLASS"))) (defmethod closer-mop:validate-superclass ((class schema-class) (superclass scalar-class)) t) (defmethod closer-mop:validate-superclass ((class schema-class) (superclass late-class)) t) (definit ((instance schema-class) :around &rest initargs &key object-class) (setf (getf initargs :object-class) (scalarize object-class) initargs (ensure-superclass 'schema-object initargs)) (apply #'call-next-method instance initargs)) (defclass schema-object () ()) (definit ((instance schema-object) :around &rest initargs) (setf initargs (ensure-superclass (object-class (class-of instance)) initargs)) (apply #'call-next-method instance initargs))
10bb40a785110f8a0aa465c54bab9e02642bda95b19764d6169c1a33c1ecc252
fission-codes/fission
Types.hs
module Fission.Error.Mismatch.Types (Mismatch (..)) where import Fission.Prelude data Mismatch a = Mismatch deriving (Eq, Show, Exception)
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-core/library/Fission/Error/Mismatch/Types.hs
haskell
module Fission.Error.Mismatch.Types (Mismatch (..)) where import Fission.Prelude data Mismatch a = Mismatch deriving (Eq, Show, Exception)
8f5141b6e01ecff38207dacad37f2e4a6f9bfb6693e29e8ae33e35525cde9fa1
MaskRay/OJHaskell
35.hs
import Control.Monad import Data.List primeFactors = loop primes where loop ps@(p:ps') n | p*p > n = [n] | n `mod` p == 0 = p : loop ps (n `div` p) | otherwise = loop ps' n primes = 2 : filter ((== 1) . length . primeFactors) [3,5..] isPrime n = case primeFactors n of [1] -> False [_] -> True otherwise -> False rots l = map (\i -> let (x,y) = splitAt i l in y ++ x) [0..length l - 1] isCircular = all (isPrime . l2n) . rots where l2n = foldl1 (\x y -> x * 10 + y) circular 1 = [[2], [3], [5], [7]] circular n = filter isCircular . replicateM n $ [1,3,7,9] main = print . length . concatMap circular $ [1..6]
null
https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/35.hs
haskell
import Control.Monad import Data.List primeFactors = loop primes where loop ps@(p:ps') n | p*p > n = [n] | n `mod` p == 0 = p : loop ps (n `div` p) | otherwise = loop ps' n primes = 2 : filter ((== 1) . length . primeFactors) [3,5..] isPrime n = case primeFactors n of [1] -> False [_] -> True otherwise -> False rots l = map (\i -> let (x,y) = splitAt i l in y ++ x) [0..length l - 1] isCircular = all (isPrime . l2n) . rots where l2n = foldl1 (\x y -> x * 10 + y) circular 1 = [[2], [3], [5], [7]] circular n = filter isCircular . replicateM n $ [1,3,7,9] main = print . length . concatMap circular $ [1..6]
110572bda2fea10bcdc6fc24947061f9841ca6ae5ac10d7ae65d3489133296e2
grin-compiler/ghc-wpc-sample-programs
Expr.hs
| Module : . . Expr Description : Parse Expressions . License : : The Idris Community . Module : Idris.Parser.Expr Description : Parse Expressions. License : BSD3 Maintainer : The Idris Community. -} # LANGUAGE FlexibleContexts , TupleSections # module Idris.Parser.Expr where import Idris.AbsSyntax import Idris.Core.TT import Idris.DSL import Idris.Options import Idris.Parser.Helpers import Idris.Parser.Ops import Prelude hiding (pi) import Control.Applicative import Control.Arrow (left) import Control.Monad import qualified Control.Monad.Combinators.Expr as P import Control.Monad.State.Strict import Data.Function (on) import Data.List import Data.Maybe import Text.Megaparsec ((<?>)) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P -- | Allow implicit type declarations allowImp :: SyntaxInfo -> SyntaxInfo allowImp syn = syn { implicitAllowed = True, constraintAllowed = False } -- | Disallow implicit type declarations disallowImp :: SyntaxInfo -> SyntaxInfo disallowImp = scopedImp -- | Implicits hare are scoped rather than top level scopedImp :: SyntaxInfo -> SyntaxInfo scopedImp syn = syn { implicitAllowed = False, constraintAllowed = False } -- | Allow scoped constraint arguments allowConstr :: SyntaxInfo -> SyntaxInfo allowConstr syn = syn { constraintAllowed = True } | Parses an expression as a whole @ FullExpr : : = ; @ @ FullExpr ::= Expr EOF_t; @ -} fullExpr :: SyntaxInfo -> IdrisParser PTerm fullExpr syn = do x <- expr syn P.eof i <- get return $ debindApp syn (desugar syn i x) tryFullExpr :: SyntaxInfo -> IState -> String -> Either Err PTerm tryFullExpr syn st = left (Msg . show . parseErrorDoc) . runparser (fullExpr syn) st "" {- | Parses an expression @ Expr ::= Pi @ -} expr :: SyntaxInfo -> IdrisParser PTerm expr = pi | Parses an expression with possible operator applied @ OpExpr : : = { - Expression Parser with Operators based on ' @ OpExpr ::= {- Expression Parser with Operators based on Expr' -}; @ -} opExpr :: SyntaxInfo -> IdrisParser PTerm opExpr syn = do i <- get P.makeExprParser (expr' syn) (table (idris_infixes i)) | Parses either an internally defined expression or a user - defined one @ ' : : = " External ( User - defined ) Syntax " | InternalExpr ; @ a user-defined one @ Expr' ::= "External (User-defined) Syntax" | InternalExpr; @ -} expr' :: SyntaxInfo -> IdrisParser PTerm expr' syn = P.try (externalExpr syn) <|> internalExpr syn <?> "expression" {- | Parses a user-defined expression -} externalExpr :: SyntaxInfo -> IdrisParser PTerm externalExpr syn = do i <- get (expr, outerFC@(FC fn _ _)) <- withExtent $ extensions syn (syntaxRulesList $ syntax_rules i) return (mapPTermFC (fixFC outerFC) (fixFCH fn outerFC) expr) <?> "user-defined expression" where -- Fix non-highlighting FCs by approximating with the span of the syntax application fixFC outer inner | inner `fcIn` outer = inner | otherwise = outer -- Fix highlighting FCs by making them useless, to avoid spurious highlights fixFCH fn outer inner | inner `fcIn` outer = inner | otherwise = FileFC fn {- | Parses a simple user-defined expression -} simpleExternalExpr :: SyntaxInfo -> IdrisParser PTerm simpleExternalExpr syn = do i <- get extensions syn (filter isSimple (syntaxRulesList $ syntax_rules i)) where isSimple (Rule (Expr x:xs) _ _) = False isSimple (Rule (SimpleExpr x:xs) _ _) = False isSimple (Rule [Keyword _] _ _) = True isSimple (Rule [Symbol _] _ _) = True isSimple (Rule (_:xs) _ _) = case last xs of Keyword _ -> True Symbol _ -> True _ -> False isSimple _ = False {- | Tries to parse a user-defined expression given a list of syntactic extensions -} extensions :: SyntaxInfo -> [Syntax] -> IdrisParser PTerm extensions syn rules = extension syn [] (filter isValid rules) <?> "user-defined expression" where isValid :: Syntax -> Bool isValid (Rule _ _ AnySyntax) = True isValid (Rule _ _ PatternSyntax) = inPattern syn isValid (Rule _ _ TermSyntax) = not (inPattern syn) isValid (DeclRule _ _) = False ^ the FC is for highlighting information deriving Show extension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser PTerm extension syn ns rules = P.choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs -> case head rs of -- can never be [] Rule (symb:_) _ _ -> P.try $ do n <- extensionSymbol symb extension syn (n : ns) [Rule ss t ctx | (Rule (_:ss) t ctx) <- rs] If we have more than one Rule in this bucket , our grammar is -- nondeterministic. Rule [] ptm _ -> return (flatten (updateSynMatch (mapMaybe id ns) ptm)) where ruleGroup [] [] = True ruleGroup (s1:_) (s2:_) = s1 == s2 ruleGroup _ _ = False extensionSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch)) extensionSymbol (Keyword n) = Nothing <$ keyword (show n) extensionSymbol (Expr n) = do tm <- expr syn return $ Just (n, SynTm tm) extensionSymbol (SimpleExpr n) = do tm <- simpleExpr syn return $ Just (n, SynTm tm) extensionSymbol (Binding n) = do (b, fc) <- withExtent name return $ Just (n, SynBind fc b) extensionSymbol (Symbol s) = Nothing <$ highlight AnnKeyword (symbol s) flatten :: PTerm -> PTerm -- flatten application flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs)) flatten t = t updateSynMatch = update where updateB :: [(Name, SynMatch)] -> (Name, FC) -> (Name, FC) updateB ns (n, fc) = case lookup n ns of Just (SynBind tfc t) -> (t, tfc) _ -> (n, fc) update :: [(Name, SynMatch)] -> PTerm -> PTerm update ns (PRef fc hls n) = case lookup n ns of Just (SynTm t) -> t _ -> PRef fc hls n update ns (PPatvar fc n) = uncurry (flip PPatvar) $ updateB ns (n, fc) update ns (PLam fc n nfc ty sc) = let (n', nfc') = updateB ns (n, nfc) in PLam fc n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PPi p n fc ty sc) = let (n', nfc') = updateB ns (n, fc) in PPi (updTacImp ns p) n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PLet fc rc n nfc ty val sc) = let (n', nfc') = updateB ns (n, nfc) in PLet fc rc n' nfc' (update ns ty) (update ns val) (update (dropn n ns) sc) update ns (PApp fc t args) = PApp fc (update ns t) (map (fmap (update ns)) args) update ns (PAppBind fc t args) = PAppBind fc (update ns t) (map (fmap (update ns)) args) update ns (PMatchApp fc n) = let (n', nfc') = updateB ns (n, fc) in PMatchApp nfc' n' update ns (PIfThenElse fc c t f) = PIfThenElse fc (update ns c) (update ns t) (update ns f) update ns (PCase fc c opts) = PCase fc (update ns c) (map (pmap (update ns)) opts) update ns (PRewrite fc by eq tm mty) = PRewrite fc by (update ns eq) (update ns tm) (fmap (update ns) mty) update ns (PPair fc hls p l r) = PPair fc hls p (update ns l) (update ns r) update ns (PDPair fc hls p l t r) = PDPair fc hls p (update ns l) (update ns t) (update ns r) update ns (PAs fc n t) = PAs fc (fst $ updateB ns (n, NoFC)) (update ns t) update ns (PAlternative ms a as) = PAlternative ms a (map (update ns) as) update ns (PHidden t) = PHidden (update ns t) update ns (PGoal fc r n sc) = PGoal fc (update ns r) n (update ns sc) update ns (PDoBlock ds) = PDoBlock $ map (upd ns) ds where upd :: [(Name, SynMatch)] -> PDo -> PDo upd ns (DoExp fc t) = DoExp fc (update ns t) upd ns (DoBind fc n nfc t) = DoBind fc n nfc (update ns t) upd ns (DoLet fc rc n nfc ty t) = DoLet fc rc n nfc (update ns ty) (update ns t) upd ns (DoBindP fc i t ts) = DoBindP fc (update ns i) (update ns t) (map (\(l,r) -> (update ns l, update ns r)) ts) upd ns (DoLetP fc i t ts) = DoLetP fc (update ns i) (update ns t) (map (\(l,r) -> (update ns l, update ns r)) ts) upd ns (DoRewrite fc h) = DoRewrite fc (update ns h) update ns (PIdiom fc t) = PIdiom fc $ update ns t update ns (PMetavar fc n) = uncurry (flip PMetavar) $ updateB ns (n, fc) update ns (PProof tacs) = PProof $ map (updTactic ns) tacs update ns (PTactics tacs) = PTactics $ map (updTactic ns) tacs update ns (PDisamb nsps t) = PDisamb nsps $ update ns t update ns (PUnifyLog t) = PUnifyLog $ update ns t update ns (PNoImplicits t) = PNoImplicits $ update ns t update ns (PQuasiquote tm mty) = PQuasiquote (update ns tm) (fmap (update ns) mty) update ns (PUnquote t) = PUnquote $ update ns t update ns (PQuoteName n res fc) = let (n', fc') = (updateB ns (n, fc)) in PQuoteName n' res fc' update ns (PRunElab fc t nsp) = PRunElab fc (update ns t) nsp update ns (PConstSugar fc t) = PConstSugar fc $ update ns t -- PConstSugar probably can't contain anything substitutable, but it's hard to track update ns t = t updTactic :: [(Name, SynMatch)] -> PTactic -> PTactic -- handle all the ones with Names explicitly, then use fmap for the rest with PTerms updTactic ns (Intro ns') = Intro $ map (fst . updateB ns . (, NoFC)) ns' updTactic ns (Focus n) = Focus . fst $ updateB ns (n, NoFC) updTactic ns (Refine n bs) = Refine (fst $ updateB ns (n, NoFC)) bs updTactic ns (Claim n t) = Claim (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (MatchRefine n) = MatchRefine (fst $ updateB ns (n, NoFC)) updTactic ns (LetTac n t) = LetTac (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (LetTacTy n ty tm) = LetTacTy (fst $ updateB ns (n, NoFC)) (update ns ty) (update ns tm) updTactic ns (ProofSearch rec prover depth top psns hints) = ProofSearch rec prover depth (fmap (fst . updateB ns . (, NoFC)) top) (map (fst . updateB ns . (, NoFC)) psns) (map (fst . updateB ns . (, NoFC)) hints) updTactic ns (Try l r) = Try (updTactic ns l) (updTactic ns r) updTactic ns (TSeq l r) = TSeq (updTactic ns l) (updTactic ns r) updTactic ns (GoalType s tac) = GoalType s $ updTactic ns tac updTactic ns (TDocStr (Left n)) = TDocStr . Left . fst $ updateB ns (n, NoFC) updTactic ns t = fmap (update ns) t updTacImp ns (TacImp o st scr r) = TacImp o st (update ns scr) r updTacImp _ x = x dropn :: Name -> [(Name, a)] -> [(Name, a)] dropn n [] = [] dropn n ((x,t) : xs) | n == x = xs | otherwise = (x,t):dropn n xs | Parses a ( normal ) built - in expression @ InternalExpr : : = UnifyLog | RecordType | SimpleExpr | Lambda | QuoteGoal | Let | If | RewriteTerm | CaseExpr | | App ; @ @ InternalExpr ::= UnifyLog | RecordType | SimpleExpr | Lambda | QuoteGoal | Let | If | RewriteTerm | CaseExpr | DoBlock | App ; @ -} internalExpr :: SyntaxInfo -> IdrisParser PTerm internalExpr syn = unifyLog syn <|> runElab syn <|> disamb syn <|> noImplicits syn <|> recordType syn <|> if_ syn <|> lambda syn <|> quoteGoal syn <|> let_ syn <|> rewriteTerm syn <|> doBlock syn <|> caseExpr syn <|> app syn <?> "expression" {- | Parses the "impossible" keyword @ Impossible ::= 'impossible' @ -} impossible :: IdrisParser PTerm impossible = PImpossible <$ keyword "impossible" | Parses a case expression @ : : = ' case ' ' of ' OpenBlock ; @ @ CaseExpr ::= 'case' Expr 'of' OpenBlock CaseOption+ CloseBlock; @ -} caseExpr :: SyntaxInfo -> IdrisParser PTerm caseExpr syn = do keyword "case" (scr, fc) <- withExtent $ expr syn keyword "of" opts <- indentedBlock1 (caseOption syn) return (PCase fc scr opts) <?> "case expression" | Parses a case in a case expression @ CaseOption : : = Expr ( Impossible | ' = > ' Expr ) Terminator ; @ @ CaseOption ::= Expr (Impossible | '=>' Expr) Terminator ; @ -} caseOption :: SyntaxInfo -> IdrisParser (PTerm, PTerm) caseOption syn = do lhs <- expr (disallowImp (syn { inPattern = True })) r <- impossible <|> symbol "=>" *> expr syn return (lhs, r) <?> "case option" warnTacticDeprecation :: FC -> IdrisParser () warnTacticDeprecation fc = parserWarning fc (Just NoOldTacticDeprecationWarnings) (Msg "This style of tactic proof is deprecated. See %runElab for the replacement.") | Parses a proof block @ ProofExpr : : = ' proof ' OpenBlock Tactic ' * CloseBlock ; @ @ ProofExpr ::= 'proof' OpenBlock Tactic'* CloseBlock ; @ -} proofExpr :: SyntaxInfo -> IdrisParser PTerm proofExpr syn = do kw <- extent $ keyword "proof" ts <- indentedBlock1 (tactic syn) warnTacticDeprecation kw return $ PProof ts <?> "proof block" | Parses a tactics block @ TacticsExpr : = ' tactics ' OpenBlock Tactic ' * CloseBlock ; @ @ TacticsExpr := 'tactics' OpenBlock Tactic'* CloseBlock ; @ -} tacticsExpr :: SyntaxInfo -> IdrisParser PTerm tacticsExpr syn = do kw <- extent $ keyword "tactics" ts <- indentedBlock1 (tactic syn) warnTacticDeprecation kw return $ PTactics ts <?> "tactics block" | Parses a simple expression @ SimpleExpr : : = { - External ( User - defined ) Simple Expression @ SimpleExpr ::= {- External (User-defined) Simple Expression -} | '?' Name | % 'implementation' | 'Refl' ('{' Expr '}')? | ProofExpr | TacticsExpr | FnName | Idiom | List | Alt | Bracketed | Constant | Type | 'Void' | Quasiquote | NameQuote | Unquote | '_' ; @ -} simpleExpr :: SyntaxInfo -> IdrisParser PTerm simpleExpr syn = P.try (simpleExternalExpr syn) <|> do (x, FC f (l, c) end) <- P.try (lchar '?' *> withExtent name) return (PMetavar (FC f (l, c-1) end) x) <|> do lchar '%'; fc <- extent $ reserved "implementation"; return (PResolveTC fc) <|> do lchar '%'; fc <- extent $ reserved "instance" parserWarning fc Nothing $ Msg "The use of %instance is deprecated, use %implementation instead." return (PResolveTC fc) <|> proofExpr syn <|> tacticsExpr syn <|> P.try (do fc <- extent (reserved "Type*"); return $ PUniverse fc AllTypes) <|> do fc <- extent $ reserved "AnyType"; return $ PUniverse fc AllTypes <|> PType <$> extent (reserved "Type") <|> do fc <- extent $ reserved "UniqueType"; return $ PUniverse fc UniqueType <|> do fc <- extent $ reserved "NullType"; return $ PUniverse fc NullType <|> do (c, cfc) <- withExtent constant return (modifyConst syn cfc (PConstant cfc c)) <|> do symbol "'"; (str, fc) <- withExtent name return (PApp fc (PRef fc [] (sUN "Symbol_")) [pexp (PConstant NoFC (Str (show str)))]) <|> do (x, fc) <- withExtent fnName if inPattern syn then P.option (PRef fc [fc] x) (do reservedOp "@" (s, fcIn) <- withExtent $ simpleExpr syn return (PAs fcIn x s)) else return (PRef fc [fc] x) <|> idiom syn <|> listExpr syn <|> alt syn <|> do reservedOp "!" (s, fc) <- withExtent $ simpleExpr syn return (PAppBind fc s []) <|> bracketed (disallowImp syn) <|> quasiquote syn <|> namequote syn <|> unquote syn <|> do lchar '_'; return Placeholder <?> "expression" |Parses an expression in parentheses @ Bracketed : : = ' ( ' Bracketed ' @ @ Bracketed ::= '(' Bracketed' @ -} bracketed :: SyntaxInfo -> IdrisParser PTerm bracketed syn = do (FC fn (sl, sc) _) <- extent (lchar '(') <?> "parenthesized expression" bracketed' (FC fn (sl, sc) (sl, sc+1)) (syn { withAppAllowed = True }) |Parses the rest of an expression in braces @ Bracketed ' : : = ' ) ' | Expr ' ) ' | ExprList ' ) ' | DependentPair ' ) ' | Operator Expr ' ) ' | Expr Operator ' ) ' ; @ @ Bracketed' ::= ')' | Expr ')' | ExprList ')' | DependentPair ')' | Operator Expr ')' | Expr Operator ')' ; @ -} bracketed' :: FC -> SyntaxInfo -> IdrisParser PTerm bracketed' open syn = do fc <- extent (addExtent open *> lchar ')') return $ PTrue fc TypeOrTerm <|> P.try (dependentPair TypeOrTerm [] open syn) <|> P.try (do (opName, fc) <- withExtent operatorName guardNotPrefix opName e <- expr syn lchar ')' return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder (PApp fc (PRef fc [] opName) [pexp (PRef fc [] (sMN 1000 "ARG")), pexp e])) <|> P.try (simpleExpr syn >>= \l -> P.try (do (opName, fc) <- withExtent operatorName lchar ')' return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder (PApp fc (PRef fc [] opName) [pexp l, pexp (PRef fc [] (sMN 1000 "ARG"))])) <|> bracketedExpr syn open l) <|> do l <- expr (allowConstr syn) bracketedExpr (allowConstr syn) open l where justPrefix :: FixDecl -> Maybe Name justPrefix (Fix (PrefixN _) opName) = Just (sUN opName) justPrefix _ = Nothing guardNotPrefix :: Name -> IdrisParser () guardNotPrefix opName = do guard $ opName /= sUN "-" guard $ opName /= sUN "!" ops <- idris_infixes <$> get guard . not . (opName `elem`) . mapMaybe justPrefix $ ops {-| Parses the rest of a dependent pair after '(' or '(Expr **' -} dependentPair :: PunInfo -> [(PTerm, Maybe (FC, PTerm), FC)] -> FC -> SyntaxInfo -> IdrisParser PTerm dependentPair pun prev openFC syn = if null prev then nametypePart <|> namePart else case pun of IsType -> nametypePart <|> namePart <|> exprPart True IsTerm -> exprPart False TypeOrTerm -> nametypePart <|> namePart <|> exprPart False where nametypePart = do (ln, lnfc, colonFC) <- P.try $ do (ln, lnfc) <- withExtent name colonFC <- extent (lchar ':') return (ln, lnfc, colonFC) lty <- expr' syn starsFC <- extent $ reservedOp "**" dependentPair IsType ((PRef lnfc [] ln, Just (colonFC, lty), starsFC):prev) openFC syn namePart = P.try $ do (ln, lnfc) <- withExtent name starsFC <- extent $ reservedOp "**" dependentPair pun ((PRef lnfc [] ln, Nothing, starsFC):prev) openFC syn exprPart isEnd = do e <- expr syn sepFCE <- let stars = (Left <$> extent (reservedOp "**")) ending = (Right <$> extent (lchar ')')) in if isEnd then ending else stars <|> ending case sepFCE of Left starsFC -> dependentPair IsTerm ((e, Nothing, starsFC):prev) openFC syn Right closeFC -> return (mkPDPairs pun openFC closeFC (reverse prev) e) mkPDPairs pun openFC closeFC ((e, cfclty, starsFC):bnds) r = (PDPair openFC ([openFC] ++ maybe [] ((: []) . fst) cfclty ++ [starsFC, closeFC] ++ (=<<) (\(_,cfclty,sfc) -> maybe [] ((: []) . fst) cfclty ++ [sfc]) bnds) pun e (maybe Placeholder snd cfclty) (mergePDPairs pun starsFC bnds r)) mergePDPairs pun starsFC' [] r = r mergePDPairs pun starsFC' ((e, cfclty, starsFC):bnds) r = PDPair starsFC' [] pun e (maybe Placeholder snd cfclty) (mergePDPairs pun starsFC bnds r) -- | Parse the contents of parentheses, after an expression has been parsed. bracketedExpr :: SyntaxInfo -> FC -> PTerm -> IdrisParser PTerm bracketedExpr syn openParenFC e = do lchar ')'; return e <|> do exprs <- some (do comma <- extent (lchar ',') r <- expr syn return (r, comma)) closeParenFC <- extent (lchar ')') let hilite = [openParenFC, closeParenFC] ++ map snd exprs return $ PPair openParenFC hilite TypeOrTerm e (mergePairs exprs) <|> do starsFC <- extent $ reservedOp "**" dependentPair IsTerm [(e, Nothing, starsFC)] openParenFC syn <?> "end of bracketed expression" where mergePairs :: [(PTerm, FC)] -> PTerm mergePairs [(t, fc)] = t mergePairs ((t, fc):rs) = PPair fc [] TypeOrTerm t (mergePairs rs) -- bit of a hack here. If the integer doesn't fit in an Int, treat it as a big integer , otherwise try fromInteger and the constants as alternatives . a better solution would be to fix fromInteger to work with Integer , as the -- name suggests, rather than Int {-| Finds optimal type for integer constant -} modifyConst :: SyntaxInfo -> FC -> PTerm -> PTerm modifyConst syn fc (PConstant inFC (BI x)) | not (inPattern syn) = PConstSugar inFC $ -- wrap in original span for highlighting PAlternative [] FirstSuccess (PApp fc (PRef fc [] (sUN "fromInteger")) [pexp (PConstant NoFC (BI (fromInteger x)))] : consts) | otherwise = PConstSugar inFC $ PAlternative [] FirstSuccess consts where consts = [ PConstant inFC (BI x) , PConstant inFC (I (fromInteger x)) , PConstant inFC (B8 (fromInteger x)) , PConstant inFC (B16 (fromInteger x)) , PConstant inFC (B32 (fromInteger x)) , PConstant inFC (B64 (fromInteger x)) ] modifyConst syn fc x = x {- | Parses an alternative expression @ Alt ::= '(|' Expr_List '|)'; Expr_List ::= Expr' | Expr' ',' Expr_List ; @ -} alt :: SyntaxInfo -> IdrisParser PTerm alt syn = do symbol "(|"; alts <- P.sepBy1 (expr' (syn { withAppAllowed = False })) (lchar ','); symbol "|)" return (PAlternative [] FirstSuccess alts) {- | Parses a possibly hidden simple expression @ HSimpleExpr ::= '.' SimpleExpr | SimpleExpr ; @ -} hsimpleExpr :: SyntaxInfo -> IdrisParser PTerm hsimpleExpr syn = do lchar '.' e <- simpleExpr syn return $ PHidden e <|> simpleExpr syn <?> "expression" | Parses a unification log expression UnifyLog : : = ' % ' ' unifyLog ' SimpleExpr ; UnifyLog ::= '%' 'unifyLog' SimpleExpr ; -} unifyLog :: SyntaxInfo -> IdrisParser PTerm unifyLog syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "unifyLog" PUnifyLog <$> simpleExpr syn <?> "unification log expression" | Parses a new - style tactics expression RunTactics : : = ' % ' ' runElab ' SimpleExpr ; RunTactics ::= '%' 'runElab' SimpleExpr ; -} runElab :: SyntaxInfo -> IdrisParser PTerm runElab syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "runElab" (tm, fc) <- withExtent $ simpleExpr syn return $ PRunElab fc tm (syn_namespace syn) <?> "new-style tactics expression" | Parses a disambiguation expression Disamb : : = ' with ' NameList ; Disamb ::= 'with' NameList Expr ; -} disamb :: SyntaxInfo -> IdrisParser PTerm disamb syn = do keyword "with" ns <- P.sepBy1 name (lchar ',') tm <- expr' syn return (PDisamb (map tons ns) tm) <?> "namespace disambiguation expression" where tons (NS n s) = txt (show n) : s tons n = [txt (show n)] | Parses a no implicits expression @ : : = ' % ' ' noImplicits ' SimpleExpr ; @ @ NoImplicits ::= '%' 'noImplicits' SimpleExpr ; @ -} noImplicits :: SyntaxInfo -> IdrisParser PTerm noImplicits syn = do P.try (lchar '%' *> reserved "noImplicits") tm <- simpleExpr syn return (PNoImplicits tm) <?> "no implicits expression" | Parses a function application expression @ App : : = ' mkForeign ' Arg Arg * | MatchApp | SimpleExpr Arg * ; MatchApp : : = SimpleExpr ' < = = ' ; @ @ App ::= 'mkForeign' Arg Arg* | MatchApp | SimpleExpr Arg* ; MatchApp ::= SimpleExpr '<==' FnName ; @ -} app :: SyntaxInfo -> IdrisParser PTerm app syn = (appExtent $ do f <- simpleExpr syn (do P.try $ reservedOp "<==" ff <- fnName return (\fc -> (PLet fc RigW (sMN 0 "match") NoFC f (PMatchApp fc ff) (PRef fc [] (sMN 0 "match")))) <?> "matching application expression") <|> (do args <- many (do notEndApp; arg syn) wargs <- if withAppAllowed syn && not (inPattern syn) then many (do notEndApp; reservedOp "|"; expr' syn) else return [] case args of [] -> return $ \fc -> f _ -> return $ \fc -> (withApp fc (flattenFromInt fc f args) wargs))) <?> "function application" where -- bit of a hack to deal with the situation where we're applying a -- literal to an argument, which we may want for obscure applications of fromInteger , and this will help disambiguate better . -- We know, at least, it won't be one of the constants! flattenFromInt fc (PAlternative _ x alts) args | Just i <- getFromInt alts = PApp fc (PRef fc [] (sUN "fromInteger")) (i : args) flattenFromInt fc f args = PApp fc f args withApp fc tm [] = tm withApp fc tm (a : as) = withApp fc (PWithApp fc tm a) as getFromInt ((PApp _ (PRef _ _ n) [a]) : _) | n == sUN "fromInteger" = Just a getFromInt (_ : xs) = getFromInt xs getFromInt _ = Nothing {-| Parses a function argument @ Arg ::= ImplicitArg | ConstraintArg | SimpleExpr ; @ -} arg :: SyntaxInfo -> IdrisParser PArg arg syn = implicitArg syn <|> constraintArg syn <|> do e <- simpleExpr syn return (pexp e) <?> "function argument" | Parses an implicit function argument @ ImplicitArg : : = ' { ' Name ( ' = ' ) ? ' } ' ; @ @ ImplicitArg ::= '{' Name ('=' Expr)? '}' ; @ -} implicitArg :: SyntaxInfo -> IdrisParser PArg implicitArg syn = do lchar '{' (n, nfc) <- withExtent name v <- P.option (PRef nfc [nfc] n) (do lchar '=' expr syn) lchar '}' return (pimp n v True) <?> "implicit function argument" | Parses a constraint argument ( for selecting a named interface implementation ) > ConstraintArg : : = > ' @ { ' ' } ' > ; > ConstraintArg ::= > '@{' Expr '}' > ; -} constraintArg :: SyntaxInfo -> IdrisParser PArg constraintArg syn = do symbol "@{" e <- expr syn symbol "}" return (pconst e) <?> "constraint argument" | Parses a quasiquote expression ( for building reflected terms using the elaborator ) > Quasiquote : : = ' ` ( ' ' ) ' > Quasiquote ::= '`(' Expr ')' -} quasiquote :: SyntaxInfo -> IdrisParser PTerm quasiquote syn = (highlight AnnQuasiquote $ do highlight AnnKeyword $ symbol "`(" e <- expr syn { syn_in_quasiquote = (syn_in_quasiquote syn) + 1 , inPattern = False } g <- optional $ do highlight AnnKeyword $ symbol ":" expr syn { inPattern = False } -- don't allow antiquotes highlight AnnKeyword $ symbol ")" return $ PQuasiquote e g) <?> "quasiquotation" | Parses an unquoting inside a quasiquotation ( for building reflected terms using the elaborator ) > Unquote : : = ' , ' > Unquote ::= ',' Expr -} unquote :: SyntaxInfo -> IdrisParser PTerm unquote syn = (highlight AnnAntiquote $ do guard (syn_in_quasiquote syn > 0) highlight AnnKeyword $ symbol "~" e <- simpleExpr syn { syn_in_quasiquote = syn_in_quasiquote syn - 1 } return $ PUnquote e) <?> "unquotation" {-| Parses a quotation of a name (for using the elaborator to resolve boring details) > NameQuote ::= '`{' Name '}' -} namequote :: SyntaxInfo -> IdrisParser PTerm namequote syn = highlight AnnQuasiquote ((P.try $ do highlight AnnKeyword $ symbol "`{{" (n, nfc) <- withExtent fnName highlight AnnKeyword $ symbol "}}" return (PQuoteName n False nfc)) <|> (do highlight AnnKeyword $ symbol "`{" (n, nfc) <- withExtent fnName highlight AnnKeyword $ symbol "}" return (PQuoteName n True nfc))) <?> "quoted name" | Parses a record field setter expression @ RecordType : : = ' record ' ' { ' FieldTypeList ' } ' ; @ @ FieldTypeList : : = FieldType | FieldType ' , ' FieldTypeList ; @ @ FieldType : : = FnName ' = ' ; @ @ RecordType ::= 'record' '{' FieldTypeList '}'; @ @ FieldTypeList ::= FieldType | FieldType ',' FieldTypeList ; @ @ FieldType ::= FnName '=' Expr ; @ -} data SetOrUpdate = FieldSet PTerm | FieldUpdate PTerm recordType :: SyntaxInfo -> IdrisParser PTerm recordType syn = do ((fgs, rec), fc) <- withExtent $ do keyword "record" lchar '{' fgs <- fieldGetOrSet lchar '}' rec <- optional (do notEndApp; simpleExpr syn) return (fgs, rec) case fgs of Left fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (applyAll fc fields (PRef fc [] (sMN 0 "fldx")))) Just v -> return (applyAll fc fields v) Right fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (getAll fc (reverse fields) (PRef fc [] (sMN 0 "fldx")))) Just v -> return (getAll fc (reverse fields) v) <?> "record setting expression" where fieldSet :: IdrisParser ([Name], SetOrUpdate) fieldSet = do ns <- fieldGet (do lchar '=' e <- expr syn return (ns, FieldSet e)) <|> do symbol "$=" e <- expr syn return (ns, FieldUpdate e) <?> "field setter" fieldGet :: IdrisParser [Name] fieldGet = P.sepBy1 fnName (symbol "->") fieldGetOrSet :: IdrisParser (Either [([Name], SetOrUpdate)] [Name]) fieldGetOrSet = P.try (Left <$> P.sepBy1 fieldSet (lchar ',')) <|> do f <- fieldGet return (Right f) applyAll :: FC -> [([Name], SetOrUpdate)] -> PTerm -> PTerm applyAll fc [] x = x applyAll fc ((ns, e) : es) x = applyAll fc es (doUpdate fc ns e x) doUpdate fc ns (FieldUpdate e) get = let get' = getAll fc (reverse ns) get in doUpdate fc ns (FieldSet (PApp fc e [pexp get'])) get doUpdate fc [n] (FieldSet e) get = PApp fc (PRef fc [] (mkType n)) [pexp e, pexp get] doUpdate fc (n : ns) e get = PApp fc (PRef fc [] (mkType n)) [pexp (doUpdate fc ns e (PApp fc (PRef fc [] n) [pexp get])), pexp get] getAll :: FC -> [Name] -> PTerm -> PTerm getAll fc [n] e = PApp fc (PRef fc [] n) [pexp e] getAll fc (n:ns) e = PApp fc (PRef fc [] n) [pexp (getAll fc ns e)] -- | Creates setters for record types on necessary functions mkType :: Name -> Name mkType (UN n) = sUN ("set_" ++ str n) mkType (MN 0 n) = sMN 0 ("set_" ++ str n) mkType (NS n s) = NS (mkType n) s | Parses a type signature @ TypeSig : : = ' : ' ; @ @ TypeExpr : : = ConstraintList ? ; @ @ TypeSig ::= ':' Expr ; @ @ TypeExpr ::= ConstraintList? Expr; @ -} typeExpr :: SyntaxInfo -> IdrisParser PTerm typeExpr syn = do cs <- if implicitAllowed syn then constraintList syn else return [] sc <- expr (allowConstr syn) return (bindList (\r -> PPi (constraint { pcount = r })) cs sc) <?> "type signature" | Parses a lambda expression @ Lambda : : = ' \\ ' TypeOptDeclList LambdaTail | ' \\ ' SimpleExprList LambdaTail ; @ @ SimpleExprList : : = SimpleExpr | SimpleExpr ' , ' SimpleExprList ; @ @ LambdaTail : : = Impossible | ' = > ' Expr @ @ Lambda ::= '\\' TypeOptDeclList LambdaTail | '\\' SimpleExprList LambdaTail ; @ @ SimpleExprList ::= SimpleExpr | SimpleExpr ',' SimpleExprList ; @ @ LambdaTail ::= Impossible | '=>' Expr @ -} lambda :: SyntaxInfo -> IdrisParser PTerm lambda syn = do lchar '\\' <?> "lambda expression" ((do xt <- P.try $ tyOptDeclList (disallowImp syn) (sc, fc) <- withExtent lambdaTail return (bindList (\r -> PLam fc) xt sc)) <|> (do ps <- P.sepBy (do (e, fc) <- withExtent $ simpleExpr (disallowImp (syn { inPattern = True })) return (fc, e)) (lchar ',') sc <- lambdaTail return (pmList (zip [0..] ps) sc))) <?> "lambda expression" where pmList :: [(Int, (FC, PTerm))] -> PTerm -> PTerm pmList [] sc = sc pmList ((i, (fc, x)) : xs) sc = PLam fc (sMN i "lamp") NoFC Placeholder (PCase fc (PRef fc [] (sMN i "lamp")) [(x, pmList xs sc)]) lambdaTail :: IdrisParser PTerm lambdaTail = impossible <|> symbol "=>" *> expr syn | Parses a term rewrite expression @ RewriteTerm : : = ' rewrite ( ' = = > ' ) ? ' in ' ; @ @ RewriteTerm ::= 'rewrite' Expr ('==>' Expr)? 'in' Expr ; @ -} rewriteTerm :: SyntaxInfo -> IdrisParser PTerm rewriteTerm syn = do keyword "rewrite" (prf, fc) <- withExtent $ expr syn giving <- optional (do symbol "==>"; expr' syn) using <- optional (do reserved "using" n <- name return n) keyword "in"; sc <- expr syn return (PRewrite fc using prf sc giving) <?> "term rewrite expression" | Parse rig count for linear types rigCount :: Parsing m => m RigCount rigCount = P.option RigW $ do lchar '1'; return Rig1 <|> do lchar '0'; return Rig0 |Parses a let binding @ Let : : = ' let ' Name ' ? ' = ' ' in ' Expr | ' let ' ' ' = ' ' ' in ' ' : : = ' : ' ' ; @ @ Let ::= 'let' Name TypeSig'? '=' Expr 'in' Expr | 'let' Expr' '=' Expr' 'in' Expr TypeSig' ::= ':' Expr' ; @ -} let_ :: SyntaxInfo -> IdrisParser PTerm let_ syn = P.try (do keyword "let" ls <- indentedBlock (let_binding syn) keyword "in"; sc <- expr syn return (buildLets ls sc)) <?> "let binding" where buildLets [] sc = sc buildLets ((fc, rc, PRef nfc _ n, ty, v, []) : ls) sc = PLet fc rc n nfc ty v (buildLets ls sc) buildLets ((fc, _, pat, ty, v, alts) : ls) sc = PCase fc v ((pat, buildLets ls sc) : alts) let_binding syn = do rc <- rigCount (pat, fc) <- withExtent $ expr' (syn { inPattern = True }) ty <- P.option Placeholder (do lchar ':'; expr' syn) lchar '=' v <- expr (syn { withAppAllowed = isVar pat }) ts <- P.option [] (do lchar '|' P.sepBy1 (do_alt syn) (lchar '|')) return (fc,rc,pat,ty,v,ts) where isVar (PRef _ _ _) = True isVar _ = False | Parses a conditional expression @ If : : = ' if ' ' then ' ' else ' @ @ If ::= 'if' Expr 'then' Expr 'else' Expr @ -} if_ :: SyntaxInfo -> IdrisParser PTerm if_ syn = (do keyword "if" (c, fc) <- withExtent $ expr syn keyword "then" t <- expr syn keyword "else" f <- expr syn return (PIfThenElse fc c t f)) <?> "conditional expression" | Parses a quote goal @ QuoteGoal : : = ' quoteGoal ' Name ' by ' ' in ' ; @ @ QuoteGoal ::= 'quoteGoal' Name 'by' Expr 'in' Expr ; @ -} quoteGoal :: SyntaxInfo -> IdrisParser PTerm quoteGoal syn = do keyword "quoteGoal"; n <- name; keyword "by" r <- expr syn keyword "in" (sc, fc) <- withExtent $ expr syn return (PGoal fc r n sc) <?> "quote goal expression" | Parses a dependent type signature @ Pi : : = PiOpts Static ? Pi ' @ @ Pi ' : : = OpExpr ( ' - > ' Pi ) ? | ' ( ' TypeDeclList ' ) ' ' - > ' Pi | ' { ' TypeDeclList ' } ' ' - > ' Pi | ' { ' ' auto ' TypeDeclList ' } ' ' - > ' Pi | ' { ' ' default ' SimpleExpr TypeDeclList ' } ' ' - > ' Pi ; @ @ Pi ::= PiOpts Static? Pi' @ @ Pi' ::= OpExpr ('->' Pi)? | '(' TypeDeclList ')' '->' Pi | '{' TypeDeclList '}' '->' Pi | '{' 'auto' TypeDeclList '}' '->' Pi | '{' 'default' SimpleExpr TypeDeclList '}' '->' Pi ; @ -} bindsymbol opts st syn = do symbol "->" return (Exp opts st False RigW) explicitPi opts st syn = do xt <- P.try (lchar '(' *> typeDeclList syn <* lchar ')') binder <- bindsymbol opts st syn sc <- expr (allowConstr syn) return (bindList (\r -> PPi (binder { pcount = r })) xt sc) autoImplicit opts st syn = do keyword "auto" when (st == Static) $ fail "auto implicits can not be static" xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr (allowConstr syn) return (bindList (\r -> PPi (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]) r)) xt sc) defaultImplicit opts st syn = do keyword "default" when (st == Static) $ fail "default implicits can not be static" ist <- get script' <- simpleExpr syn let script = debindApp syn . desugar syn ist $ script' xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr (allowConstr syn) return (bindList (\r -> PPi (TacImp [] Dynamic script r)) xt sc) normalImplicit opts st syn = do xt <- typeDeclList syn <* lchar '}' symbol "->" cs <- constraintList syn sc <- expr syn let (im,cl) = if implicitAllowed syn then (Imp opts st False (Just (Impl False True False)) True RigW, constraint) else (Imp opts st False (Just (Impl False False False)) True RigW, Imp opts st False (Just (Impl True False False)) True RigW) return (bindList (\r -> PPi (im { pcount = r })) xt (bindList (\r -> PPi (cl { pcount = r })) cs sc)) constraintPi opts st syn = do cs <- constraintList1 syn sc <- expr syn if implicitAllowed syn then return (bindList (\r -> PPi constraint { pcount = r }) cs sc) else return (bindList (\r -> PPi (Imp opts st False (Just (Impl True False False)) True r)) cs sc) implicitPi opts st syn = autoImplicit opts st syn <|> defaultImplicit opts st syn <|> normalImplicit opts st syn unboundPi opts st syn = do x <- opExpr syn (do binder <- bindsymbol opts st syn sc <- expr syn return (PPi binder (sUN "__pi_arg") NoFC x sc)) <|> return x -- This is used when we need to disambiguate from a constraint list unboundPiNoConstraint opts st syn = do x <- opExpr syn (do binder <- bindsymbol opts st syn sc <- expr syn P.notFollowedBy $ reservedOp "=>" return (PPi binder (sUN "__pi_arg") NoFC x sc)) <|> do P.notFollowedBy $ reservedOp "=>" return x pi :: SyntaxInfo -> IdrisParser PTerm pi syn = do opts <- piOpts syn st <- static explicitPi opts st syn <|> P.try (do lchar '{'; implicitPi opts st syn) <|> if constraintAllowed syn then P.try (unboundPiNoConstraint opts st syn) <|> constraintPi opts st syn else unboundPi opts st syn <?> "dependent type signature" {- | Parses Possible Options for Pi Expressions @ PiOpts ::= '.'? @ -} piOpts :: SyntaxInfo -> IdrisParser [ArgOpt] piOpts syn | implicitAllowed syn = lchar '.' *> return [InaccessibleArg] <|> return [] piOpts syn = return [] | Parses a type constraint list @ ConstraintList : : = ' ( ' Expr_List ' ) ' ' = > ' | Expr ' = > ' ; @ @ ConstraintList ::= '(' Expr_List ')' '=>' | Expr '=>' ; @ -} constraintList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] constraintList syn = P.try (constraintList1 syn) <|> return [] constraintList1 :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] constraintList1 syn = P.try (do lchar '(' tys <- P.sepBy1 nexpr (lchar ',') lchar ')' reservedOp "=>" return tys) <|> P.try (do t <- opExpr (disallowImp syn) reservedOp "=>" return [(RigW, defname, NoFC, t)]) <?> "type constraint list" where nexpr = P.try (do (n, fc) <- withExtent name; lchar ':' e <- expr (disallowImp syn) return (RigW, n, fc, e)) <|> do e <- expr (disallowImp syn) return (RigW, defname, NoFC, e) defname = sMN 0 "constraint" | Parses a type declaration list @ TypeDeclList : : = FunctionSignatureList | NameList TypeSig ; @ @ FunctionSignatureList : : = Name TypeSig | Name TypeSig ' , ' FunctionSignatureList ; @ @ TypeDeclList ::= FunctionSignatureList | NameList TypeSig ; @ @ FunctionSignatureList ::= Name TypeSig | Name TypeSig ',' FunctionSignatureList ; @ -} typeDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] typeDeclList syn = P.try (P.sepBy1 (do rig <- rigCount (x, xfc) <- withExtent fnName lchar ':' t <- typeExpr (disallowImp syn) return (rig, x, xfc, t)) (lchar ',')) <|> do ns <- P.sepBy1 (withExtent name) (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\(x, xfc) -> (RigW, x, xfc, t)) ns) <?> "type declaration list" | Parses a type declaration list with optional parameters @ TypeOptDeclList : : = NameOrPlaceholder ? | NameOrPlaceholder ? ' , ' TypeOptDeclList ; @ @ NameOrPlaceHolder : : = Name | ' _ ' ; @ @ TypeOptDeclList ::= NameOrPlaceholder TypeSig? | NameOrPlaceholder TypeSig? ',' TypeOptDeclList ; @ @ NameOrPlaceHolder ::= Name | '_'; @ -} tyOptDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] tyOptDeclList syn = P.sepBy1 (do (x, fc) <- withExtent nameOrPlaceholder t <- P.option Placeholder (do lchar ':' expr syn) return (RigW, x, fc, t)) (lchar ',') <?> "type declaration list" where nameOrPlaceholder :: IdrisParser Name nameOrPlaceholder = fnName <|> sMN 0 "underscore" <$ reservedOp "_" <?> "name or placeholder" | Parses a list literal expression e.g. [ 1,2,3 ] or a comprehension [ ( x , y ) | x < - xs , y < - ys ] @ ListExpr : : = ' [ ' ' ] ' | ' [ ' ' | ' DoList ' ] ' | ' [ ' ExprList ' ] ' ; @ @ DoList : : = Do | Do ' , ' DoList ; @ @ ExprList : : = Expr | Expr ' , ' ExprList ; @ @ ListExpr ::= '[' ']' | '[' Expr '|' DoList ']' | '[' ExprList ']' ; @ @ DoList ::= Do | Do ',' DoList ; @ @ ExprList ::= Expr | Expr ',' ExprList ; @ -} listExpr :: SyntaxInfo -> IdrisParser PTerm listExpr syn = do (FC f (l, c) _) <- extent (lchar '[') (do (FC _ _ (l', c')) <- extent (lchar ']') <?> "end of list expression" return (mkNil (FC f (l, c) (l', c')))) <|> (do (x, fc) <- withExtent (expr (syn { withAppAllowed = False })) <?> "expression" (do P.try (lchar '|') <?> "list comprehension" qs <- P.sepBy1 (do_ syn) (lchar ',') lchar ']' return (PDoBlock (map addGuard qs ++ [DoExp fc (PApp fc (PRef fc [] (sUN "pure")) [pexp x])]))) <|> (do xs <- many (do commaFC <- extent (lchar ',') <?> "list element" elt <- expr syn return (elt, commaFC)) rbrackFC <- extent (lchar ']') <?> "end of list expression" return (mkList fc rbrackFC ((x, (FC f (l, c) (l, c+1))) : xs)))) <?> "list expression" where mkNil :: FC -> PTerm mkNil fc = PRef fc [fc] (sUN "Nil") mkList :: FC -> FC -> [(PTerm, FC)] -> PTerm mkList errFC nilFC [] = PRef nilFC [nilFC] (sUN "Nil") mkList errFC nilFC ((x, fc) : xs) = PApp errFC (PRef fc [fc] (sUN "::")) [pexp x, pexp (mkList errFC nilFC xs)] addGuard :: PDo -> PDo addGuard (DoExp fc e) = DoExp fc (PApp fc (PRef fc [] (sUN "guard")) [pexp e]) addGuard x = x | Parses a do - block @ Do ' : : = Do KeepTerminator ; @ @ : : = ' do ' OpenBlock Do'+ CloseBlock ; @ @ Do' ::= Do KeepTerminator; @ @ DoBlock ::= 'do' OpenBlock Do'+ CloseBlock ; @ -} doBlock :: SyntaxInfo -> IdrisParser PTerm doBlock syn = do keyword "do" PDoBlock <$> indentedBlock1 (do_ syn) <?> "do block" | Parses an expression inside a do block @ Do : : = ' let ' Name ' ? ' = ' let ' ' ' = ' rewrite | Name ' < - ' Expr | Expr ' ' < - ' Expr | Expr ; @ @ Do ::= 'let' Name TypeSig'? '=' Expr | 'let' Expr' '=' Expr | 'rewrite Expr | Name '<-' Expr | Expr' '<-' Expr | Expr ; @ -} do_ :: SyntaxInfo -> IdrisParser PDo do_ syn = P.try (do keyword "let" (i, ifc) <- withExtent name ty' <- P.optional (do lchar ':' expr' syn) reservedOp "=" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) -- If there is an explicit type, this can’t be a pattern-matching let, so do not parse alternatives P.option (DoLet fc RigW i ifc (fromMaybe Placeholder ty') e) (do lchar '|' when (isJust ty') $ fail "a pattern-matching let may not have an explicit type annotation" ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoLetP fc (PRef ifc [ifc] i) e ts))) <|> P.try (do keyword "let" i <- expr' syn reservedOp "=" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) P.option (DoLetP fc i e []) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoLetP fc i e ts))) <|> P.try (do (sc, fc) <- withExtent (keyword "rewrite" *> expr syn) return (DoRewrite fc sc)) <|> P.try (do (i, ifc) <- withExtent name symbol "<-" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }); P.option (DoBind fc i ifc e) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoBindP fc (PRef ifc [ifc] i) e ts))) <|> P.try (do i <- expr' syn symbol "<-" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }); P.option (DoBindP fc i e []) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoBindP fc i e ts))) <|> do (e, fc) <- withExtent $ expr syn return (DoExp fc e) <?> "do block expression" do_alt syn = do l <- expr' syn P.option (Placeholder, l) (do symbol "=>" r <- expr' syn return (l, r)) | Parses an expression in idiom brackets @ Idiom : : = ' [ | ' ' | ] ' ; @ @ Idiom ::= '[|' Expr '|]'; @ -} idiom :: SyntaxInfo -> IdrisParser PTerm idiom syn = do symbol "[|" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) symbol "|]" return (PIdiom fc e) <?> "expression in idiom brackets" |Parses a constant or literal expression @ Constant : : = ' Integer ' | ' Int ' | ' ' | ' Double ' | ' String ' | ' Bits8 ' | ' Bits16 ' | ' Bits32 ' | ' Bits64 ' | Float_t | | VerbatimString_t | String_t | ; @ @ Constant ::= 'Integer' | 'Int' | 'Char' | 'Double' | 'String' | 'Bits8' | 'Bits16' | 'Bits32' | 'Bits64' | Float_t | Natural_t | VerbatimString_t | String_t | Char_t ; @ -} constants :: [(String, Idris.Core.TT.Const)] constants = [ ("Integer", AType (ATInt ITBig)) , ("Int", AType (ATInt ITNative)) , ("Char", AType (ATInt ITChar)) , ("Double", AType ATFloat) , ("String", StrType) , ("prim__WorldType", WorldType) , ("prim__TheWorld", TheWorld) , ("Bits8", AType (ATInt (ITFixed IT8))) , ("Bits16", AType (ATInt (ITFixed IT16))) , ("Bits32", AType (ATInt (ITFixed IT32))) , ("Bits64", AType (ATInt (ITFixed IT64))) ] -- | Parse a constant and its source span constant :: Parsing m => m Idris.Core.TT.Const constant = P.choice [ ty <$ reserved name | (name, ty) <- constants ] <|> P.try (Fl <$> float) <|> BI <$> natural <|> Str <$> verbatimStringLiteral <|> Str <$> stringLiteral <|> P.try (Ch <$> charLiteral) --Currently ambigous with symbols <?> "constant or literal" {- | Parses a verbatim multi-line string literal (triple-quoted) @ VerbatimString_t ::= '\"\"\"' ~'\"\"\"' '\"'* '\"\"\"' ; @ -} verbatimStringLiteral :: Parsing m => m String verbatimStringLiteral = token $ do P.try $ string "\"\"\"" str <- P.manyTill P.anySingle $ P.try (string "\"\"\"") moreQuotes <- P.many $ P.char '"' return $ str ++ moreQuotes {- | Parses a static modifier @ Static ::= '%static' ; @ -} static :: IdrisParser Static static = Static <$ reserved "%static" <|> return Dynamic <?> "static modifier" | Parses a tactic script @ Tactic : : = ' intro ' NameList ? | ' intros ' | ' refine ' Name Imp+ | ' mrefine ' Name | ' rewrite ' Expr | ' induction ' Expr | ' equiv ' Expr | ' let ' Name ' : ' ' ' = ' Expr | ' let ' Name ' = ' Expr | ' focus ' Name | ' exact ' Expr | ' applyTactic ' Expr | ' reflect ' Expr | ' fill ' Expr | ' try ' Tactic ' | ' Tactic | ' { ' TacticSeq ' } ' | ' compute ' | ' trivial ' | ' solve ' | ' attack ' | ' state ' | ' term ' | ' undo ' | ' qed ' | ' abandon ' | ' : ' ' q ' ; Imp : : = ' ? ' | ' _ ' ; TacticSeq : : = Tactic ' ; ' Tactic | Tactic ' ; ' TacticSeq ; @ @ Tactic ::= 'intro' NameList? | 'intros' | 'refine' Name Imp+ | 'mrefine' Name | 'rewrite' Expr | 'induction' Expr | 'equiv' Expr | 'let' Name ':' Expr' '=' Expr | 'let' Name '=' Expr | 'focus' Name | 'exact' Expr | 'applyTactic' Expr | 'reflect' Expr | 'fill' Expr | 'try' Tactic '|' Tactic | '{' TacticSeq '}' | 'compute' | 'trivial' | 'solve' | 'attack' | 'state' | 'term' | 'undo' | 'qed' | 'abandon' | ':' 'q' ; Imp ::= '?' | '_'; TacticSeq ::= Tactic ';' Tactic | Tactic ';' TacticSeq ; @ -} -- | A specification of the arguments that tactics can take data TacticArg = NameTArg -- ^ Names: n1, n2, n3, ... n | ExprTArg | AltsTArg | StringLitTArg The FIXMEs are Issue # 1766 in the issue tracker . -- -lang/Idris-dev/issues/1766 -- | A list of available tactics and their argument requirements tactics :: [([String], Maybe TacticArg, SyntaxInfo -> IdrisParser PTactic)] tactics = FIXME syntax for intro ( fresh name ) do ns <- P.sepBy (spaced name) (lchar ','); return $ Intro ns) , noArgs ["intros"] Intros , noArgs ["unfocus"] Unfocus , (["refine"], Just ExprTArg, const $ do n <- spaced fnName imps <- many imp return $ Refine n imps) , (["claim"], Nothing, \syn -> do n <- indentGt *> name goal <- indentGt *> expr syn return $ Claim n goal) , (["mrefine"], Just ExprTArg, const $ do n <- spaced fnName return $ MatchRefine n) , expressionTactic ["rewrite"] Rewrite , expressionTactic ["equiv"] Equiv FIXME syntax for let do n <- (indentGt *> name) (do indentGt *> lchar ':' ty <- indentGt *> expr' syn indentGt *> lchar '=' t <- indentGt *> expr syn i <- get return $ LetTacTy n (desugar syn i ty) (desugar syn i t)) <|> (do indentGt *> lchar '=' t <- indentGt *> expr syn i <- get return $ LetTac n (desugar syn i t))) , (["focus"], Just ExprTArg, const $ do n <- spaced name return $ Focus n) , expressionTactic ["exact"] Exact , expressionTactic ["applyTactic"] ApplyTactic , expressionTactic ["byReflection"] ByReflection , expressionTactic ["reflect"] Reflect , expressionTactic ["fill"] Fill , (["try"], Just AltsTArg, \syn -> do t <- spaced (tactic syn) lchar '|' t1 <- spaced (tactic syn) return $ Try t t1) , noArgs ["compute"] Compute , noArgs ["trivial"] Trivial , noArgs ["unify"] DoUnify , (["search"], Nothing, const $ do depth <- P.option 10 natural return (ProofSearch True True (fromInteger depth) Nothing [] [])) , noArgs ["implementation"] TCImplementation , noArgs ["solve"] Solve , noArgs ["attack"] Attack , noArgs ["state", ":state"] ProofState , noArgs ["term", ":term"] ProofTerm , noArgs ["undo", ":undo"] Undo , noArgs ["qed", ":qed"] Qed , noArgs ["abandon", ":q"] Abandon , noArgs ["skip"] Skip , noArgs ["sourceLocation"] SourceFC , expressionTactic [":e", ":eval"] TEval , expressionTactic [":t", ":type"] TCheck , expressionTactic [":search"] TSearch , (["fail"], Just StringLitTArg, const $ do msg <- stringLiteral return $ TFail [Idris.Core.TT.TextPart msg]) , ([":doc"], Just ExprTArg, const $ do whiteSpace doc <- (Right <$> constant) <|> (Left <$> fnName) P.eof return (TDocStr doc)) ] where expressionTactic names tactic = (names, Just ExprTArg, \syn -> do t <- spaced (expr syn) i <- get return $ tactic (desugar syn i t)) noArgs names tactic = (names, Nothing, const (return tactic)) spaced parser = indentGt *> parser imp :: IdrisParser Bool imp = do lchar '?'; return False <|> do lchar '_'; return True tactic :: SyntaxInfo -> IdrisParser PTactic tactic syn = P.choice [ do P.choice (map reserved names); parser syn | (names, _, parser) <- tactics ] <|> do lchar '{' t <- tactic syn; lchar ';'; ts <- P.sepBy1 (tactic syn) (lchar ';') lchar '}' return $ TSeq t (mergeSeq ts) <|> ((lchar ':' >> empty) <?> "prover command") <?> "tactic" where mergeSeq :: [PTactic] -> PTactic mergeSeq [t] = t mergeSeq (t:ts) = TSeq t (mergeSeq ts) -- | Parses a tactic as a whole fullTactic :: SyntaxInfo -> IdrisParser PTactic fullTactic syn = do t <- tactic syn P.eof return t
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/idris-1.3.3/src/Idris/Parser/Expr.hs
haskell
| Allow implicit type declarations | Disallow implicit type declarations | Implicits hare are scoped rather than top level | Allow scoped constraint arguments | Parses an expression @ Expr ::= Pi @ Expression Parser with Operators based on Expr' | Parses a user-defined expression Fix non-highlighting FCs by approximating with the span of the syntax application Fix highlighting FCs by making them useless, to avoid spurious highlights | Parses a simple user-defined expression | Tries to parse a user-defined expression given a list of syntactic extensions can never be [] nondeterministic. flatten application PConstSugar probably can't contain anything substitutable, but it's hard to track handle all the ones with Names explicitly, then use fmap for the rest with PTerms | Parses the "impossible" keyword @ Impossible ::= 'impossible' @ External (User-defined) Simple Expression | Parses the rest of a dependent pair after '(' or '(Expr **' | Parse the contents of parentheses, after an expression has been parsed. bit of a hack here. If the integer doesn't fit in an Int, treat it as a name suggests, rather than Int | Finds optimal type for integer constant wrap in original span for highlighting | Parses an alternative expression @ Alt ::= '(|' Expr_List '|)'; Expr_List ::= Expr' | Expr' ',' Expr_List ; @ | Parses a possibly hidden simple expression @ HSimpleExpr ::= '.' SimpleExpr | SimpleExpr ; @ bit of a hack to deal with the situation where we're applying a literal to an argument, which we may want for obscure applications We know, at least, it won't be one of the constants! | Parses a function argument @ Arg ::= ImplicitArg | ConstraintArg | SimpleExpr ; @ don't allow antiquotes | Parses a quotation of a name (for using the elaborator to resolve boring details) > NameQuote ::= '`{' Name '}' | Creates setters for record types on necessary functions This is used when we need to disambiguate from a constraint list | Parses Possible Options for Pi Expressions @ PiOpts ::= '.'? @ If there is an explicit type, this can’t be a pattern-matching let, so do not parse alternatives | Parse a constant and its source span Currently ambigous with symbols | Parses a verbatim multi-line string literal (triple-quoted) @ VerbatimString_t ::= '\"\"\"' ~'\"\"\"' '\"'* '\"\"\"' ; @ | Parses a static modifier @ Static ::= '%static' ; @ | A specification of the arguments that tactics can take ^ Names: n1, n2, n3, ... n -lang/Idris-dev/issues/1766 | A list of available tactics and their argument requirements | Parses a tactic as a whole
| Module : . . Expr Description : Parse Expressions . License : : The Idris Community . Module : Idris.Parser.Expr Description : Parse Expressions. License : BSD3 Maintainer : The Idris Community. -} # LANGUAGE FlexibleContexts , TupleSections # module Idris.Parser.Expr where import Idris.AbsSyntax import Idris.Core.TT import Idris.DSL import Idris.Options import Idris.Parser.Helpers import Idris.Parser.Ops import Prelude hiding (pi) import Control.Applicative import Control.Arrow (left) import Control.Monad import qualified Control.Monad.Combinators.Expr as P import Control.Monad.State.Strict import Data.Function (on) import Data.List import Data.Maybe import Text.Megaparsec ((<?>)) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P allowImp :: SyntaxInfo -> SyntaxInfo allowImp syn = syn { implicitAllowed = True, constraintAllowed = False } disallowImp :: SyntaxInfo -> SyntaxInfo disallowImp = scopedImp scopedImp :: SyntaxInfo -> SyntaxInfo scopedImp syn = syn { implicitAllowed = False, constraintAllowed = False } allowConstr :: SyntaxInfo -> SyntaxInfo allowConstr syn = syn { constraintAllowed = True } | Parses an expression as a whole @ FullExpr : : = ; @ @ FullExpr ::= Expr EOF_t; @ -} fullExpr :: SyntaxInfo -> IdrisParser PTerm fullExpr syn = do x <- expr syn P.eof i <- get return $ debindApp syn (desugar syn i x) tryFullExpr :: SyntaxInfo -> IState -> String -> Either Err PTerm tryFullExpr syn st = left (Msg . show . parseErrorDoc) . runparser (fullExpr syn) st "" expr :: SyntaxInfo -> IdrisParser PTerm expr = pi | Parses an expression with possible operator applied @ OpExpr : : = { - Expression Parser with Operators based on ' @ @ -} opExpr :: SyntaxInfo -> IdrisParser PTerm opExpr syn = do i <- get P.makeExprParser (expr' syn) (table (idris_infixes i)) | Parses either an internally defined expression or a user - defined one @ ' : : = " External ( User - defined ) Syntax " | InternalExpr ; @ a user-defined one @ Expr' ::= "External (User-defined) Syntax" | InternalExpr; @ -} expr' :: SyntaxInfo -> IdrisParser PTerm expr' syn = P.try (externalExpr syn) <|> internalExpr syn <?> "expression" externalExpr :: SyntaxInfo -> IdrisParser PTerm externalExpr syn = do i <- get (expr, outerFC@(FC fn _ _)) <- withExtent $ extensions syn (syntaxRulesList $ syntax_rules i) return (mapPTermFC (fixFC outerFC) (fixFCH fn outerFC) expr) <?> "user-defined expression" fixFC outer inner | inner `fcIn` outer = inner | otherwise = outer fixFCH fn outer inner | inner `fcIn` outer = inner | otherwise = FileFC fn simpleExternalExpr :: SyntaxInfo -> IdrisParser PTerm simpleExternalExpr syn = do i <- get extensions syn (filter isSimple (syntaxRulesList $ syntax_rules i)) where isSimple (Rule (Expr x:xs) _ _) = False isSimple (Rule (SimpleExpr x:xs) _ _) = False isSimple (Rule [Keyword _] _ _) = True isSimple (Rule [Symbol _] _ _) = True isSimple (Rule (_:xs) _ _) = case last xs of Keyword _ -> True Symbol _ -> True _ -> False isSimple _ = False extensions :: SyntaxInfo -> [Syntax] -> IdrisParser PTerm extensions syn rules = extension syn [] (filter isValid rules) <?> "user-defined expression" where isValid :: Syntax -> Bool isValid (Rule _ _ AnySyntax) = True isValid (Rule _ _ PatternSyntax) = inPattern syn isValid (Rule _ _ TermSyntax) = not (inPattern syn) isValid (DeclRule _ _) = False ^ the FC is for highlighting information deriving Show extension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser PTerm extension syn ns rules = P.choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs -> Rule (symb:_) _ _ -> P.try $ do n <- extensionSymbol symb extension syn (n : ns) [Rule ss t ctx | (Rule (_:ss) t ctx) <- rs] If we have more than one Rule in this bucket , our grammar is Rule [] ptm _ -> return (flatten (updateSynMatch (mapMaybe id ns) ptm)) where ruleGroup [] [] = True ruleGroup (s1:_) (s2:_) = s1 == s2 ruleGroup _ _ = False extensionSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch)) extensionSymbol (Keyword n) = Nothing <$ keyword (show n) extensionSymbol (Expr n) = do tm <- expr syn return $ Just (n, SynTm tm) extensionSymbol (SimpleExpr n) = do tm <- simpleExpr syn return $ Just (n, SynTm tm) extensionSymbol (Binding n) = do (b, fc) <- withExtent name return $ Just (n, SynBind fc b) extensionSymbol (Symbol s) = Nothing <$ highlight AnnKeyword (symbol s) flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs)) flatten t = t updateSynMatch = update where updateB :: [(Name, SynMatch)] -> (Name, FC) -> (Name, FC) updateB ns (n, fc) = case lookup n ns of Just (SynBind tfc t) -> (t, tfc) _ -> (n, fc) update :: [(Name, SynMatch)] -> PTerm -> PTerm update ns (PRef fc hls n) = case lookup n ns of Just (SynTm t) -> t _ -> PRef fc hls n update ns (PPatvar fc n) = uncurry (flip PPatvar) $ updateB ns (n, fc) update ns (PLam fc n nfc ty sc) = let (n', nfc') = updateB ns (n, nfc) in PLam fc n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PPi p n fc ty sc) = let (n', nfc') = updateB ns (n, fc) in PPi (updTacImp ns p) n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PLet fc rc n nfc ty val sc) = let (n', nfc') = updateB ns (n, nfc) in PLet fc rc n' nfc' (update ns ty) (update ns val) (update (dropn n ns) sc) update ns (PApp fc t args) = PApp fc (update ns t) (map (fmap (update ns)) args) update ns (PAppBind fc t args) = PAppBind fc (update ns t) (map (fmap (update ns)) args) update ns (PMatchApp fc n) = let (n', nfc') = updateB ns (n, fc) in PMatchApp nfc' n' update ns (PIfThenElse fc c t f) = PIfThenElse fc (update ns c) (update ns t) (update ns f) update ns (PCase fc c opts) = PCase fc (update ns c) (map (pmap (update ns)) opts) update ns (PRewrite fc by eq tm mty) = PRewrite fc by (update ns eq) (update ns tm) (fmap (update ns) mty) update ns (PPair fc hls p l r) = PPair fc hls p (update ns l) (update ns r) update ns (PDPair fc hls p l t r) = PDPair fc hls p (update ns l) (update ns t) (update ns r) update ns (PAs fc n t) = PAs fc (fst $ updateB ns (n, NoFC)) (update ns t) update ns (PAlternative ms a as) = PAlternative ms a (map (update ns) as) update ns (PHidden t) = PHidden (update ns t) update ns (PGoal fc r n sc) = PGoal fc (update ns r) n (update ns sc) update ns (PDoBlock ds) = PDoBlock $ map (upd ns) ds where upd :: [(Name, SynMatch)] -> PDo -> PDo upd ns (DoExp fc t) = DoExp fc (update ns t) upd ns (DoBind fc n nfc t) = DoBind fc n nfc (update ns t) upd ns (DoLet fc rc n nfc ty t) = DoLet fc rc n nfc (update ns ty) (update ns t) upd ns (DoBindP fc i t ts) = DoBindP fc (update ns i) (update ns t) (map (\(l,r) -> (update ns l, update ns r)) ts) upd ns (DoLetP fc i t ts) = DoLetP fc (update ns i) (update ns t) (map (\(l,r) -> (update ns l, update ns r)) ts) upd ns (DoRewrite fc h) = DoRewrite fc (update ns h) update ns (PIdiom fc t) = PIdiom fc $ update ns t update ns (PMetavar fc n) = uncurry (flip PMetavar) $ updateB ns (n, fc) update ns (PProof tacs) = PProof $ map (updTactic ns) tacs update ns (PTactics tacs) = PTactics $ map (updTactic ns) tacs update ns (PDisamb nsps t) = PDisamb nsps $ update ns t update ns (PUnifyLog t) = PUnifyLog $ update ns t update ns (PNoImplicits t) = PNoImplicits $ update ns t update ns (PQuasiquote tm mty) = PQuasiquote (update ns tm) (fmap (update ns) mty) update ns (PUnquote t) = PUnquote $ update ns t update ns (PQuoteName n res fc) = let (n', fc') = (updateB ns (n, fc)) in PQuoteName n' res fc' update ns (PRunElab fc t nsp) = PRunElab fc (update ns t) nsp update ns (PConstSugar fc t) = PConstSugar fc $ update ns t update ns t = t updTactic :: [(Name, SynMatch)] -> PTactic -> PTactic updTactic ns (Intro ns') = Intro $ map (fst . updateB ns . (, NoFC)) ns' updTactic ns (Focus n) = Focus . fst $ updateB ns (n, NoFC) updTactic ns (Refine n bs) = Refine (fst $ updateB ns (n, NoFC)) bs updTactic ns (Claim n t) = Claim (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (MatchRefine n) = MatchRefine (fst $ updateB ns (n, NoFC)) updTactic ns (LetTac n t) = LetTac (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (LetTacTy n ty tm) = LetTacTy (fst $ updateB ns (n, NoFC)) (update ns ty) (update ns tm) updTactic ns (ProofSearch rec prover depth top psns hints) = ProofSearch rec prover depth (fmap (fst . updateB ns . (, NoFC)) top) (map (fst . updateB ns . (, NoFC)) psns) (map (fst . updateB ns . (, NoFC)) hints) updTactic ns (Try l r) = Try (updTactic ns l) (updTactic ns r) updTactic ns (TSeq l r) = TSeq (updTactic ns l) (updTactic ns r) updTactic ns (GoalType s tac) = GoalType s $ updTactic ns tac updTactic ns (TDocStr (Left n)) = TDocStr . Left . fst $ updateB ns (n, NoFC) updTactic ns t = fmap (update ns) t updTacImp ns (TacImp o st scr r) = TacImp o st (update ns scr) r updTacImp _ x = x dropn :: Name -> [(Name, a)] -> [(Name, a)] dropn n [] = [] dropn n ((x,t) : xs) | n == x = xs | otherwise = (x,t):dropn n xs | Parses a ( normal ) built - in expression @ InternalExpr : : = UnifyLog | RecordType | SimpleExpr | Lambda | QuoteGoal | Let | If | RewriteTerm | CaseExpr | | App ; @ @ InternalExpr ::= UnifyLog | RecordType | SimpleExpr | Lambda | QuoteGoal | Let | If | RewriteTerm | CaseExpr | DoBlock | App ; @ -} internalExpr :: SyntaxInfo -> IdrisParser PTerm internalExpr syn = unifyLog syn <|> runElab syn <|> disamb syn <|> noImplicits syn <|> recordType syn <|> if_ syn <|> lambda syn <|> quoteGoal syn <|> let_ syn <|> rewriteTerm syn <|> doBlock syn <|> caseExpr syn <|> app syn <?> "expression" impossible :: IdrisParser PTerm impossible = PImpossible <$ keyword "impossible" | Parses a case expression @ : : = ' case ' ' of ' OpenBlock ; @ @ CaseExpr ::= 'case' Expr 'of' OpenBlock CaseOption+ CloseBlock; @ -} caseExpr :: SyntaxInfo -> IdrisParser PTerm caseExpr syn = do keyword "case" (scr, fc) <- withExtent $ expr syn keyword "of" opts <- indentedBlock1 (caseOption syn) return (PCase fc scr opts) <?> "case expression" | Parses a case in a case expression @ CaseOption : : = Expr ( Impossible | ' = > ' Expr ) Terminator ; @ @ CaseOption ::= Expr (Impossible | '=>' Expr) Terminator ; @ -} caseOption :: SyntaxInfo -> IdrisParser (PTerm, PTerm) caseOption syn = do lhs <- expr (disallowImp (syn { inPattern = True })) r <- impossible <|> symbol "=>" *> expr syn return (lhs, r) <?> "case option" warnTacticDeprecation :: FC -> IdrisParser () warnTacticDeprecation fc = parserWarning fc (Just NoOldTacticDeprecationWarnings) (Msg "This style of tactic proof is deprecated. See %runElab for the replacement.") | Parses a proof block @ ProofExpr : : = ' proof ' OpenBlock Tactic ' * CloseBlock ; @ @ ProofExpr ::= 'proof' OpenBlock Tactic'* CloseBlock ; @ -} proofExpr :: SyntaxInfo -> IdrisParser PTerm proofExpr syn = do kw <- extent $ keyword "proof" ts <- indentedBlock1 (tactic syn) warnTacticDeprecation kw return $ PProof ts <?> "proof block" | Parses a tactics block @ TacticsExpr : = ' tactics ' OpenBlock Tactic ' * CloseBlock ; @ @ TacticsExpr := 'tactics' OpenBlock Tactic'* CloseBlock ; @ -} tacticsExpr :: SyntaxInfo -> IdrisParser PTerm tacticsExpr syn = do kw <- extent $ keyword "tactics" ts <- indentedBlock1 (tactic syn) warnTacticDeprecation kw return $ PTactics ts <?> "tactics block" | Parses a simple expression @ SimpleExpr : : = { - External ( User - defined ) Simple Expression @ SimpleExpr ::= | '?' Name | % 'implementation' | 'Refl' ('{' Expr '}')? | ProofExpr | TacticsExpr | FnName | Idiom | List | Alt | Bracketed | Constant | Type | 'Void' | Quasiquote | NameQuote | Unquote | '_' ; @ -} simpleExpr :: SyntaxInfo -> IdrisParser PTerm simpleExpr syn = P.try (simpleExternalExpr syn) <|> do (x, FC f (l, c) end) <- P.try (lchar '?' *> withExtent name) return (PMetavar (FC f (l, c-1) end) x) <|> do lchar '%'; fc <- extent $ reserved "implementation"; return (PResolveTC fc) <|> do lchar '%'; fc <- extent $ reserved "instance" parserWarning fc Nothing $ Msg "The use of %instance is deprecated, use %implementation instead." return (PResolveTC fc) <|> proofExpr syn <|> tacticsExpr syn <|> P.try (do fc <- extent (reserved "Type*"); return $ PUniverse fc AllTypes) <|> do fc <- extent $ reserved "AnyType"; return $ PUniverse fc AllTypes <|> PType <$> extent (reserved "Type") <|> do fc <- extent $ reserved "UniqueType"; return $ PUniverse fc UniqueType <|> do fc <- extent $ reserved "NullType"; return $ PUniverse fc NullType <|> do (c, cfc) <- withExtent constant return (modifyConst syn cfc (PConstant cfc c)) <|> do symbol "'"; (str, fc) <- withExtent name return (PApp fc (PRef fc [] (sUN "Symbol_")) [pexp (PConstant NoFC (Str (show str)))]) <|> do (x, fc) <- withExtent fnName if inPattern syn then P.option (PRef fc [fc] x) (do reservedOp "@" (s, fcIn) <- withExtent $ simpleExpr syn return (PAs fcIn x s)) else return (PRef fc [fc] x) <|> idiom syn <|> listExpr syn <|> alt syn <|> do reservedOp "!" (s, fc) <- withExtent $ simpleExpr syn return (PAppBind fc s []) <|> bracketed (disallowImp syn) <|> quasiquote syn <|> namequote syn <|> unquote syn <|> do lchar '_'; return Placeholder <?> "expression" |Parses an expression in parentheses @ Bracketed : : = ' ( ' Bracketed ' @ @ Bracketed ::= '(' Bracketed' @ -} bracketed :: SyntaxInfo -> IdrisParser PTerm bracketed syn = do (FC fn (sl, sc) _) <- extent (lchar '(') <?> "parenthesized expression" bracketed' (FC fn (sl, sc) (sl, sc+1)) (syn { withAppAllowed = True }) |Parses the rest of an expression in braces @ Bracketed ' : : = ' ) ' | Expr ' ) ' | ExprList ' ) ' | DependentPair ' ) ' | Operator Expr ' ) ' | Expr Operator ' ) ' ; @ @ Bracketed' ::= ')' | Expr ')' | ExprList ')' | DependentPair ')' | Operator Expr ')' | Expr Operator ')' ; @ -} bracketed' :: FC -> SyntaxInfo -> IdrisParser PTerm bracketed' open syn = do fc <- extent (addExtent open *> lchar ')') return $ PTrue fc TypeOrTerm <|> P.try (dependentPair TypeOrTerm [] open syn) <|> P.try (do (opName, fc) <- withExtent operatorName guardNotPrefix opName e <- expr syn lchar ')' return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder (PApp fc (PRef fc [] opName) [pexp (PRef fc [] (sMN 1000 "ARG")), pexp e])) <|> P.try (simpleExpr syn >>= \l -> P.try (do (opName, fc) <- withExtent operatorName lchar ')' return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder (PApp fc (PRef fc [] opName) [pexp l, pexp (PRef fc [] (sMN 1000 "ARG"))])) <|> bracketedExpr syn open l) <|> do l <- expr (allowConstr syn) bracketedExpr (allowConstr syn) open l where justPrefix :: FixDecl -> Maybe Name justPrefix (Fix (PrefixN _) opName) = Just (sUN opName) justPrefix _ = Nothing guardNotPrefix :: Name -> IdrisParser () guardNotPrefix opName = do guard $ opName /= sUN "-" guard $ opName /= sUN "!" ops <- idris_infixes <$> get guard . not . (opName `elem`) . mapMaybe justPrefix $ ops dependentPair :: PunInfo -> [(PTerm, Maybe (FC, PTerm), FC)] -> FC -> SyntaxInfo -> IdrisParser PTerm dependentPair pun prev openFC syn = if null prev then nametypePart <|> namePart else case pun of IsType -> nametypePart <|> namePart <|> exprPart True IsTerm -> exprPart False TypeOrTerm -> nametypePart <|> namePart <|> exprPart False where nametypePart = do (ln, lnfc, colonFC) <- P.try $ do (ln, lnfc) <- withExtent name colonFC <- extent (lchar ':') return (ln, lnfc, colonFC) lty <- expr' syn starsFC <- extent $ reservedOp "**" dependentPair IsType ((PRef lnfc [] ln, Just (colonFC, lty), starsFC):prev) openFC syn namePart = P.try $ do (ln, lnfc) <- withExtent name starsFC <- extent $ reservedOp "**" dependentPair pun ((PRef lnfc [] ln, Nothing, starsFC):prev) openFC syn exprPart isEnd = do e <- expr syn sepFCE <- let stars = (Left <$> extent (reservedOp "**")) ending = (Right <$> extent (lchar ')')) in if isEnd then ending else stars <|> ending case sepFCE of Left starsFC -> dependentPair IsTerm ((e, Nothing, starsFC):prev) openFC syn Right closeFC -> return (mkPDPairs pun openFC closeFC (reverse prev) e) mkPDPairs pun openFC closeFC ((e, cfclty, starsFC):bnds) r = (PDPair openFC ([openFC] ++ maybe [] ((: []) . fst) cfclty ++ [starsFC, closeFC] ++ (=<<) (\(_,cfclty,sfc) -> maybe [] ((: []) . fst) cfclty ++ [sfc]) bnds) pun e (maybe Placeholder snd cfclty) (mergePDPairs pun starsFC bnds r)) mergePDPairs pun starsFC' [] r = r mergePDPairs pun starsFC' ((e, cfclty, starsFC):bnds) r = PDPair starsFC' [] pun e (maybe Placeholder snd cfclty) (mergePDPairs pun starsFC bnds r) bracketedExpr :: SyntaxInfo -> FC -> PTerm -> IdrisParser PTerm bracketedExpr syn openParenFC e = do lchar ')'; return e <|> do exprs <- some (do comma <- extent (lchar ',') r <- expr syn return (r, comma)) closeParenFC <- extent (lchar ')') let hilite = [openParenFC, closeParenFC] ++ map snd exprs return $ PPair openParenFC hilite TypeOrTerm e (mergePairs exprs) <|> do starsFC <- extent $ reservedOp "**" dependentPair IsTerm [(e, Nothing, starsFC)] openParenFC syn <?> "end of bracketed expression" where mergePairs :: [(PTerm, FC)] -> PTerm mergePairs [(t, fc)] = t mergePairs ((t, fc):rs) = PPair fc [] TypeOrTerm t (mergePairs rs) big integer , otherwise try fromInteger and the constants as alternatives . a better solution would be to fix fromInteger to work with Integer , as the modifyConst :: SyntaxInfo -> FC -> PTerm -> PTerm modifyConst syn fc (PConstant inFC (BI x)) | not (inPattern syn) PAlternative [] FirstSuccess (PApp fc (PRef fc [] (sUN "fromInteger")) [pexp (PConstant NoFC (BI (fromInteger x)))] : consts) | otherwise = PConstSugar inFC $ PAlternative [] FirstSuccess consts where consts = [ PConstant inFC (BI x) , PConstant inFC (I (fromInteger x)) , PConstant inFC (B8 (fromInteger x)) , PConstant inFC (B16 (fromInteger x)) , PConstant inFC (B32 (fromInteger x)) , PConstant inFC (B64 (fromInteger x)) ] modifyConst syn fc x = x alt :: SyntaxInfo -> IdrisParser PTerm alt syn = do symbol "(|"; alts <- P.sepBy1 (expr' (syn { withAppAllowed = False })) (lchar ','); symbol "|)" return (PAlternative [] FirstSuccess alts) hsimpleExpr :: SyntaxInfo -> IdrisParser PTerm hsimpleExpr syn = do lchar '.' e <- simpleExpr syn return $ PHidden e <|> simpleExpr syn <?> "expression" | Parses a unification log expression UnifyLog : : = ' % ' ' unifyLog ' SimpleExpr ; UnifyLog ::= '%' 'unifyLog' SimpleExpr ; -} unifyLog :: SyntaxInfo -> IdrisParser PTerm unifyLog syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "unifyLog" PUnifyLog <$> simpleExpr syn <?> "unification log expression" | Parses a new - style tactics expression RunTactics : : = ' % ' ' runElab ' SimpleExpr ; RunTactics ::= '%' 'runElab' SimpleExpr ; -} runElab :: SyntaxInfo -> IdrisParser PTerm runElab syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "runElab" (tm, fc) <- withExtent $ simpleExpr syn return $ PRunElab fc tm (syn_namespace syn) <?> "new-style tactics expression" | Parses a disambiguation expression Disamb : : = ' with ' NameList ; Disamb ::= 'with' NameList Expr ; -} disamb :: SyntaxInfo -> IdrisParser PTerm disamb syn = do keyword "with" ns <- P.sepBy1 name (lchar ',') tm <- expr' syn return (PDisamb (map tons ns) tm) <?> "namespace disambiguation expression" where tons (NS n s) = txt (show n) : s tons n = [txt (show n)] | Parses a no implicits expression @ : : = ' % ' ' noImplicits ' SimpleExpr ; @ @ NoImplicits ::= '%' 'noImplicits' SimpleExpr ; @ -} noImplicits :: SyntaxInfo -> IdrisParser PTerm noImplicits syn = do P.try (lchar '%' *> reserved "noImplicits") tm <- simpleExpr syn return (PNoImplicits tm) <?> "no implicits expression" | Parses a function application expression @ App : : = ' mkForeign ' Arg Arg * | MatchApp | SimpleExpr Arg * ; MatchApp : : = SimpleExpr ' < = = ' ; @ @ App ::= 'mkForeign' Arg Arg* | MatchApp | SimpleExpr Arg* ; MatchApp ::= SimpleExpr '<==' FnName ; @ -} app :: SyntaxInfo -> IdrisParser PTerm app syn = (appExtent $ do f <- simpleExpr syn (do P.try $ reservedOp "<==" ff <- fnName return (\fc -> (PLet fc RigW (sMN 0 "match") NoFC f (PMatchApp fc ff) (PRef fc [] (sMN 0 "match")))) <?> "matching application expression") <|> (do args <- many (do notEndApp; arg syn) wargs <- if withAppAllowed syn && not (inPattern syn) then many (do notEndApp; reservedOp "|"; expr' syn) else return [] case args of [] -> return $ \fc -> f _ -> return $ \fc -> (withApp fc (flattenFromInt fc f args) wargs))) <?> "function application" where of fromInteger , and this will help disambiguate better . flattenFromInt fc (PAlternative _ x alts) args | Just i <- getFromInt alts = PApp fc (PRef fc [] (sUN "fromInteger")) (i : args) flattenFromInt fc f args = PApp fc f args withApp fc tm [] = tm withApp fc tm (a : as) = withApp fc (PWithApp fc tm a) as getFromInt ((PApp _ (PRef _ _ n) [a]) : _) | n == sUN "fromInteger" = Just a getFromInt (_ : xs) = getFromInt xs getFromInt _ = Nothing arg :: SyntaxInfo -> IdrisParser PArg arg syn = implicitArg syn <|> constraintArg syn <|> do e <- simpleExpr syn return (pexp e) <?> "function argument" | Parses an implicit function argument @ ImplicitArg : : = ' { ' Name ( ' = ' ) ? ' } ' ; @ @ ImplicitArg ::= '{' Name ('=' Expr)? '}' ; @ -} implicitArg :: SyntaxInfo -> IdrisParser PArg implicitArg syn = do lchar '{' (n, nfc) <- withExtent name v <- P.option (PRef nfc [nfc] n) (do lchar '=' expr syn) lchar '}' return (pimp n v True) <?> "implicit function argument" | Parses a constraint argument ( for selecting a named interface implementation ) > ConstraintArg : : = > ' @ { ' ' } ' > ; > ConstraintArg ::= > '@{' Expr '}' > ; -} constraintArg :: SyntaxInfo -> IdrisParser PArg constraintArg syn = do symbol "@{" e <- expr syn symbol "}" return (pconst e) <?> "constraint argument" | Parses a quasiquote expression ( for building reflected terms using the elaborator ) > Quasiquote : : = ' ` ( ' ' ) ' > Quasiquote ::= '`(' Expr ')' -} quasiquote :: SyntaxInfo -> IdrisParser PTerm quasiquote syn = (highlight AnnQuasiquote $ do highlight AnnKeyword $ symbol "`(" e <- expr syn { syn_in_quasiquote = (syn_in_quasiquote syn) + 1 , inPattern = False } g <- optional $ do highlight AnnKeyword $ symbol ":" highlight AnnKeyword $ symbol ")" return $ PQuasiquote e g) <?> "quasiquotation" | Parses an unquoting inside a quasiquotation ( for building reflected terms using the elaborator ) > Unquote : : = ' , ' > Unquote ::= ',' Expr -} unquote :: SyntaxInfo -> IdrisParser PTerm unquote syn = (highlight AnnAntiquote $ do guard (syn_in_quasiquote syn > 0) highlight AnnKeyword $ symbol "~" e <- simpleExpr syn { syn_in_quasiquote = syn_in_quasiquote syn - 1 } return $ PUnquote e) <?> "unquotation" namequote :: SyntaxInfo -> IdrisParser PTerm namequote syn = highlight AnnQuasiquote ((P.try $ do highlight AnnKeyword $ symbol "`{{" (n, nfc) <- withExtent fnName highlight AnnKeyword $ symbol "}}" return (PQuoteName n False nfc)) <|> (do highlight AnnKeyword $ symbol "`{" (n, nfc) <- withExtent fnName highlight AnnKeyword $ symbol "}" return (PQuoteName n True nfc))) <?> "quoted name" | Parses a record field setter expression @ RecordType : : = ' record ' ' { ' FieldTypeList ' } ' ; @ @ FieldTypeList : : = FieldType | FieldType ' , ' FieldTypeList ; @ @ FieldType : : = FnName ' = ' ; @ @ RecordType ::= 'record' '{' FieldTypeList '}'; @ @ FieldTypeList ::= FieldType | FieldType ',' FieldTypeList ; @ @ FieldType ::= FnName '=' Expr ; @ -} data SetOrUpdate = FieldSet PTerm | FieldUpdate PTerm recordType :: SyntaxInfo -> IdrisParser PTerm recordType syn = do ((fgs, rec), fc) <- withExtent $ do keyword "record" lchar '{' fgs <- fieldGetOrSet lchar '}' rec <- optional (do notEndApp; simpleExpr syn) return (fgs, rec) case fgs of Left fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (applyAll fc fields (PRef fc [] (sMN 0 "fldx")))) Just v -> return (applyAll fc fields v) Right fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (getAll fc (reverse fields) (PRef fc [] (sMN 0 "fldx")))) Just v -> return (getAll fc (reverse fields) v) <?> "record setting expression" where fieldSet :: IdrisParser ([Name], SetOrUpdate) fieldSet = do ns <- fieldGet (do lchar '=' e <- expr syn return (ns, FieldSet e)) <|> do symbol "$=" e <- expr syn return (ns, FieldUpdate e) <?> "field setter" fieldGet :: IdrisParser [Name] fieldGet = P.sepBy1 fnName (symbol "->") fieldGetOrSet :: IdrisParser (Either [([Name], SetOrUpdate)] [Name]) fieldGetOrSet = P.try (Left <$> P.sepBy1 fieldSet (lchar ',')) <|> do f <- fieldGet return (Right f) applyAll :: FC -> [([Name], SetOrUpdate)] -> PTerm -> PTerm applyAll fc [] x = x applyAll fc ((ns, e) : es) x = applyAll fc es (doUpdate fc ns e x) doUpdate fc ns (FieldUpdate e) get = let get' = getAll fc (reverse ns) get in doUpdate fc ns (FieldSet (PApp fc e [pexp get'])) get doUpdate fc [n] (FieldSet e) get = PApp fc (PRef fc [] (mkType n)) [pexp e, pexp get] doUpdate fc (n : ns) e get = PApp fc (PRef fc [] (mkType n)) [pexp (doUpdate fc ns e (PApp fc (PRef fc [] n) [pexp get])), pexp get] getAll :: FC -> [Name] -> PTerm -> PTerm getAll fc [n] e = PApp fc (PRef fc [] n) [pexp e] getAll fc (n:ns) e = PApp fc (PRef fc [] n) [pexp (getAll fc ns e)] mkType :: Name -> Name mkType (UN n) = sUN ("set_" ++ str n) mkType (MN 0 n) = sMN 0 ("set_" ++ str n) mkType (NS n s) = NS (mkType n) s | Parses a type signature @ TypeSig : : = ' : ' ; @ @ TypeExpr : : = ConstraintList ? ; @ @ TypeSig ::= ':' Expr ; @ @ TypeExpr ::= ConstraintList? Expr; @ -} typeExpr :: SyntaxInfo -> IdrisParser PTerm typeExpr syn = do cs <- if implicitAllowed syn then constraintList syn else return [] sc <- expr (allowConstr syn) return (bindList (\r -> PPi (constraint { pcount = r })) cs sc) <?> "type signature" | Parses a lambda expression @ Lambda : : = ' \\ ' TypeOptDeclList LambdaTail | ' \\ ' SimpleExprList LambdaTail ; @ @ SimpleExprList : : = SimpleExpr | SimpleExpr ' , ' SimpleExprList ; @ @ LambdaTail : : = Impossible | ' = > ' Expr @ @ Lambda ::= '\\' TypeOptDeclList LambdaTail | '\\' SimpleExprList LambdaTail ; @ @ SimpleExprList ::= SimpleExpr | SimpleExpr ',' SimpleExprList ; @ @ LambdaTail ::= Impossible | '=>' Expr @ -} lambda :: SyntaxInfo -> IdrisParser PTerm lambda syn = do lchar '\\' <?> "lambda expression" ((do xt <- P.try $ tyOptDeclList (disallowImp syn) (sc, fc) <- withExtent lambdaTail return (bindList (\r -> PLam fc) xt sc)) <|> (do ps <- P.sepBy (do (e, fc) <- withExtent $ simpleExpr (disallowImp (syn { inPattern = True })) return (fc, e)) (lchar ',') sc <- lambdaTail return (pmList (zip [0..] ps) sc))) <?> "lambda expression" where pmList :: [(Int, (FC, PTerm))] -> PTerm -> PTerm pmList [] sc = sc pmList ((i, (fc, x)) : xs) sc = PLam fc (sMN i "lamp") NoFC Placeholder (PCase fc (PRef fc [] (sMN i "lamp")) [(x, pmList xs sc)]) lambdaTail :: IdrisParser PTerm lambdaTail = impossible <|> symbol "=>" *> expr syn | Parses a term rewrite expression @ RewriteTerm : : = ' rewrite ( ' = = > ' ) ? ' in ' ; @ @ RewriteTerm ::= 'rewrite' Expr ('==>' Expr)? 'in' Expr ; @ -} rewriteTerm :: SyntaxInfo -> IdrisParser PTerm rewriteTerm syn = do keyword "rewrite" (prf, fc) <- withExtent $ expr syn giving <- optional (do symbol "==>"; expr' syn) using <- optional (do reserved "using" n <- name return n) keyword "in"; sc <- expr syn return (PRewrite fc using prf sc giving) <?> "term rewrite expression" | Parse rig count for linear types rigCount :: Parsing m => m RigCount rigCount = P.option RigW $ do lchar '1'; return Rig1 <|> do lchar '0'; return Rig0 |Parses a let binding @ Let : : = ' let ' Name ' ? ' = ' ' in ' Expr | ' let ' ' ' = ' ' ' in ' ' : : = ' : ' ' ; @ @ Let ::= 'let' Name TypeSig'? '=' Expr 'in' Expr | 'let' Expr' '=' Expr' 'in' Expr TypeSig' ::= ':' Expr' ; @ -} let_ :: SyntaxInfo -> IdrisParser PTerm let_ syn = P.try (do keyword "let" ls <- indentedBlock (let_binding syn) keyword "in"; sc <- expr syn return (buildLets ls sc)) <?> "let binding" where buildLets [] sc = sc buildLets ((fc, rc, PRef nfc _ n, ty, v, []) : ls) sc = PLet fc rc n nfc ty v (buildLets ls sc) buildLets ((fc, _, pat, ty, v, alts) : ls) sc = PCase fc v ((pat, buildLets ls sc) : alts) let_binding syn = do rc <- rigCount (pat, fc) <- withExtent $ expr' (syn { inPattern = True }) ty <- P.option Placeholder (do lchar ':'; expr' syn) lchar '=' v <- expr (syn { withAppAllowed = isVar pat }) ts <- P.option [] (do lchar '|' P.sepBy1 (do_alt syn) (lchar '|')) return (fc,rc,pat,ty,v,ts) where isVar (PRef _ _ _) = True isVar _ = False | Parses a conditional expression @ If : : = ' if ' ' then ' ' else ' @ @ If ::= 'if' Expr 'then' Expr 'else' Expr @ -} if_ :: SyntaxInfo -> IdrisParser PTerm if_ syn = (do keyword "if" (c, fc) <- withExtent $ expr syn keyword "then" t <- expr syn keyword "else" f <- expr syn return (PIfThenElse fc c t f)) <?> "conditional expression" | Parses a quote goal @ QuoteGoal : : = ' quoteGoal ' Name ' by ' ' in ' ; @ @ QuoteGoal ::= 'quoteGoal' Name 'by' Expr 'in' Expr ; @ -} quoteGoal :: SyntaxInfo -> IdrisParser PTerm quoteGoal syn = do keyword "quoteGoal"; n <- name; keyword "by" r <- expr syn keyword "in" (sc, fc) <- withExtent $ expr syn return (PGoal fc r n sc) <?> "quote goal expression" | Parses a dependent type signature @ Pi : : = PiOpts Static ? Pi ' @ @ Pi ' : : = OpExpr ( ' - > ' Pi ) ? | ' ( ' TypeDeclList ' ) ' ' - > ' Pi | ' { ' TypeDeclList ' } ' ' - > ' Pi | ' { ' ' auto ' TypeDeclList ' } ' ' - > ' Pi | ' { ' ' default ' SimpleExpr TypeDeclList ' } ' ' - > ' Pi ; @ @ Pi ::= PiOpts Static? Pi' @ @ Pi' ::= OpExpr ('->' Pi)? | '(' TypeDeclList ')' '->' Pi | '{' TypeDeclList '}' '->' Pi | '{' 'auto' TypeDeclList '}' '->' Pi | '{' 'default' SimpleExpr TypeDeclList '}' '->' Pi ; @ -} bindsymbol opts st syn = do symbol "->" return (Exp opts st False RigW) explicitPi opts st syn = do xt <- P.try (lchar '(' *> typeDeclList syn <* lchar ')') binder <- bindsymbol opts st syn sc <- expr (allowConstr syn) return (bindList (\r -> PPi (binder { pcount = r })) xt sc) autoImplicit opts st syn = do keyword "auto" when (st == Static) $ fail "auto implicits can not be static" xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr (allowConstr syn) return (bindList (\r -> PPi (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]) r)) xt sc) defaultImplicit opts st syn = do keyword "default" when (st == Static) $ fail "default implicits can not be static" ist <- get script' <- simpleExpr syn let script = debindApp syn . desugar syn ist $ script' xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr (allowConstr syn) return (bindList (\r -> PPi (TacImp [] Dynamic script r)) xt sc) normalImplicit opts st syn = do xt <- typeDeclList syn <* lchar '}' symbol "->" cs <- constraintList syn sc <- expr syn let (im,cl) = if implicitAllowed syn then (Imp opts st False (Just (Impl False True False)) True RigW, constraint) else (Imp opts st False (Just (Impl False False False)) True RigW, Imp opts st False (Just (Impl True False False)) True RigW) return (bindList (\r -> PPi (im { pcount = r })) xt (bindList (\r -> PPi (cl { pcount = r })) cs sc)) constraintPi opts st syn = do cs <- constraintList1 syn sc <- expr syn if implicitAllowed syn then return (bindList (\r -> PPi constraint { pcount = r }) cs sc) else return (bindList (\r -> PPi (Imp opts st False (Just (Impl True False False)) True r)) cs sc) implicitPi opts st syn = autoImplicit opts st syn <|> defaultImplicit opts st syn <|> normalImplicit opts st syn unboundPi opts st syn = do x <- opExpr syn (do binder <- bindsymbol opts st syn sc <- expr syn return (PPi binder (sUN "__pi_arg") NoFC x sc)) <|> return x unboundPiNoConstraint opts st syn = do x <- opExpr syn (do binder <- bindsymbol opts st syn sc <- expr syn P.notFollowedBy $ reservedOp "=>" return (PPi binder (sUN "__pi_arg") NoFC x sc)) <|> do P.notFollowedBy $ reservedOp "=>" return x pi :: SyntaxInfo -> IdrisParser PTerm pi syn = do opts <- piOpts syn st <- static explicitPi opts st syn <|> P.try (do lchar '{'; implicitPi opts st syn) <|> if constraintAllowed syn then P.try (unboundPiNoConstraint opts st syn) <|> constraintPi opts st syn else unboundPi opts st syn <?> "dependent type signature" piOpts :: SyntaxInfo -> IdrisParser [ArgOpt] piOpts syn | implicitAllowed syn = lchar '.' *> return [InaccessibleArg] <|> return [] piOpts syn = return [] | Parses a type constraint list @ ConstraintList : : = ' ( ' Expr_List ' ) ' ' = > ' | Expr ' = > ' ; @ @ ConstraintList ::= '(' Expr_List ')' '=>' | Expr '=>' ; @ -} constraintList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] constraintList syn = P.try (constraintList1 syn) <|> return [] constraintList1 :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] constraintList1 syn = P.try (do lchar '(' tys <- P.sepBy1 nexpr (lchar ',') lchar ')' reservedOp "=>" return tys) <|> P.try (do t <- opExpr (disallowImp syn) reservedOp "=>" return [(RigW, defname, NoFC, t)]) <?> "type constraint list" where nexpr = P.try (do (n, fc) <- withExtent name; lchar ':' e <- expr (disallowImp syn) return (RigW, n, fc, e)) <|> do e <- expr (disallowImp syn) return (RigW, defname, NoFC, e) defname = sMN 0 "constraint" | Parses a type declaration list @ TypeDeclList : : = FunctionSignatureList | NameList TypeSig ; @ @ FunctionSignatureList : : = Name TypeSig | Name TypeSig ' , ' FunctionSignatureList ; @ @ TypeDeclList ::= FunctionSignatureList | NameList TypeSig ; @ @ FunctionSignatureList ::= Name TypeSig | Name TypeSig ',' FunctionSignatureList ; @ -} typeDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] typeDeclList syn = P.try (P.sepBy1 (do rig <- rigCount (x, xfc) <- withExtent fnName lchar ':' t <- typeExpr (disallowImp syn) return (rig, x, xfc, t)) (lchar ',')) <|> do ns <- P.sepBy1 (withExtent name) (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\(x, xfc) -> (RigW, x, xfc, t)) ns) <?> "type declaration list" | Parses a type declaration list with optional parameters @ TypeOptDeclList : : = NameOrPlaceholder ? | NameOrPlaceholder ? ' , ' TypeOptDeclList ; @ @ NameOrPlaceHolder : : = Name | ' _ ' ; @ @ TypeOptDeclList ::= NameOrPlaceholder TypeSig? | NameOrPlaceholder TypeSig? ',' TypeOptDeclList ; @ @ NameOrPlaceHolder ::= Name | '_'; @ -} tyOptDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)] tyOptDeclList syn = P.sepBy1 (do (x, fc) <- withExtent nameOrPlaceholder t <- P.option Placeholder (do lchar ':' expr syn) return (RigW, x, fc, t)) (lchar ',') <?> "type declaration list" where nameOrPlaceholder :: IdrisParser Name nameOrPlaceholder = fnName <|> sMN 0 "underscore" <$ reservedOp "_" <?> "name or placeholder" | Parses a list literal expression e.g. [ 1,2,3 ] or a comprehension [ ( x , y ) | x < - xs , y < - ys ] @ ListExpr : : = ' [ ' ' ] ' | ' [ ' ' | ' DoList ' ] ' | ' [ ' ExprList ' ] ' ; @ @ DoList : : = Do | Do ' , ' DoList ; @ @ ExprList : : = Expr | Expr ' , ' ExprList ; @ @ ListExpr ::= '[' ']' | '[' Expr '|' DoList ']' | '[' ExprList ']' ; @ @ DoList ::= Do | Do ',' DoList ; @ @ ExprList ::= Expr | Expr ',' ExprList ; @ -} listExpr :: SyntaxInfo -> IdrisParser PTerm listExpr syn = do (FC f (l, c) _) <- extent (lchar '[') (do (FC _ _ (l', c')) <- extent (lchar ']') <?> "end of list expression" return (mkNil (FC f (l, c) (l', c')))) <|> (do (x, fc) <- withExtent (expr (syn { withAppAllowed = False })) <?> "expression" (do P.try (lchar '|') <?> "list comprehension" qs <- P.sepBy1 (do_ syn) (lchar ',') lchar ']' return (PDoBlock (map addGuard qs ++ [DoExp fc (PApp fc (PRef fc [] (sUN "pure")) [pexp x])]))) <|> (do xs <- many (do commaFC <- extent (lchar ',') <?> "list element" elt <- expr syn return (elt, commaFC)) rbrackFC <- extent (lchar ']') <?> "end of list expression" return (mkList fc rbrackFC ((x, (FC f (l, c) (l, c+1))) : xs)))) <?> "list expression" where mkNil :: FC -> PTerm mkNil fc = PRef fc [fc] (sUN "Nil") mkList :: FC -> FC -> [(PTerm, FC)] -> PTerm mkList errFC nilFC [] = PRef nilFC [nilFC] (sUN "Nil") mkList errFC nilFC ((x, fc) : xs) = PApp errFC (PRef fc [fc] (sUN "::")) [pexp x, pexp (mkList errFC nilFC xs)] addGuard :: PDo -> PDo addGuard (DoExp fc e) = DoExp fc (PApp fc (PRef fc [] (sUN "guard")) [pexp e]) addGuard x = x | Parses a do - block @ Do ' : : = Do KeepTerminator ; @ @ : : = ' do ' OpenBlock Do'+ CloseBlock ; @ @ Do' ::= Do KeepTerminator; @ @ DoBlock ::= 'do' OpenBlock Do'+ CloseBlock ; @ -} doBlock :: SyntaxInfo -> IdrisParser PTerm doBlock syn = do keyword "do" PDoBlock <$> indentedBlock1 (do_ syn) <?> "do block" | Parses an expression inside a do block @ Do : : = ' let ' Name ' ? ' = ' let ' ' ' = ' rewrite | Name ' < - ' Expr | Expr ' ' < - ' Expr | Expr ; @ @ Do ::= 'let' Name TypeSig'? '=' Expr | 'let' Expr' '=' Expr | 'rewrite Expr | Name '<-' Expr | Expr' '<-' Expr | Expr ; @ -} do_ :: SyntaxInfo -> IdrisParser PDo do_ syn = P.try (do keyword "let" (i, ifc) <- withExtent name ty' <- P.optional (do lchar ':' expr' syn) reservedOp "=" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) P.option (DoLet fc RigW i ifc (fromMaybe Placeholder ty') e) (do lchar '|' when (isJust ty') $ fail "a pattern-matching let may not have an explicit type annotation" ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoLetP fc (PRef ifc [ifc] i) e ts))) <|> P.try (do keyword "let" i <- expr' syn reservedOp "=" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) P.option (DoLetP fc i e []) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoLetP fc i e ts))) <|> P.try (do (sc, fc) <- withExtent (keyword "rewrite" *> expr syn) return (DoRewrite fc sc)) <|> P.try (do (i, ifc) <- withExtent name symbol "<-" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }); P.option (DoBind fc i ifc e) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoBindP fc (PRef ifc [ifc] i) e ts))) <|> P.try (do i <- expr' syn symbol "<-" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }); P.option (DoBindP fc i e []) (do lchar '|' ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|') return (DoBindP fc i e ts))) <|> do (e, fc) <- withExtent $ expr syn return (DoExp fc e) <?> "do block expression" do_alt syn = do l <- expr' syn P.option (Placeholder, l) (do symbol "=>" r <- expr' syn return (l, r)) | Parses an expression in idiom brackets @ Idiom : : = ' [ | ' ' | ] ' ; @ @ Idiom ::= '[|' Expr '|]'; @ -} idiom :: SyntaxInfo -> IdrisParser PTerm idiom syn = do symbol "[|" (e, fc) <- withExtent $ expr (syn { withAppAllowed = False }) symbol "|]" return (PIdiom fc e) <?> "expression in idiom brackets" |Parses a constant or literal expression @ Constant : : = ' Integer ' | ' Int ' | ' ' | ' Double ' | ' String ' | ' Bits8 ' | ' Bits16 ' | ' Bits32 ' | ' Bits64 ' | Float_t | | VerbatimString_t | String_t | ; @ @ Constant ::= 'Integer' | 'Int' | 'Char' | 'Double' | 'String' | 'Bits8' | 'Bits16' | 'Bits32' | 'Bits64' | Float_t | Natural_t | VerbatimString_t | String_t | Char_t ; @ -} constants :: [(String, Idris.Core.TT.Const)] constants = [ ("Integer", AType (ATInt ITBig)) , ("Int", AType (ATInt ITNative)) , ("Char", AType (ATInt ITChar)) , ("Double", AType ATFloat) , ("String", StrType) , ("prim__WorldType", WorldType) , ("prim__TheWorld", TheWorld) , ("Bits8", AType (ATInt (ITFixed IT8))) , ("Bits16", AType (ATInt (ITFixed IT16))) , ("Bits32", AType (ATInt (ITFixed IT32))) , ("Bits64", AType (ATInt (ITFixed IT64))) ] constant :: Parsing m => m Idris.Core.TT.Const constant = P.choice [ ty <$ reserved name | (name, ty) <- constants ] <|> P.try (Fl <$> float) <|> BI <$> natural <|> Str <$> verbatimStringLiteral <|> Str <$> stringLiteral <?> "constant or literal" verbatimStringLiteral :: Parsing m => m String verbatimStringLiteral = token $ do P.try $ string "\"\"\"" str <- P.manyTill P.anySingle $ P.try (string "\"\"\"") moreQuotes <- P.many $ P.char '"' return $ str ++ moreQuotes static :: IdrisParser Static static = Static <$ reserved "%static" <|> return Dynamic <?> "static modifier" | Parses a tactic script @ Tactic : : = ' intro ' NameList ? | ' intros ' | ' refine ' Name Imp+ | ' mrefine ' Name | ' rewrite ' Expr | ' induction ' Expr | ' equiv ' Expr | ' let ' Name ' : ' ' ' = ' Expr | ' let ' Name ' = ' Expr | ' focus ' Name | ' exact ' Expr | ' applyTactic ' Expr | ' reflect ' Expr | ' fill ' Expr | ' try ' Tactic ' | ' Tactic | ' { ' TacticSeq ' } ' | ' compute ' | ' trivial ' | ' solve ' | ' attack ' | ' state ' | ' term ' | ' undo ' | ' qed ' | ' abandon ' | ' : ' ' q ' ; Imp : : = ' ? ' | ' _ ' ; TacticSeq : : = Tactic ' ; ' Tactic | Tactic ' ; ' TacticSeq ; @ @ Tactic ::= 'intro' NameList? | 'intros' | 'refine' Name Imp+ | 'mrefine' Name | 'rewrite' Expr | 'induction' Expr | 'equiv' Expr | 'let' Name ':' Expr' '=' Expr | 'let' Name '=' Expr | 'focus' Name | 'exact' Expr | 'applyTactic' Expr | 'reflect' Expr | 'fill' Expr | 'try' Tactic '|' Tactic | '{' TacticSeq '}' | 'compute' | 'trivial' | 'solve' | 'attack' | 'state' | 'term' | 'undo' | 'qed' | 'abandon' | ':' 'q' ; Imp ::= '?' | '_'; TacticSeq ::= Tactic ';' Tactic | Tactic ';' TacticSeq ; @ -} | ExprTArg | AltsTArg | StringLitTArg The FIXMEs are Issue # 1766 in the issue tracker . tactics :: [([String], Maybe TacticArg, SyntaxInfo -> IdrisParser PTactic)] tactics = FIXME syntax for intro ( fresh name ) do ns <- P.sepBy (spaced name) (lchar ','); return $ Intro ns) , noArgs ["intros"] Intros , noArgs ["unfocus"] Unfocus , (["refine"], Just ExprTArg, const $ do n <- spaced fnName imps <- many imp return $ Refine n imps) , (["claim"], Nothing, \syn -> do n <- indentGt *> name goal <- indentGt *> expr syn return $ Claim n goal) , (["mrefine"], Just ExprTArg, const $ do n <- spaced fnName return $ MatchRefine n) , expressionTactic ["rewrite"] Rewrite , expressionTactic ["equiv"] Equiv FIXME syntax for let do n <- (indentGt *> name) (do indentGt *> lchar ':' ty <- indentGt *> expr' syn indentGt *> lchar '=' t <- indentGt *> expr syn i <- get return $ LetTacTy n (desugar syn i ty) (desugar syn i t)) <|> (do indentGt *> lchar '=' t <- indentGt *> expr syn i <- get return $ LetTac n (desugar syn i t))) , (["focus"], Just ExprTArg, const $ do n <- spaced name return $ Focus n) , expressionTactic ["exact"] Exact , expressionTactic ["applyTactic"] ApplyTactic , expressionTactic ["byReflection"] ByReflection , expressionTactic ["reflect"] Reflect , expressionTactic ["fill"] Fill , (["try"], Just AltsTArg, \syn -> do t <- spaced (tactic syn) lchar '|' t1 <- spaced (tactic syn) return $ Try t t1) , noArgs ["compute"] Compute , noArgs ["trivial"] Trivial , noArgs ["unify"] DoUnify , (["search"], Nothing, const $ do depth <- P.option 10 natural return (ProofSearch True True (fromInteger depth) Nothing [] [])) , noArgs ["implementation"] TCImplementation , noArgs ["solve"] Solve , noArgs ["attack"] Attack , noArgs ["state", ":state"] ProofState , noArgs ["term", ":term"] ProofTerm , noArgs ["undo", ":undo"] Undo , noArgs ["qed", ":qed"] Qed , noArgs ["abandon", ":q"] Abandon , noArgs ["skip"] Skip , noArgs ["sourceLocation"] SourceFC , expressionTactic [":e", ":eval"] TEval , expressionTactic [":t", ":type"] TCheck , expressionTactic [":search"] TSearch , (["fail"], Just StringLitTArg, const $ do msg <- stringLiteral return $ TFail [Idris.Core.TT.TextPart msg]) , ([":doc"], Just ExprTArg, const $ do whiteSpace doc <- (Right <$> constant) <|> (Left <$> fnName) P.eof return (TDocStr doc)) ] where expressionTactic names tactic = (names, Just ExprTArg, \syn -> do t <- spaced (expr syn) i <- get return $ tactic (desugar syn i t)) noArgs names tactic = (names, Nothing, const (return tactic)) spaced parser = indentGt *> parser imp :: IdrisParser Bool imp = do lchar '?'; return False <|> do lchar '_'; return True tactic :: SyntaxInfo -> IdrisParser PTactic tactic syn = P.choice [ do P.choice (map reserved names); parser syn | (names, _, parser) <- tactics ] <|> do lchar '{' t <- tactic syn; lchar ';'; ts <- P.sepBy1 (tactic syn) (lchar ';') lchar '}' return $ TSeq t (mergeSeq ts) <|> ((lchar ':' >> empty) <?> "prover command") <?> "tactic" where mergeSeq :: [PTactic] -> PTactic mergeSeq [t] = t mergeSeq (t:ts) = TSeq t (mergeSeq ts) fullTactic :: SyntaxInfo -> IdrisParser PTactic fullTactic syn = do t <- tactic syn P.eof return t
6d4c85fc8dd933ac32989a41f938cca48adb330d3ec1697bfc9c25635ce0e36f
clojure/core.typed
bootstrap_cljs.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:skip-wiki clojure.core.typed.bootstrap-cljs (:require [clojure.set :as set])) (def -base-aliases '#{AnyInteger Integer Int Seqable NonEmptySeq Number String Boolean Seq Str EmptySeqable NonEmptySeqable Option Coll NonEmptyColl NonEmptyASeq NonEmptyAVec EmptyCount NonEmptyCount Vec Nilable AVec NilableNonEmptyASeq PersistentList Collection Set Stack Reversible IPersistentSet IPersistentVector IPersistentMap APersistentMap Associative Map Atom1 Atom2 Sequential Num}) (def -specials '#{All U Any Pred ReadOnlyArray Array IFn TFn I HSequential HSeq HSet HMap Val Value CountRange ExactCount Difference Rec Assoc Get HVec JSUndefined JSNull Nothing JSNumber JSBoolean JSString JSSymbol JSObject CLJSInteger JSObj}) (let [i (set/intersection -base-aliases -specials)] (assert (empty? i) (pr-str i))) (defmacro base-aliases "Define base aliases" [] `(do ~@(map #(list 'def %) (concat -base-aliases -specials))))
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.js/src/clojure/core/typed/bootstrap_cljs.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) , contributors . (ns ^:skip-wiki clojure.core.typed.bootstrap-cljs (:require [clojure.set :as set])) (def -base-aliases '#{AnyInteger Integer Int Seqable NonEmptySeq Number String Boolean Seq Str EmptySeqable NonEmptySeqable Option Coll NonEmptyColl NonEmptyASeq NonEmptyAVec EmptyCount NonEmptyCount Vec Nilable AVec NilableNonEmptyASeq PersistentList Collection Set Stack Reversible IPersistentSet IPersistentVector IPersistentMap APersistentMap Associative Map Atom1 Atom2 Sequential Num}) (def -specials '#{All U Any Pred ReadOnlyArray Array IFn TFn I HSequential HSeq HSet HMap Val Value CountRange ExactCount Difference Rec Assoc Get HVec JSUndefined JSNull Nothing JSNumber JSBoolean JSString JSSymbol JSObject CLJSInteger JSObj}) (let [i (set/intersection -base-aliases -specials)] (assert (empty? i) (pr-str i))) (defmacro base-aliases "Define base aliases" [] `(do ~@(map #(list 'def %) (concat -base-aliases -specials))))
1f896c07aa5c8f1780d200f78304e308a68894462f504bdfddb560470a4f7307
gldubc/cast-machine
exec.ml
# 1 "exec.cppo.ml" open Primitives open Utils open Bytecode open Types open Types.Print open Bytecode_Eager open Syntax.Eager (* #define MONITOR "1" *) # define BENCH " 1 " # define DEBUG " 1 " module Env = struct include . Make(struct ` type ` t = var let equal = ( =) let hash = Hashtbl.hash end ) end include Hashtbl.Make(struct `type `t = var let equal = (=) let hash = Hashtbl.hash end) end *) module type Structures = sig type result type stack_item type stack type dump type env type state = bytecode * env * stack * dump type nu val empty_env : env val typeof : stack_item -> tau end module Make_Machine (B : Bytecode) = struct open B type result = [ | `CST of b | `Fail ] and stack_item = [ `CST of b | `FCST of (b -> b) | `CLS of bytecode * env * kappa * mark | `ACLS of int * bytecode * env * kappa * mark | `TYP of kappa | `ARR of b array | `FAIL | `PAIR of stack_item * stack_item ] and env = stack_item list type stack = stack_item list let access e n = List.nth e n let empty_env : env = [] (* machine values *) (* type nu = [ | `CST of b | `CLS of var * bytecode * env * kappa * mark | `PAIR of nu * nu ] *) type dump_item = | Boundary of kappa | Frame of bytecode * env type dump = dump_item list type state = bytecode * env * stack * dump let n_t_dyn = neg t_dyn let rec typeof : stack_item -> t = function | `CST b -> cap (constant b) (t_dyn) | `CLS (_, _, k, _) -> eval_1 k | `ACLS (_,_,_,k,_) -> eval_1 k | `PAIR (v1, v2) -> pair (typeof v1) (typeof v2) | _ -> failwith "error: trying to take typeof of `TYP or `FAIL" (* parameter functions *) let compose : kappa - > kappa - > kappa = fun k1 k2 - > let ( ) = in let ( t3,t4 ) = eval k2 in mk_kappa ( ( cap t1 t3 ) , ( cap t2 t4 ) ) let (t1,t2) = eval k1 in let (t3,t4) = eval k2 in mk_kappa ((cap t1 t3), (cap t2 t4)) *) let dump : kappa -> dump -> dump = fun k -> function | [] -> [Boundary k] | Boundary k' :: d' -> Boundary (compose k k') :: d' | (Frame _ :: _) as d -> Boundary k :: d let rec applycast : stack_item -> kappa -> stack_item = fun v k -> let (t,td) = eval k in begin match v with | `CST b -> if subtype (constant b) (ceil t) then `CST b else `FAIL | `PAIR (v1, v2) -> let t1, t2 = pi1 t, pi2 t in let k1, k2 = mk_kappa (t1,dom t1), mk_kappa (t2,dom t2) in let cv1 = applycast v1 k1 in let cv2 = applycast v2 k2 in begin match cv1, cv2 with | `FAIL, _ -> `FAIL | _, `FAIL -> `FAIL | _ -> `PAIR (cv1, cv2) end | `CLS (c,e,k',_) -> if td = t_bot then `FAIL else let kc = compose k k' in `CLS (c,e,kc,Strict) | `ACLS (n,c,e,k',_) -> if td = t_bot then `FAIL else let kc = compose k k' in `ACLS (n,c,e,kc,Strict) | _ -> failwith "wrong object to be cast" end module Print = struct let rec show_stack_value : stack_item -> string = function | `CST b -> pp_b b | `FCST _ -> "" | `CLS (btc, env, ts, m) -> Printf.sprintf "C(%s, %s, %s, %s)" (show_bytecode 2 btc) (show_env 1 env) (show_kappa ts) (show_mark m) | `ACLS (n,btc, env, ts, m) -> Printf.sprintf "C_%i(%s, %s, %s, %s)" n (show_bytecode 2 btc) (show_env 1 env) (show_kappa ts) (show_mark m) | `TYP k -> show_kappa k | `FAIL -> "Fail" | `PAIR (v1, v2) -> Printf.sprintf "(%s, %s)" (show_stack_value v1) (show_stack_value v2) | `ARR _ ->"[a]" and sh_env_v : int -> stack_item -> string = function | 2 -> show_stack_value | 0 -> (fun _ -> "_") | 1 -> show_stack_value_1 | _ -> failwith "wrong verbose argument" and show_result : stack_item -> string = function | `CST b -> Printf.sprintf "%s = %s" (show_tau (constant b)) (pp_b b) | `CLS (_,_, k,_) -> let t = eval_1 k in Printf.sprintf "%s = <fun>" (show_tau t) | `FAIL -> "Fail" | `PAIR (v1, v2) as v -> Printf.sprintf "%s = (%s, %s)" (show_tau @@ typeof v) (show_result v1) (show_result v2) | `ARR _ -> "[a]" | _ -> failwith "not a return value" and show_env verb ?inline:(i=true) : env -> string = fun e -> let sep = if i then " . " else "\n\t " in String.concat sep (List.map (fun v -> sh_env_v verb v) e) fun verb inline env - > let lenv = List.of_seq ( Env.to_seq env ) in let sep = if inline then " . " else " \n\t " in if lenv = [ ] then " { } " else " { " ^ String.concat sep ( List.map ( fun ( v , sv ) - > Printf.sprintf " ( % s : = % s ) " ( pp_var v ) ( sh_env_v verb sv ) ) lenv ) ^ " } " let lenv = List.of_seq (Env.to_seq env) in let sep = if inline then " . " else "\n\t " in if lenv = [] then "{}" else "{ " ^ String.concat sep (List.map (fun (v,sv) -> Printf.sprintf "(%s := %s)" (pp_var v) (sh_env_v verb sv)) lenv) ^ " }" *) and show_dump_item verb : dump_item -> string = function | Boundary t -> Printf.sprintf "<%s>" (show_kappa t) | Frame (_,e) -> Printf.sprintf "([code], %s)" (show_env verb e) and show_dump verb : dump -> string = fun d -> (String.concat "\n\n\t " (List.map (show_dump_item verb) d)) and show_stack_value_1 : stack_item -> string = function | `CST b -> pp_b b | `CLS (c,env,bnd,_) -> Printf.sprintf "[c[%i],e[%i],%s]" (List.length c) (List.length env) (show_kappa bnd) | `TYP t -> show_kappa t | `FAIL -> "Fail" | `PAIR (v1, v2) -> Printf.sprintf "(%s, %s)" (show_stack_value_1 v1) (show_stack_value_1 v2) | `ARR a -> "[" ^ (String.concat ";" (Array.to_list ( Array.map (fun v -> pp_b v) a ))) ^ "]" | _->"not implem" let show_stack s verbose = let show_stack_val = begin match verbose with | 2 -> show_stack_value | 1 -> show_stack_value_1 | 0 -> fun _ -> "" | _ -> failwith "wrong verbose argument" end in Printf.sprintf "[ %s ]" (String.concat "\n\t " (List.map show_stack_val s)) end module MetricsDebug = struct open Print module MetricsEnv = Hashtbl.Make(struct type t = byte let equal a b = match a, b with | ACC _, ACC _ | CST _, CST _ | CLS _, CLS _ | LET , LET | TYP _, TYP _ | END , END | TCA _, TCA _ | IFZ _, IFZ _ -> true | _ -> a = b let hash = Hashtbl.hash end) type metrics = {mutable stack_sizes : (int * int) list; mutable longest_proxies : (int * int) list; mutable casts : (int * int) list; instructions : int MetricsEnv.t; mutable dump_sizes : (int * int) list; mutable env_sizes : (int * int) list; mutable dump_frames : (int * int) list; mutable dump_bounds : (int * int) list; } type run_params = {run : bool ref; step : int ref; max_stack : int ref; max_env : int ref; verbose : int ref; delim : int ref; debug : bool ref; step_mode : bool ref; step_start : int ref; monitor : bool ref; mutable states : state list; mutable metrics : metrics} let init_metrics : unit -> metrics = fun () -> {stack_sizes = []; longest_proxies = []; casts = []; instructions = MetricsEnv.create 20; dump_sizes = []; env_sizes = []; dump_frames = []; dump_bounds = [] } let run_params = {run = ref true; step = ref 0; max_stack = ref 1000; max_env = ref 1000; verbose = ref 2; delim = ref 2; debug = ref true; step_mode = ref false; step_start = ref 0; monitor = ref false; states = []; metrics = init_metrics ()} let count_cast : stack -> int = let rec aux acc = function | [] -> acc | `TYP _ :: s -> aux (acc+1) s | _ :: s -> aux acc s in aux 0 let count_bound dmp : int = List.fold_left (fun n e -> match e with | Boundary _ -> n+1 | _ -> n) 0 dmp let longest_proxy : stack -> int = let rec aux max acc = function | [] -> max | `TYP _ :: s when acc+1 > max -> aux (acc+1) (acc+1) s | `TYP _ :: s -> aux max (acc+1) s | _ :: s -> aux max 0 s in aux 0 0 let env_length : env -> int = List.length let dump_length d = List.fold_left (fun n -> function | Frame (_,e) -> env_length e + n | _ -> n) 0 d let dump_frame_length d = List.length d let gather_metrics : run_params -> state -> unit = fun run_params -> let met = run_params.metrics in fun (c, e, s, d) -> begin (* let () = print_endline "coucou" in *) met.dump_bounds<- (!(run_params.step), count_bound d) :: met.dump_bounds; met.env_sizes <- (!(run_params.step), List.length e) :: met.env_sizes; met.stack_sizes <- (!(run_params.step), (List.length s)) :: met.stack_sizes; met.dump_sizes <- (!(run_params.step), dump_length d) :: met.dump_sizes; met.dump_frames <- (!(run_params.step), dump_frame_length d) :: met.dump_frames; met.longest_proxies <- (!(run_params.step), (longest_proxy s)) :: met.longest_proxies; met.casts <- (!(run_params.step), (count_cast s)) :: met.casts; run_params.metrics <- met; if c != [] then let instr = List.hd c in let cnt_inst = (try MetricsEnv.find met.instructions instr with Not_found -> 0) in let () = Printf.printf "counting one instruction %s" (show_byte 1 instr) in MetricsEnv.replace met.instructions instr (cnt_inst+1) end let delim n i = let si = string_of_int i in let d = String.length si in String.init (n+1-d) (fun _ -> ' ') let rec firstk k xs = match xs with | [] -> [] | x::xs -> if k=1 then [x] else x::firstk (k-1) xs;; let print_debug_stack run_params s = let stack_size = List.length s in if !(run_params.verbose) >= 1 then let d = delim !(run_params.delim) stack_size in let ssize = string_of_int stack_size in let strstack = show_stack (firstk 20 s) !(run_params.verbose) in Printf.printf "Stack[%s]:%s%s\n" ssize d strstack else Printf.printf "Stack[%i]\n" (stack_size) let print_debug_code run_params s = let stack_size = List.length s in if !(run_params.verbose) >= 1 then Printf.printf "Code [%i]:%s%s\n" (stack_size) (delim !(run_params.delim) stack_size) (show_bytecode !(run_params.verbose) (firstk 7 s)) else Printf.printf "Code [%i]\n" (stack_size) let print_debug_env run_params s = let stack_size = env_length s in if stack_size < 20 && !(run_params.verbose) >= 1 then Printf.printf "Env [%i]:%s%s\n" (stack_size) (delim !(run_params.delim) stack_size) (show_env !(run_params.verbose) ~inline:false s) else Printf.printf "Env [%i]\n" (stack_size) let print_debug_dump run_params s = let stack_size = dump_length s in if !(run_params.verbose) >= 1 then Printf.printf "Dump [%i][%i][#casts=%i]:\n\t %s%s\n" (List.length s) (stack_size) (count_bound s) (delim !(run_params.delim) stack_size) (show_dump !(run_params.verbose) (firstk 4 s)) else Printf.printf "Dump [%i][%i][casts=%i]\n" (List.length s) (stack_size) (count_bound s) let print_debug_run run_params = function | c, e, s, d -> Printf.printf "==={%i}========================================================================\n" !(run_params.step); Stdlib.flush stdout; print_debug_code run_params c; Stdlib.flush stdout; print_endline ""; print_debug_stack run_params s; Stdlib.flush stdout; print_endline ""; print_debug_env run_params e; Stdlib.flush stdout; print_endline ""; print_debug_dump run_params d; Stdlib.flush stdout end module Transitions = struct open MetricsDebug exception Machine_Stack_Overflow of int * int exception Dump_Stack_Overflow of int * int exception Env_Overflow of int let run_check run_params (_, e, s, d) = if List.length s > !(run_params.max_stack) then raise (Machine_Stack_Overflow (List.length s, !(run_params.step))) else if dump_length d > !(run_params.max_stack) * !(run_params.max_env) then raise (Dump_Stack_Overflow (dump_length d, !(run_params.step))) else if List.length d > !(run_params.max_stack) then raise (Dump_Stack_Overflow (List.length d, !(run_params.step))) else if env_length e > !(run_params.max_env) then raise (Env_Overflow !(run_params.step)) let run_procedures state = begin (* let () = print_endline "coucou" in *) run_params.step := !(run_params.step)+1; (* if !(run_params.monitor) then gather_metrics run_params state; *) # 405 "exec.cppo.ml" if !(run_params.debug) then print_debug_run run_params state; (* run_check run_params state; *) # 408 "exec.cppo.ml" (* #ifdef STEPMODE *) let ref_state = ref state in if !(run_params.step_mode) && !(run_params.step) >= !(run_params.step_start) then begin run_params.debug := true; let cmd = read_line () in if cmd = "b" then (begin ref_state := List.hd run_params.states; run_params.states <- List.tl run_params.states; run_params.step := !(run_params.step)-2 end) else if cmd = "2" then run_params.verbose := 2 else if cmd = "1" then run_params.verbose := 1 else if cmd = "0" then run_params.verbose := 0 else run_params.states <- state :: run_params.states end; !ref_state (* #endif *) (* #ifndef STEPMODE *) (* state *) (* #endif *) end (* let cast : v -> kappa *) let run code env = let rec aux : state -> state = fun state -> # 442 "exec.cppo.ml" (* let () = print_endline "hello" in *) let state = run_procedures state in # 445 "exec.cppo.ml" (* #ifdef MONITOR *) (* let () = print_endline "coucou" in *) (* gather_metrics run_params state; *) (* #endif *) match state with | c, `FAIL ::e, s, d -> aux ([],empty_env,`FAIL::s,Frame(c,e)::d) | ACC n :: c, e, s, d -> aux (c, e, (access e n) :: s, d) | CST b :: c, e, s, d -> aux (c, e, `CST b :: s, d) | CLS (c', k) :: c, e, s, d -> let rec cls = `CLS (c',cls::e,k,Static) in aux (c, e, cls::s, d) | TYP k :: c, e, s, d -> aux (c, e, `TYP k :: s, d) | APP :: c, e, v :: `CLS (c', e', _, Static) :: s, d -> let ( ) = print_endline " \n=====\nDebug : " in let ( ) = Printf.printf " Dump extended with code : % s " ( show_bytecode 1 c ) in let ( ) = Printf.printf " and environment e[%i ] = % s " ( e ) ( show_env 1 e ) in let () = Printf.printf "Dump extended with code: %s" (show_bytecode 1 c) in let () = Printf.printf "and environment e[%i] = %s" (List.length e) (show_env 1 e) in *) aux (c', v :: e', s, Frame (c, e) :: d) | APP :: c, e, v :: `CLS (c', e', k, Strict) :: s, d -> let ( ta1,ta2 ) = eval k in let ( ) = print_endline " Debug tau " in let ( ) = print_endline ( show_tau ) in let ( ) = print_endline ( show_tau ) in let tv = v in let () = print_endline "Debug tau" in let () = print_endline (show_tau ta1) in let () = print_endline (show_tau ta2) in let tv = typeof v in *) (* let () = print_endline "Debug typeof v" in *) (* let () = print_endline (show_tau tv) in *) let kr = mk_app k (typeof v) in let ( ) = in let ( ) = print_endline " Debug tau circ bool " in let ( ) = print_endline ( show_tau t1 ) in let ( ) = print_endline ( show_tau t2 ) in let () = print_endline "Debug tau circ bool" in let () = print_endline (show_tau t1) in let () = print_endline (show_tau t2) in *) let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', `TYP kr::s, Frame(CAS::c,e)::d) | APP :: c, e, `CST b :: `FCST o :: s, d -> let b' = o b in aux (c, e, `CST b' :: s, d) | TAP :: _, _, v :: `CLS (c', e', _, Static) :: s, d -> aux (c', v :: e', s, d) | TAP :: _, e, `CST c :: `FCST o :: s, d -> let c' = o c in aux ([RET], e, `CST c' :: s, d) | TAP :: _, _, v :: `CLS (c', e', k, Strict) :: s, d -> let kr = mk_app k (typeof v) in let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', s, dump kr d) | RET :: c, e, v :: s, Boundary k :: d -> aux (CAS :: RET :: c, e, v :: `TYP k :: s, d) | RET :: _, _, v :: s, Frame (c', e') :: d -> aux (c', e', v :: s, d) | TCA k::_, _, v::`CLS (c',e',_,Static)::s, d -> aux (c', v::e', s, dump k d) | TCA k :: _, _, v :: `CLS (c',e',k',Strict) :: s, d -> let kr = mk_app k' (typeof v) in let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', s, dump (compose k kr) d) aux ( ( compose ): : c , e , v::`TYP kd::`CLS ( c',e',k',Static ) : : s , d ) | CAS : : c , e , ` CST b : : ` TYP k : : s , d - > let t = eval_1 k in if subtype ( constant b ) ( ceil t ) then aux ( c , e , ` CST b : : s , d ) else aux ( [ ] , empty_env , ` FAIL : : s , Frame ( c , e ) : : d ) | CAS : : c , e , ` CLS ( c',e',k , _ ) : : ` TYP k ' : : s , d - > let t2 ' = eval_2 k ' in if is_bottom t2 ' then aux ( [ ] , empty_env , ` FAIL : : s , Frame ( c , e ) : : d ) else let kc = compose k k ' in aux ( c , e , ` CLS ( c',e',kc , Strict ) : : s , d ) let t = eval_1 k in if subtype (constant b) (ceil t) then aux (c, e, `CST b :: s, d) else aux ([], empty_env, `FAIL :: s, Frame (c, e) :: d) | CAS :: c, e, `CLS (c',e',k,_) :: `TYP k':: s, d -> let t2' = eval_2 k' in if is_bottom t2' then aux ([], empty_env, `FAIL :: s, Frame (c, e) :: d) else let kc = compose k k' in aux (c, e, `CLS (c',e',kc,Strict) :: s, d) *) | CAS :: c, e, v :: `TYP k:: s, d -> let v' = applycast v k in begin match v' with | `FAIL -> aux ([], empty_env, `FAIL :: s, Frame (c,e) :: d) | _ -> aux (c, e, v'::s, d) end | LET :: c, e, v :: s, d -> aux (c, v :: e, s, d) | END :: c, _ :: e, s, d -> aux (c, e, s, d) | MKP :: c, e, v2 :: v1 :: s, d -> aux (c, e, `PAIR (v1, v2) :: s, d) | FST :: c, e, `PAIR (v1, _) :: s, d -> aux (c, e, v1 :: s, d) | SND :: c, e, `PAIR (_, v2) :: s, d -> aux (c, e, v2 :: s, d) | SUC :: c, e, `CST (Integer i) :: s, d -> aux (c, e, `CST (Integer (succ i)) :: s, d) | PRE :: c, e, `CST (Integer i) :: s, d -> aux (c, e, `CST (Integer (pred i)) :: s, d) | MUL :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (mult i1 i2)) :: s, d) | EQB :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> let ieq = if i1 = i2 then zero else one in aux (c, e, `CST ieq :: s, d) | EQB :: c, e, `CST b1 :: `CST b2 :: s, d -> let ieq = if b1 = b2 then zero else one in aux (c, e, `CST ieq :: s, d) | EQB :: c, e, v1 :: v2 :: s, d -> let ieq = if v1 = v2 then zero else one in aux (c, e, `CST ieq :: s, d) | ADD :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (add i1 i2)) :: s, d) | DIV :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (div i2 i1)) :: s, d) | MOD :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (i2 mod i1)) :: s, d) | SUB :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (sub i2 i1)) :: s, d) | MKA :: c, e, `CST (Integer n) :: s, d -> let v = Array.make (CD.Intervals.V.get_int n) zero in aux (c, e, `ARR v :: s, d) | GET :: c, e, `CST (Integer i) :: `ARR a :: s, d -> let v = a.(CD.Intervals.V.get_int i) in aux (c, e, `CST v :: s, d) | SET::c,e,`CST(Integer i)::`ARR a::`CST v::s, d -> let () = Array.set a (CD.Intervals.V.get_int i) v in aux (c, e, s , d) | IFZ (c1, _) :: c, e, `CST b :: s, d when b = Primitives.zero -> aux (c1 @ c, e, s, d) | IFZ (_, c2) :: c, e, _ :: s, d -> aux (c2 @ c, e, s, d) | s -> s in aux (code, env, [], []) end open Transitions open MetricsDebug open Print let run_init code = # 622 "exec.cppo.ml" let () = if !(run_params.debug) then print_endline "Run initialization" in # 624 "exec.cppo.ml" run code [] let finish = function | _, _, [v], _ -> v | [], _, `FAIL::_,_ -> `FAIL | c, _, s, d -> begin print_endline (show_bytecode 1 c); print_endline (show_stack s 1); print_endline (show_dump 1 d); failwith "unfinished computation" end (* | _ -> failwith "no return value" *) let wrap_run : bytecode -> parameters_structure -> unit = fun code params -> # 641 "exec.cppo.ml" begin (if !(params.debug) then Printf.printf "Bytecode:\n%s" (show_bytecode 1 code)); run_params.debug := !(params.debug); run_params.verbose := !(params.verbose); run_params.step_mode := !(params.step_mode); run_params.monitor := !(params.monitor); run_params.step_start := !(params.step_start) end; # 650 "exec.cppo.ml" let v = finish (run_init code) in # 652 "exec.cppo.ml" let () = # 654 "exec.cppo.ml" print_string "- : " ; print_string @@ show_result v; print_endline "" # 656 "exec.cppo.ml" in if !(params.monitor) then begin print_endline "\n===Monitor===\n=============\n"; let met = run_params.metrics in let print_max (ls,fmt) = let (step_max, size_max) = max cmp_tuple ls in Printf.printf fmt (string_of_int size_max) (string_of_int step_max) in let _ = List.map print_max [met.stack_sizes, "Stack max size: %s at step %s\n"; met.dump_sizes, "Dump env max size: %s at step %s\n"; met.dump_frames, "Dump length max : %s at step %s\n"; met.dump_bounds, "Dump casts max : %s at step %s\n"; met.longest_proxies, "Longest proxy size: %s at step %s\n" ; met.casts, "Largest amount of casts size: %s at step %s\n" ; met.env_sizes, "Env max size: %s at step %s\n"] in (); (* let () = print_endline "debug" in *) let instr_counts = met.instructions in let l_instr_counts = List.of_seq (MetricsEnv.to_seq instr_counts) in List.iter (fun (by, cnt) -> printf "\n%i %s" cnt (show_byte 0 by)) l_instr_counts; print_endline "\n=============\n============="; run_params.metrics <- init_metrics () end # 684 "exec.cppo.ml" end module Machine = Make_Machine(Bytecode_Eager) module Machine_Symbolic = Make_Machine(Bytecode_Symbolic) module Machine_Symbolic_Cap = Make_Machine(Bytecode_Symbolic_Cap)
null
https://raw.githubusercontent.com/gldubc/cast-machine/34d79c324cd0a9aff52865ead19e74126b96daaa/src/exec.ml
ocaml
#define MONITOR "1" machine values type nu = [ | `CST of b | `CLS of var * bytecode * env * kappa * mark | `PAIR of nu * nu ] parameter functions let () = print_endline "coucou" in let () = print_endline "coucou" in if !(run_params.monitor) then gather_metrics run_params state; run_check run_params state; #ifdef STEPMODE #endif #ifndef STEPMODE state #endif let cast : v -> kappa let () = print_endline "hello" in #ifdef MONITOR let () = print_endline "coucou" in gather_metrics run_params state; #endif let () = print_endline "Debug typeof v" in let () = print_endline (show_tau tv) in | _ -> failwith "no return value" let () = print_endline "debug" in
# 1 "exec.cppo.ml" open Primitives open Utils open Bytecode open Types open Types.Print open Bytecode_Eager open Syntax.Eager # define BENCH " 1 " # define DEBUG " 1 " module Env = struct include . Make(struct ` type ` t = var let equal = ( =) let hash = Hashtbl.hash end ) end include Hashtbl.Make(struct `type `t = var let equal = (=) let hash = Hashtbl.hash end) end *) module type Structures = sig type result type stack_item type stack type dump type env type state = bytecode * env * stack * dump type nu val empty_env : env val typeof : stack_item -> tau end module Make_Machine (B : Bytecode) = struct open B type result = [ | `CST of b | `Fail ] and stack_item = [ `CST of b | `FCST of (b -> b) | `CLS of bytecode * env * kappa * mark | `ACLS of int * bytecode * env * kappa * mark | `TYP of kappa | `ARR of b array | `FAIL | `PAIR of stack_item * stack_item ] and env = stack_item list type stack = stack_item list let access e n = List.nth e n let empty_env : env = [] type dump_item = | Boundary of kappa | Frame of bytecode * env type dump = dump_item list type state = bytecode * env * stack * dump let n_t_dyn = neg t_dyn let rec typeof : stack_item -> t = function | `CST b -> cap (constant b) (t_dyn) | `CLS (_, _, k, _) -> eval_1 k | `ACLS (_,_,_,k,_) -> eval_1 k | `PAIR (v1, v2) -> pair (typeof v1) (typeof v2) | _ -> failwith "error: trying to take typeof of `TYP or `FAIL" let compose : kappa - > kappa - > kappa = fun k1 k2 - > let ( ) = in let ( t3,t4 ) = eval k2 in mk_kappa ( ( cap t1 t3 ) , ( cap t2 t4 ) ) let (t1,t2) = eval k1 in let (t3,t4) = eval k2 in mk_kappa ((cap t1 t3), (cap t2 t4)) *) let dump : kappa -> dump -> dump = fun k -> function | [] -> [Boundary k] | Boundary k' :: d' -> Boundary (compose k k') :: d' | (Frame _ :: _) as d -> Boundary k :: d let rec applycast : stack_item -> kappa -> stack_item = fun v k -> let (t,td) = eval k in begin match v with | `CST b -> if subtype (constant b) (ceil t) then `CST b else `FAIL | `PAIR (v1, v2) -> let t1, t2 = pi1 t, pi2 t in let k1, k2 = mk_kappa (t1,dom t1), mk_kappa (t2,dom t2) in let cv1 = applycast v1 k1 in let cv2 = applycast v2 k2 in begin match cv1, cv2 with | `FAIL, _ -> `FAIL | _, `FAIL -> `FAIL | _ -> `PAIR (cv1, cv2) end | `CLS (c,e,k',_) -> if td = t_bot then `FAIL else let kc = compose k k' in `CLS (c,e,kc,Strict) | `ACLS (n,c,e,k',_) -> if td = t_bot then `FAIL else let kc = compose k k' in `ACLS (n,c,e,kc,Strict) | _ -> failwith "wrong object to be cast" end module Print = struct let rec show_stack_value : stack_item -> string = function | `CST b -> pp_b b | `FCST _ -> "" | `CLS (btc, env, ts, m) -> Printf.sprintf "C(%s, %s, %s, %s)" (show_bytecode 2 btc) (show_env 1 env) (show_kappa ts) (show_mark m) | `ACLS (n,btc, env, ts, m) -> Printf.sprintf "C_%i(%s, %s, %s, %s)" n (show_bytecode 2 btc) (show_env 1 env) (show_kappa ts) (show_mark m) | `TYP k -> show_kappa k | `FAIL -> "Fail" | `PAIR (v1, v2) -> Printf.sprintf "(%s, %s)" (show_stack_value v1) (show_stack_value v2) | `ARR _ ->"[a]" and sh_env_v : int -> stack_item -> string = function | 2 -> show_stack_value | 0 -> (fun _ -> "_") | 1 -> show_stack_value_1 | _ -> failwith "wrong verbose argument" and show_result : stack_item -> string = function | `CST b -> Printf.sprintf "%s = %s" (show_tau (constant b)) (pp_b b) | `CLS (_,_, k,_) -> let t = eval_1 k in Printf.sprintf "%s = <fun>" (show_tau t) | `FAIL -> "Fail" | `PAIR (v1, v2) as v -> Printf.sprintf "%s = (%s, %s)" (show_tau @@ typeof v) (show_result v1) (show_result v2) | `ARR _ -> "[a]" | _ -> failwith "not a return value" and show_env verb ?inline:(i=true) : env -> string = fun e -> let sep = if i then " . " else "\n\t " in String.concat sep (List.map (fun v -> sh_env_v verb v) e) fun verb inline env - > let lenv = List.of_seq ( Env.to_seq env ) in let sep = if inline then " . " else " \n\t " in if lenv = [ ] then " { } " else " { " ^ String.concat sep ( List.map ( fun ( v , sv ) - > Printf.sprintf " ( % s : = % s ) " ( pp_var v ) ( sh_env_v verb sv ) ) lenv ) ^ " } " let lenv = List.of_seq (Env.to_seq env) in let sep = if inline then " . " else "\n\t " in if lenv = [] then "{}" else "{ " ^ String.concat sep (List.map (fun (v,sv) -> Printf.sprintf "(%s := %s)" (pp_var v) (sh_env_v verb sv)) lenv) ^ " }" *) and show_dump_item verb : dump_item -> string = function | Boundary t -> Printf.sprintf "<%s>" (show_kappa t) | Frame (_,e) -> Printf.sprintf "([code], %s)" (show_env verb e) and show_dump verb : dump -> string = fun d -> (String.concat "\n\n\t " (List.map (show_dump_item verb) d)) and show_stack_value_1 : stack_item -> string = function | `CST b -> pp_b b | `CLS (c,env,bnd,_) -> Printf.sprintf "[c[%i],e[%i],%s]" (List.length c) (List.length env) (show_kappa bnd) | `TYP t -> show_kappa t | `FAIL -> "Fail" | `PAIR (v1, v2) -> Printf.sprintf "(%s, %s)" (show_stack_value_1 v1) (show_stack_value_1 v2) | `ARR a -> "[" ^ (String.concat ";" (Array.to_list ( Array.map (fun v -> pp_b v) a ))) ^ "]" | _->"not implem" let show_stack s verbose = let show_stack_val = begin match verbose with | 2 -> show_stack_value | 1 -> show_stack_value_1 | 0 -> fun _ -> "" | _ -> failwith "wrong verbose argument" end in Printf.sprintf "[ %s ]" (String.concat "\n\t " (List.map show_stack_val s)) end module MetricsDebug = struct open Print module MetricsEnv = Hashtbl.Make(struct type t = byte let equal a b = match a, b with | ACC _, ACC _ | CST _, CST _ | CLS _, CLS _ | LET , LET | TYP _, TYP _ | END , END | TCA _, TCA _ | IFZ _, IFZ _ -> true | _ -> a = b let hash = Hashtbl.hash end) type metrics = {mutable stack_sizes : (int * int) list; mutable longest_proxies : (int * int) list; mutable casts : (int * int) list; instructions : int MetricsEnv.t; mutable dump_sizes : (int * int) list; mutable env_sizes : (int * int) list; mutable dump_frames : (int * int) list; mutable dump_bounds : (int * int) list; } type run_params = {run : bool ref; step : int ref; max_stack : int ref; max_env : int ref; verbose : int ref; delim : int ref; debug : bool ref; step_mode : bool ref; step_start : int ref; monitor : bool ref; mutable states : state list; mutable metrics : metrics} let init_metrics : unit -> metrics = fun () -> {stack_sizes = []; longest_proxies = []; casts = []; instructions = MetricsEnv.create 20; dump_sizes = []; env_sizes = []; dump_frames = []; dump_bounds = [] } let run_params = {run = ref true; step = ref 0; max_stack = ref 1000; max_env = ref 1000; verbose = ref 2; delim = ref 2; debug = ref true; step_mode = ref false; step_start = ref 0; monitor = ref false; states = []; metrics = init_metrics ()} let count_cast : stack -> int = let rec aux acc = function | [] -> acc | `TYP _ :: s -> aux (acc+1) s | _ :: s -> aux acc s in aux 0 let count_bound dmp : int = List.fold_left (fun n e -> match e with | Boundary _ -> n+1 | _ -> n) 0 dmp let longest_proxy : stack -> int = let rec aux max acc = function | [] -> max | `TYP _ :: s when acc+1 > max -> aux (acc+1) (acc+1) s | `TYP _ :: s -> aux max (acc+1) s | _ :: s -> aux max 0 s in aux 0 0 let env_length : env -> int = List.length let dump_length d = List.fold_left (fun n -> function | Frame (_,e) -> env_length e + n | _ -> n) 0 d let dump_frame_length d = List.length d let gather_metrics : run_params -> state -> unit = fun run_params -> let met = run_params.metrics in fun (c, e, s, d) -> begin met.dump_bounds<- (!(run_params.step), count_bound d) :: met.dump_bounds; met.env_sizes <- (!(run_params.step), List.length e) :: met.env_sizes; met.stack_sizes <- (!(run_params.step), (List.length s)) :: met.stack_sizes; met.dump_sizes <- (!(run_params.step), dump_length d) :: met.dump_sizes; met.dump_frames <- (!(run_params.step), dump_frame_length d) :: met.dump_frames; met.longest_proxies <- (!(run_params.step), (longest_proxy s)) :: met.longest_proxies; met.casts <- (!(run_params.step), (count_cast s)) :: met.casts; run_params.metrics <- met; if c != [] then let instr = List.hd c in let cnt_inst = (try MetricsEnv.find met.instructions instr with Not_found -> 0) in let () = Printf.printf "counting one instruction %s" (show_byte 1 instr) in MetricsEnv.replace met.instructions instr (cnt_inst+1) end let delim n i = let si = string_of_int i in let d = String.length si in String.init (n+1-d) (fun _ -> ' ') let rec firstk k xs = match xs with | [] -> [] | x::xs -> if k=1 then [x] else x::firstk (k-1) xs;; let print_debug_stack run_params s = let stack_size = List.length s in if !(run_params.verbose) >= 1 then let d = delim !(run_params.delim) stack_size in let ssize = string_of_int stack_size in let strstack = show_stack (firstk 20 s) !(run_params.verbose) in Printf.printf "Stack[%s]:%s%s\n" ssize d strstack else Printf.printf "Stack[%i]\n" (stack_size) let print_debug_code run_params s = let stack_size = List.length s in if !(run_params.verbose) >= 1 then Printf.printf "Code [%i]:%s%s\n" (stack_size) (delim !(run_params.delim) stack_size) (show_bytecode !(run_params.verbose) (firstk 7 s)) else Printf.printf "Code [%i]\n" (stack_size) let print_debug_env run_params s = let stack_size = env_length s in if stack_size < 20 && !(run_params.verbose) >= 1 then Printf.printf "Env [%i]:%s%s\n" (stack_size) (delim !(run_params.delim) stack_size) (show_env !(run_params.verbose) ~inline:false s) else Printf.printf "Env [%i]\n" (stack_size) let print_debug_dump run_params s = let stack_size = dump_length s in if !(run_params.verbose) >= 1 then Printf.printf "Dump [%i][%i][#casts=%i]:\n\t %s%s\n" (List.length s) (stack_size) (count_bound s) (delim !(run_params.delim) stack_size) (show_dump !(run_params.verbose) (firstk 4 s)) else Printf.printf "Dump [%i][%i][casts=%i]\n" (List.length s) (stack_size) (count_bound s) let print_debug_run run_params = function | c, e, s, d -> Printf.printf "==={%i}========================================================================\n" !(run_params.step); Stdlib.flush stdout; print_debug_code run_params c; Stdlib.flush stdout; print_endline ""; print_debug_stack run_params s; Stdlib.flush stdout; print_endline ""; print_debug_env run_params e; Stdlib.flush stdout; print_endline ""; print_debug_dump run_params d; Stdlib.flush stdout end module Transitions = struct open MetricsDebug exception Machine_Stack_Overflow of int * int exception Dump_Stack_Overflow of int * int exception Env_Overflow of int let run_check run_params (_, e, s, d) = if List.length s > !(run_params.max_stack) then raise (Machine_Stack_Overflow (List.length s, !(run_params.step))) else if dump_length d > !(run_params.max_stack) * !(run_params.max_env) then raise (Dump_Stack_Overflow (dump_length d, !(run_params.step))) else if List.length d > !(run_params.max_stack) then raise (Dump_Stack_Overflow (List.length d, !(run_params.step))) else if env_length e > !(run_params.max_env) then raise (Env_Overflow !(run_params.step)) let run_procedures state = begin run_params.step := !(run_params.step)+1; # 405 "exec.cppo.ml" if !(run_params.debug) then print_debug_run run_params state; # 408 "exec.cppo.ml" let ref_state = ref state in if !(run_params.step_mode) && !(run_params.step) >= !(run_params.step_start) then begin run_params.debug := true; let cmd = read_line () in if cmd = "b" then (begin ref_state := List.hd run_params.states; run_params.states <- List.tl run_params.states; run_params.step := !(run_params.step)-2 end) else if cmd = "2" then run_params.verbose := 2 else if cmd = "1" then run_params.verbose := 1 else if cmd = "0" then run_params.verbose := 0 else run_params.states <- state :: run_params.states end; !ref_state end let run code env = let rec aux : state -> state = fun state -> # 442 "exec.cppo.ml" let state = run_procedures state in # 445 "exec.cppo.ml" match state with | c, `FAIL ::e, s, d -> aux ([],empty_env,`FAIL::s,Frame(c,e)::d) | ACC n :: c, e, s, d -> aux (c, e, (access e n) :: s, d) | CST b :: c, e, s, d -> aux (c, e, `CST b :: s, d) | CLS (c', k) :: c, e, s, d -> let rec cls = `CLS (c',cls::e,k,Static) in aux (c, e, cls::s, d) | TYP k :: c, e, s, d -> aux (c, e, `TYP k :: s, d) | APP :: c, e, v :: `CLS (c', e', _, Static) :: s, d -> let ( ) = print_endline " \n=====\nDebug : " in let ( ) = Printf.printf " Dump extended with code : % s " ( show_bytecode 1 c ) in let ( ) = Printf.printf " and environment e[%i ] = % s " ( e ) ( show_env 1 e ) in let () = Printf.printf "Dump extended with code: %s" (show_bytecode 1 c) in let () = Printf.printf "and environment e[%i] = %s" (List.length e) (show_env 1 e) in *) aux (c', v :: e', s, Frame (c, e) :: d) | APP :: c, e, v :: `CLS (c', e', k, Strict) :: s, d -> let ( ta1,ta2 ) = eval k in let ( ) = print_endline " Debug tau " in let ( ) = print_endline ( show_tau ) in let ( ) = print_endline ( show_tau ) in let tv = v in let () = print_endline "Debug tau" in let () = print_endline (show_tau ta1) in let () = print_endline (show_tau ta2) in let tv = typeof v in *) let kr = mk_app k (typeof v) in let ( ) = in let ( ) = print_endline " Debug tau circ bool " in let ( ) = print_endline ( show_tau t1 ) in let ( ) = print_endline ( show_tau t2 ) in let () = print_endline "Debug tau circ bool" in let () = print_endline (show_tau t1) in let () = print_endline (show_tau t2) in *) let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', `TYP kr::s, Frame(CAS::c,e)::d) | APP :: c, e, `CST b :: `FCST o :: s, d -> let b' = o b in aux (c, e, `CST b' :: s, d) | TAP :: _, _, v :: `CLS (c', e', _, Static) :: s, d -> aux (c', v :: e', s, d) | TAP :: _, e, `CST c :: `FCST o :: s, d -> let c' = o c in aux ([RET], e, `CST c' :: s, d) | TAP :: _, _, v :: `CLS (c', e', k, Strict) :: s, d -> let kr = mk_app k (typeof v) in let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', s, dump kr d) | RET :: c, e, v :: s, Boundary k :: d -> aux (CAS :: RET :: c, e, v :: `TYP k :: s, d) | RET :: _, _, v :: s, Frame (c', e') :: d -> aux (c', e', v :: s, d) | TCA k::_, _, v::`CLS (c',e',_,Static)::s, d -> aux (c', v::e', s, dump k d) | TCA k :: _, _, v :: `CLS (c',e',k',Strict) :: s, d -> let kr = mk_app k' (typeof v) in let kd = mk_dom k in let v' = applycast v kd in aux (c', v'::e', s, dump (compose k kr) d) aux ( ( compose ): : c , e , v::`TYP kd::`CLS ( c',e',k',Static ) : : s , d ) | CAS : : c , e , ` CST b : : ` TYP k : : s , d - > let t = eval_1 k in if subtype ( constant b ) ( ceil t ) then aux ( c , e , ` CST b : : s , d ) else aux ( [ ] , empty_env , ` FAIL : : s , Frame ( c , e ) : : d ) | CAS : : c , e , ` CLS ( c',e',k , _ ) : : ` TYP k ' : : s , d - > let t2 ' = eval_2 k ' in if is_bottom t2 ' then aux ( [ ] , empty_env , ` FAIL : : s , Frame ( c , e ) : : d ) else let kc = compose k k ' in aux ( c , e , ` CLS ( c',e',kc , Strict ) : : s , d ) let t = eval_1 k in if subtype (constant b) (ceil t) then aux (c, e, `CST b :: s, d) else aux ([], empty_env, `FAIL :: s, Frame (c, e) :: d) | CAS :: c, e, `CLS (c',e',k,_) :: `TYP k':: s, d -> let t2' = eval_2 k' in if is_bottom t2' then aux ([], empty_env, `FAIL :: s, Frame (c, e) :: d) else let kc = compose k k' in aux (c, e, `CLS (c',e',kc,Strict) :: s, d) *) | CAS :: c, e, v :: `TYP k:: s, d -> let v' = applycast v k in begin match v' with | `FAIL -> aux ([], empty_env, `FAIL :: s, Frame (c,e) :: d) | _ -> aux (c, e, v'::s, d) end | LET :: c, e, v :: s, d -> aux (c, v :: e, s, d) | END :: c, _ :: e, s, d -> aux (c, e, s, d) | MKP :: c, e, v2 :: v1 :: s, d -> aux (c, e, `PAIR (v1, v2) :: s, d) | FST :: c, e, `PAIR (v1, _) :: s, d -> aux (c, e, v1 :: s, d) | SND :: c, e, `PAIR (_, v2) :: s, d -> aux (c, e, v2 :: s, d) | SUC :: c, e, `CST (Integer i) :: s, d -> aux (c, e, `CST (Integer (succ i)) :: s, d) | PRE :: c, e, `CST (Integer i) :: s, d -> aux (c, e, `CST (Integer (pred i)) :: s, d) | MUL :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (mult i1 i2)) :: s, d) | EQB :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> let ieq = if i1 = i2 then zero else one in aux (c, e, `CST ieq :: s, d) | EQB :: c, e, `CST b1 :: `CST b2 :: s, d -> let ieq = if b1 = b2 then zero else one in aux (c, e, `CST ieq :: s, d) | EQB :: c, e, v1 :: v2 :: s, d -> let ieq = if v1 = v2 then zero else one in aux (c, e, `CST ieq :: s, d) | ADD :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (add i1 i2)) :: s, d) | DIV :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (div i2 i1)) :: s, d) | MOD :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (i2 mod i1)) :: s, d) | SUB :: c, e, `CST (Integer i1) :: `CST (Integer i2) :: s, d -> aux (c, e, `CST (Integer (sub i2 i1)) :: s, d) | MKA :: c, e, `CST (Integer n) :: s, d -> let v = Array.make (CD.Intervals.V.get_int n) zero in aux (c, e, `ARR v :: s, d) | GET :: c, e, `CST (Integer i) :: `ARR a :: s, d -> let v = a.(CD.Intervals.V.get_int i) in aux (c, e, `CST v :: s, d) | SET::c,e,`CST(Integer i)::`ARR a::`CST v::s, d -> let () = Array.set a (CD.Intervals.V.get_int i) v in aux (c, e, s , d) | IFZ (c1, _) :: c, e, `CST b :: s, d when b = Primitives.zero -> aux (c1 @ c, e, s, d) | IFZ (_, c2) :: c, e, _ :: s, d -> aux (c2 @ c, e, s, d) | s -> s in aux (code, env, [], []) end open Transitions open MetricsDebug open Print let run_init code = # 622 "exec.cppo.ml" let () = if !(run_params.debug) then print_endline "Run initialization" in # 624 "exec.cppo.ml" run code [] let finish = function | _, _, [v], _ -> v | [], _, `FAIL::_,_ -> `FAIL | c, _, s, d -> begin print_endline (show_bytecode 1 c); print_endline (show_stack s 1); print_endline (show_dump 1 d); failwith "unfinished computation" end let wrap_run : bytecode -> parameters_structure -> unit = fun code params -> # 641 "exec.cppo.ml" begin (if !(params.debug) then Printf.printf "Bytecode:\n%s" (show_bytecode 1 code)); run_params.debug := !(params.debug); run_params.verbose := !(params.verbose); run_params.step_mode := !(params.step_mode); run_params.monitor := !(params.monitor); run_params.step_start := !(params.step_start) end; # 650 "exec.cppo.ml" let v = finish (run_init code) in # 652 "exec.cppo.ml" let () = # 654 "exec.cppo.ml" print_string "- : " ; print_string @@ show_result v; print_endline "" # 656 "exec.cppo.ml" in if !(params.monitor) then begin print_endline "\n===Monitor===\n=============\n"; let met = run_params.metrics in let print_max (ls,fmt) = let (step_max, size_max) = max cmp_tuple ls in Printf.printf fmt (string_of_int size_max) (string_of_int step_max) in let _ = List.map print_max [met.stack_sizes, "Stack max size: %s at step %s\n"; met.dump_sizes, "Dump env max size: %s at step %s\n"; met.dump_frames, "Dump length max : %s at step %s\n"; met.dump_bounds, "Dump casts max : %s at step %s\n"; met.longest_proxies, "Longest proxy size: %s at step %s\n" ; met.casts, "Largest amount of casts size: %s at step %s\n" ; met.env_sizes, "Env max size: %s at step %s\n"] in (); let instr_counts = met.instructions in let l_instr_counts = List.of_seq (MetricsEnv.to_seq instr_counts) in List.iter (fun (by, cnt) -> printf "\n%i %s" cnt (show_byte 0 by)) l_instr_counts; print_endline "\n=============\n============="; run_params.metrics <- init_metrics () end # 684 "exec.cppo.ml" end module Machine = Make_Machine(Bytecode_Eager) module Machine_Symbolic = Make_Machine(Bytecode_Symbolic) module Machine_Symbolic_Cap = Make_Machine(Bytecode_Symbolic_Cap)
299f819b6bc15bada800d2f8f100420178248e6d761da4ec7b9be10af9452793
ijvcms/chuanqi_dev
service_base.erl
%%%------------------------------------------------------------------- @author zhengsiying ( C ) 2015 , < COMPANY > %%% @doc %%% 基础服务:一般是每个节点都需要的服务 %%% @end Created : 07 . 三月 2015 17:13 %%%------------------------------------------------------------------- -module(service_base). -include("common.hrl"). %% API -export([ start/0 ]). %% ==================================================================== %% API functions %% ==================================================================== start() -> db:init(), error_logger:add_report_handler(logger_handle), ModList = [{misc_timer}, {mod_randseed},{dp_sup},{mod_ets_holder_sup}],%% misc_timer 时间-时间戳 mod_ranseed 随机数 ok = util:start_mod(permanent, ModList), ok. %% ==================================================================== Internal functions %% ====================================================================
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/service/service_base.erl
erlang
------------------------------------------------------------------- @doc 基础服务:一般是每个节点都需要的服务 @end ------------------------------------------------------------------- API ==================================================================== API functions ==================================================================== misc_timer 时间-时间戳 mod_ranseed 随机数 ==================================================================== ====================================================================
@author zhengsiying ( C ) 2015 , < COMPANY > Created : 07 . 三月 2015 17:13 -module(service_base). -include("common.hrl"). -export([ start/0 ]). start() -> db:init(), error_logger:add_report_handler(logger_handle), ok = util:start_mod(permanent, ModList), ok. Internal functions
8aad2403f737eed85ca57d1d4f673369c2ded8452e780e54237896885a64b995
heyoka/faxe
esp_state_sequence.erl
%% Date: 15.07.2019 - 09:55 Ⓒ 2019 heyoka %% @doc %% This node takes a list of lambda expressions representing different states. %% It is used to impose a strict sequence of events on the data, that is seen to be valid for further processing. %% %% The node will emit values only after each state has evaluated as true in the given order and, for each step in the sequence %% within the corresponding timeout. %% You must define a timeout for every state transition with the 'within' parameter. %% If a timeout occurs at any point the sequence will be reset and started from the first expression again . %% Note that the sequence timeouts start after the first datapoint has satisfied the first lambda expression . Therefore , if 3 lambda states are given , only 2 durations for the ' within ' parameter can be defined . %% %% With the 'strict' parameter the sequence of states must be met exactly without any datapoints in between, %% that do not satisfy the current state expression. %% Without strict mode, this would not reset the sequence of evaluation. %% %% On a successful evaluation of the whole sequence, %% the node will simply output the last value, that completed the sequence. %% The state_sequence node can be used with one or many input nodes . %% @todo implement output mode : ie merge for all output points %% -module(esp_state_sequence). -author("Alexander Minichmair"). %% API -behavior(df_component). -include("faxe.hrl"). %% API -export([init/3, process/3, options/0, handle_info/2, wants/0, emits/0]). -record(state, { node_id, lambdas, durations, current_index, tref, is_strict = false }). options() -> [ {states, lambda_list}, {within, duration_list}, {strict, is_set, false}, {output, string, <<"last">>} ]. wants() -> point. emits() -> point. init(_NodeId, _Ins, #{states := Lambdas, within := DurList0, strict := Strict}) -> DurList = [faxe_time:duration_to_ms(Dur) || Dur <- DurList0], {ok, all, #state{lambdas = Lambdas, durations = DurList, current_index = 1, is_strict = Strict}}. process(_In, #data_batch{points = _Points} = _Batch, _State = #state{lambdas = _Lambda}) -> {error, not_implemented}; process(_Inport, #data_point{} = Point, State = #state{current_index = Index, lambdas = Lambdas}) -> lager : notice("in on port : ~p ~ n ~ p",[_Inport , lager : pr(Point , ? MODULE ) ] ) , case exec(Point, lists:nth(Index, Lambdas)) of true -> eval_true(Point, State); false -> eval_false(State) end. handle_info(state_timeout, State = #state{}) -> %% lager:warning("state_timeout when index: ~p",[State#state.current_index]), {ok, reset(State)}; handle_info(_R, State) -> {ok, State}. exec(Point, LFun) -> faxe_lambda:execute_bool(Point, LFun). eval_true(Point, State = #state{current_index = Current, tref = TRef, lambdas = Lambdas, durations = DurList}) -> %% lager:info("ok, go to next state from (~p)" , [Current]), catch (erlang:cancel_timer(TRef)), case Current == length(Lambdas) of true -> %% lager:notice("done, reset !"), {emit, Point, reset(State)}; false -> lager : notice("start timeout : ~p " , [ lists : nth(Current , DurList ) ] ) , Timer = erlang:send_after(lists:nth(Current, DurList), self(), state_timeout), {ok, State#state{current_index = Current + 1, tref = Timer}} end. eval_false(State = #state{is_strict = true}) -> %% lager:notice("strict, no match: reset!"), {ok, reset(State)}; eval_false(State) -> {ok, State}. reset(State = #state{tref = Timer}) -> catch (erlang:cancel_timer(Timer)), State#state{current_index = 1, tref = undefined}.
null
https://raw.githubusercontent.com/heyoka/faxe/a5d768e1c354e2e76761cd6bd4dd003a8d88339f/apps/faxe/src/components/esp_state_sequence.erl
erlang
Date: 15.07.2019 - 09:55 @doc This node takes a list of lambda expressions representing different states. It is used to impose a strict sequence of events on the data, that is seen to be valid for further processing. The node will emit values only after each state has evaluated as true in the given order and, for each step in the sequence within the corresponding timeout. You must define a timeout for every state transition with the 'within' parameter. With the 'strict' parameter the sequence of states must be met exactly without any datapoints in between, that do not satisfy the current state expression. Without strict mode, this would not reset the sequence of evaluation. On a successful evaluation of the whole sequence, the node will simply output the last value, that completed the sequence. API API lager:warning("state_timeout when index: ~p",[State#state.current_index]), lager:info("ok, go to next state from (~p)" , [Current]), lager:notice("done, reset !"), lager:notice("strict, no match: reset!"),
Ⓒ 2019 heyoka If a timeout occurs at any point the sequence will be reset and started from the first expression again . Note that the sequence timeouts start after the first datapoint has satisfied the first lambda expression . Therefore , if 3 lambda states are given , only 2 durations for the ' within ' parameter can be defined . The state_sequence node can be used with one or many input nodes . @todo implement output mode : ie merge for all output points -module(esp_state_sequence). -author("Alexander Minichmair"). -behavior(df_component). -include("faxe.hrl"). -export([init/3, process/3, options/0, handle_info/2, wants/0, emits/0]). -record(state, { node_id, lambdas, durations, current_index, tref, is_strict = false }). options() -> [ {states, lambda_list}, {within, duration_list}, {strict, is_set, false}, {output, string, <<"last">>} ]. wants() -> point. emits() -> point. init(_NodeId, _Ins, #{states := Lambdas, within := DurList0, strict := Strict}) -> DurList = [faxe_time:duration_to_ms(Dur) || Dur <- DurList0], {ok, all, #state{lambdas = Lambdas, durations = DurList, current_index = 1, is_strict = Strict}}. process(_In, #data_batch{points = _Points} = _Batch, _State = #state{lambdas = _Lambda}) -> {error, not_implemented}; process(_Inport, #data_point{} = Point, State = #state{current_index = Index, lambdas = Lambdas}) -> lager : notice("in on port : ~p ~ n ~ p",[_Inport , lager : pr(Point , ? MODULE ) ] ) , case exec(Point, lists:nth(Index, Lambdas)) of true -> eval_true(Point, State); false -> eval_false(State) end. handle_info(state_timeout, State = #state{}) -> {ok, reset(State)}; handle_info(_R, State) -> {ok, State}. exec(Point, LFun) -> faxe_lambda:execute_bool(Point, LFun). eval_true(Point, State = #state{current_index = Current, tref = TRef, lambdas = Lambdas, durations = DurList}) -> catch (erlang:cancel_timer(TRef)), case Current == length(Lambdas) of true -> {emit, Point, reset(State)}; false -> lager : notice("start timeout : ~p " , [ lists : nth(Current , DurList ) ] ) , Timer = erlang:send_after(lists:nth(Current, DurList), self(), state_timeout), {ok, State#state{current_index = Current + 1, tref = Timer}} end. eval_false(State = #state{is_strict = true}) -> {ok, reset(State)}; eval_false(State) -> {ok, State}. reset(State = #state{tref = Timer}) -> catch (erlang:cancel_timer(Timer)), State#state{current_index = 1, tref = undefined}.
dc7ee291e60c09ef61b831cec55cd74befb57ccc8bed5a1472cfe504b743818f
haskell/array
Internals.hs
# LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses , CPP # CPP #-} # LANGUAGE RoleAnnotations # {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Array.IO.Internal Copyright : ( c ) The University of Glasgow 2001 - 2012 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : non-portable (uses Data.Array.Base) -- Mutable boxed and unboxed arrays in the IO monad . -- ----------------------------------------------------------------------------- module Data.Array.IO.Internals ( instance of : , instance of : , : : IOUArray ix a - > IO ( IOUArray ix b ) unsafeThawIOUArray, unsafeFreezeIOUArray ) where import Data.Int import Data.Word import Data.Typeable import Control.Monad.ST ( RealWorld, stToIO ) import Foreign.Ptr ( Ptr, FunPtr ) import Foreign.StablePtr ( StablePtr ) #if __GLASGOW_HASKELL__ < 711 import Data.Ix #endif import Data.Array.Base import GHC.IOArray (IOArray(..)) ----------------------------------------------------------------------------- -- Flat unboxed mutable arrays (IO monad) -- | Mutable, unboxed, strict arrays in the 'IO' monad. The type -- arguments are as follows: -- -- * @i@: the index type of the array (should be an instance of 'Ix') -- * : the element type of the array . Only certain element types -- are supported: see "Data.Array.MArray" for a list of instances. -- newtype IOUArray i e = IOUArray (STUArray RealWorld i e) deriving Typeable -- Both parameters have class-based invariants. See also #9220. type role IOUArray nominal nominal instance Eq (IOUArray i e) where IOUArray s1 == IOUArray s2 = s1 == s2 instance MArray IOUArray Bool IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Char IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (Ptr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (FunPtr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Float IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Double IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (StablePtr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int8 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int16 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int32 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int64 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word8 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word16 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word32 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word64 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) | Casts an ' IOUArray ' with one element type into one with a -- different element type. All the elements of the resulting array -- are undefined (unless you know what you\'re doing...). castIOUArray :: IOUArray ix a -> IO (IOUArray ix b) castIOUArray (IOUArray marr) = stToIO $ do marr' <- castSTUArray marr return (IOUArray marr') # INLINE unsafeThawIOUArray # #if __GLASGOW_HASKELL__ >= 711 unsafeThawIOUArray :: UArray ix e -> IO (IOUArray ix e) #else unsafeThawIOUArray :: Ix ix => UArray ix e -> IO (IOUArray ix e) #endif unsafeThawIOUArray arr = stToIO $ do marr <- unsafeThawSTUArray arr return (IOUArray marr) # RULES " unsafeThaw / IOUArray " unsafeThaw = unsafeThawIOUArray # "unsafeThaw/IOUArray" unsafeThaw = unsafeThawIOUArray #-} #if __GLASGOW_HASKELL__ >= 711 thawIOUArray :: UArray ix e -> IO (IOUArray ix e) #else thawIOUArray :: Ix ix => UArray ix e -> IO (IOUArray ix e) #endif thawIOUArray arr = stToIO $ do marr <- thawSTUArray arr return (IOUArray marr) # RULES " thaw / IOUArray " thaw = thawIOUArray # "thaw/IOUArray" thaw = thawIOUArray #-} # INLINE unsafeFreezeIOUArray # #if __GLASGOW_HASKELL__ >= 711 unsafeFreezeIOUArray :: IOUArray ix e -> IO (UArray ix e) #else unsafeFreezeIOUArray :: Ix ix => IOUArray ix e -> IO (UArray ix e) #endif unsafeFreezeIOUArray (IOUArray marr) = stToIO (unsafeFreezeSTUArray marr) # RULES " unsafeFreeze / IOUArray " unsafeFreeze = unsafeFreezeIOUArray # "unsafeFreeze/IOUArray" unsafeFreeze = unsafeFreezeIOUArray #-} #if __GLASGOW_HASKELL__ >= 711 freezeIOUArray :: IOUArray ix e -> IO (UArray ix e) #else freezeIOUArray :: Ix ix => IOUArray ix e -> IO (UArray ix e) #endif freezeIOUArray (IOUArray marr) = stToIO (freezeSTUArray marr) {-# RULES "freeze/IOUArray" freeze = freezeIOUArray #-}
null
https://raw.githubusercontent.com/haskell/array/9d63218fd067ff4885c0efa43b388238421a5c89/Data/Array/IO/Internals.hs
haskell
# OPTIONS_HADDOCK hide # --------------------------------------------------------------------------- | Module : Data.Array.IO.Internal License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : non-portable (uses Data.Array.Base) --------------------------------------------------------------------------- --------------------------------------------------------------------------- Flat unboxed mutable arrays (IO monad) | Mutable, unboxed, strict arrays in the 'IO' monad. The type arguments are as follows: * @i@: the index type of the array (should be an instance of 'Ix') are supported: see "Data.Array.MArray" for a list of instances. Both parameters have class-based invariants. See also #9220. different element type. All the elements of the resulting array are undefined (unless you know what you\'re doing...). # RULES "freeze/IOUArray" freeze = freezeIOUArray #
# LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses , CPP # CPP #-} # LANGUAGE RoleAnnotations # Copyright : ( c ) The University of Glasgow 2001 - 2012 Mutable boxed and unboxed arrays in the IO monad . module Data.Array.IO.Internals ( instance of : , instance of : , : : IOUArray ix a - > IO ( IOUArray ix b ) unsafeThawIOUArray, unsafeFreezeIOUArray ) where import Data.Int import Data.Word import Data.Typeable import Control.Monad.ST ( RealWorld, stToIO ) import Foreign.Ptr ( Ptr, FunPtr ) import Foreign.StablePtr ( StablePtr ) #if __GLASGOW_HASKELL__ < 711 import Data.Ix #endif import Data.Array.Base import GHC.IOArray (IOArray(..)) * : the element type of the array . Only certain element types newtype IOUArray i e = IOUArray (STUArray RealWorld i e) deriving Typeable type role IOUArray nominal nominal instance Eq (IOUArray i e) where IOUArray s1 == IOUArray s2 = s1 == s2 instance MArray IOUArray Bool IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Char IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (Ptr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (FunPtr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Float IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Double IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray (StablePtr a) IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int8 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int16 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int32 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Int64 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word8 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word16 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word32 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) instance MArray IOUArray Word64 IO where # INLINE getBounds # getBounds (IOUArray arr) = stToIO $ getBounds arr # INLINE getNumElements # getNumElements (IOUArray arr) = stToIO $ getNumElements arr # INLINE newArray # newArray lu initialValue = stToIO $ do marr <- newArray lu initialValue; return (IOUArray marr) # INLINE unsafeNewArray _ # unsafeNewArray_ lu = stToIO $ do marr <- unsafeNewArray_ lu; return (IOUArray marr) # INLINE newArray _ # newArray_ = unsafeNewArray_ # INLINE unsafeRead # unsafeRead (IOUArray marr) i = stToIO (unsafeRead marr i) # INLINE unsafeWrite # unsafeWrite (IOUArray marr) i e = stToIO (unsafeWrite marr i e) | Casts an ' IOUArray ' with one element type into one with a castIOUArray :: IOUArray ix a -> IO (IOUArray ix b) castIOUArray (IOUArray marr) = stToIO $ do marr' <- castSTUArray marr return (IOUArray marr') # INLINE unsafeThawIOUArray # #if __GLASGOW_HASKELL__ >= 711 unsafeThawIOUArray :: UArray ix e -> IO (IOUArray ix e) #else unsafeThawIOUArray :: Ix ix => UArray ix e -> IO (IOUArray ix e) #endif unsafeThawIOUArray arr = stToIO $ do marr <- unsafeThawSTUArray arr return (IOUArray marr) # RULES " unsafeThaw / IOUArray " unsafeThaw = unsafeThawIOUArray # "unsafeThaw/IOUArray" unsafeThaw = unsafeThawIOUArray #-} #if __GLASGOW_HASKELL__ >= 711 thawIOUArray :: UArray ix e -> IO (IOUArray ix e) #else thawIOUArray :: Ix ix => UArray ix e -> IO (IOUArray ix e) #endif thawIOUArray arr = stToIO $ do marr <- thawSTUArray arr return (IOUArray marr) # RULES " thaw / IOUArray " thaw = thawIOUArray # "thaw/IOUArray" thaw = thawIOUArray #-} # INLINE unsafeFreezeIOUArray # #if __GLASGOW_HASKELL__ >= 711 unsafeFreezeIOUArray :: IOUArray ix e -> IO (UArray ix e) #else unsafeFreezeIOUArray :: Ix ix => IOUArray ix e -> IO (UArray ix e) #endif unsafeFreezeIOUArray (IOUArray marr) = stToIO (unsafeFreezeSTUArray marr) # RULES " unsafeFreeze / IOUArray " unsafeFreeze = unsafeFreezeIOUArray # "unsafeFreeze/IOUArray" unsafeFreeze = unsafeFreezeIOUArray #-} #if __GLASGOW_HASKELL__ >= 711 freezeIOUArray :: IOUArray ix e -> IO (UArray ix e) #else freezeIOUArray :: Ix ix => IOUArray ix e -> IO (UArray ix e) #endif freezeIOUArray (IOUArray marr) = stToIO (freezeSTUArray marr)
781268076d7276fd32deabce287a5e4837b0c5aee70651ee847829f549c0a58d
naveensundarg/prover
closure1.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- ;;; File: closure1.lisp The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations ;;; under the License. ;;; The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 . All Rights Reserved . ;;; Contributor(s ): < > . (in-package :snark) ;;; simple closure algorithm for small deduction tasks ;;; that do not require features like indexing for performance (defun closure1 (items &key done unary-rules binary-rules ternary-rules (subsumption-test #'equal)) ;; compute closure of the union of items and done using rules and subsumption-test ;; if done is given as an argument, it is assumed to be closed already (flet ((unsubsumed (l1 l2 subsumption-test) ;; return items in l2 that are not subsumed by any item in l1 (delete-if #'(lambda (item2) (some #'(lambda (item1) (funcall subsumption-test item1 item2)) l1)) l2))) (let ((todo (make-deque))) (dolist (item items) (deque-push-last todo item)) (loop (when (deque-empty? todo) (return done)) (let ((item1 (deque-pop-first todo))) (when (unsubsumed done (list item1) subsumption-test) (setf done (cons item1 (unsubsumed (list item1) done subsumption-test))) (prog-> (dolist unary-rules ->* rule) (funcall rule item1 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)) (prog-> (dolist binary-rules ->* rule) (dolist done ->* item2) (funcall rule item1 item2 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)) (prog-> (dolist ternary-rules ->* rule) (dolist done ->* item2) (dolist done ->* item3) (funcall rule item1 item2 item3 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)))))))) closure1.lisp EOF
null
https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/closure1.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- File: closure1.lisp Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. simple closure algorithm for small deduction tasks that do not require features like indexing for performance compute closure of the union of items and done using rules and subsumption-test if done is given as an argument, it is assumed to be closed already return items in l2 that are not subsumed by any item in l1
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 . All Rights Reserved . Contributor(s ): < > . (in-package :snark) (defun closure1 (items &key done unary-rules binary-rules ternary-rules (subsumption-test #'equal)) (flet ((unsubsumed (l1 l2 subsumption-test) (delete-if #'(lambda (item2) (some #'(lambda (item1) (funcall subsumption-test item1 item2)) l1)) l2))) (let ((todo (make-deque))) (dolist (item items) (deque-push-last todo item)) (loop (when (deque-empty? todo) (return done)) (let ((item1 (deque-pop-first todo))) (when (unsubsumed done (list item1) subsumption-test) (setf done (cons item1 (unsubsumed (list item1) done subsumption-test))) (prog-> (dolist unary-rules ->* rule) (funcall rule item1 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)) (prog-> (dolist binary-rules ->* rule) (dolist done ->* item2) (funcall rule item1 item2 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)) (prog-> (dolist ternary-rules ->* rule) (dolist done ->* item2) (dolist done ->* item3) (funcall rule item1 item2 item3 ->* new-item) (when (eq :inconsistent new-item) (return-from closure1 new-item)) (deque-push-last todo new-item)))))))) closure1.lisp EOF
ff69856feaa7742cb6e56805a7df7ccc6d23a7c1c8dff3409581090e6e2cb5ca
m4dc4p/haskelldb
WX.hs
----------------------------------------------------------- -- | Module : Database . HaskellDB.WX Copyright : HWT Group 2003 , 2005 - 2006 -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : non-portable -- WxHaskell < / > interface for HaskellDB -- ----------------------------------------------------------- module Database.HaskellDB.WX ( WXOptions(..), wxConnect, DriverInterface(..), driver ) where import Data.Maybe import Control.Exception (catch, throwIO) import Control.Monad import System.IO.Unsafe (unsafeInterleaveIO) import System.Time import Database.HaskellDB import Database.HaskellDB.DriverAPI import Database.HaskellDB.Database import Database.HaskellDB.Sql.Generate (SqlGenerator) import Database.HaskellDB.Sql.Print import Database.HaskellDB.PrimQuery import Database.HaskellDB.Query import Database.HaskellDB.FieldType import Graphics.UI.WXCore.WxcClasses (Db) import Graphics.UI.WXCore.Db (DbRow, ColumnInfo(..),TableInfo(..),SqlType(..)) import qualified Graphics.UI.WXCore.Db as WX type Connection = Db () data WXOptions = WXOptions { ^ name binding in ODBC uid :: String, -- ^ user id pwd :: String -- ^ password } -- | Run an action and close the connection. wxConnect :: SqlGenerator -> WXOptions -> (Database -> IO a) -> IO a wxConnect gen WXOptions{dsn=d,uid=u,pwd=p} action = handleDbError (WX.dbWithConnection d u p (action . mkDatabase gen)) wxConnectOpts :: [(String,String)] -> (Database -> IO a) -> IO a wxConnectOpts opts f = do [a,b,c] <- getOptions ["dsn","uid","pwd"] opts gen <- getGenerator opts wxConnect gen (PostgreSQLOptions {dsn = a, uid = b, pwd = c}) f driver :: DriverInterface driver = defaultdriver {connect = wxConnectOpts} handleDbError :: IO a -> IO a handleDbError io = WX.catchDbError io (fail . WX.dbErrorMsg) mkDatabase :: SqlGenerator -> Connection -> Database mkDatabase gen connection = Database { dbQuery = wxQuery gen connection, dbInsert = wxInsert gen connection, dbInsertQuery = wxInsertQuery gen connection, dbDelete = wxDelete gen connection, dbUpdate = wxUpdate gen connection, dbTables = wxTables connection, dbDescribe = wxDescribe connection, dbTransaction = wxTransaction connection, dbCreateDB = wxCreateDB gen connection, dbCreateTable = wxCreateTable gen connection, dbDropDB = wxDropDB gen connection, dbDropTable = wxDropTable gen connection } wxQuery :: GetRec er vr => SqlGenerator -> Connection -> PrimQuery -> Rel er -> IO [Record vr] wxQuery gen connection qtree rel = wxPrimQuery connection sql scheme rel where sql = show $ ppSql $ sqlQuery gen qtree scheme = attributes qtree wxInsert gen conn table assoc = wxPrimExecute conn $ show $ ppInsert $ sqlInsert gen table assoc wxInsertQuery gen conn table assoc = wxPrimExecute conn $ show $ ppInsert $ sqlInsertQuery gen table assoc wxDelete gen conn table exprs = wxPrimExecute conn $ show $ ppDelete $ sqlDelete gen table exprs wxUpdate gen conn table criteria assigns = wxPrimExecute conn $ show $ ppUpdate $ sqlUpdate gen table criteria assigns wxTables :: Connection -> IO [TableName] wxTables conn = handleDbError $ liftM (map tableName . WX.dbTables) (WX.dbGetInfo conn) wxDescribe :: Connection -> TableName -> IO [(Attribute,FieldDesc)] wxDescribe conn table = do i <- handleDbError $ WX.dbGetTableInfo conn table return $ map toFieldDesc $ tableColumns i where toFieldDesc ColumnInfo {columnName = name, columnSize = size, columnSqlType = sqlType, columnNullable = nullable} = (name, (toFieldType size sqlType, nullable)) wxCreateDB :: SqlGenerator -> Connection -> String -> IO () wxCreateDB gen conn name = wxPrimExecute conn $ show $ ppCreate $ sqlCreateDB gen name wxCreateTable :: SqlGenerator -> Connection -> TableName -> [(Attribute,FieldDesc)] -> IO () wxCreateTable gen conn name as = wxPrimExecute conn $ show $ ppCreate $ sqlCreateTable gen name as wxDropDB :: SqlGenerator -> Connection -> String -> IO () wxDropDB gen conn name = wxPrimExecute conn $ show $ ppDrop $ sqlDropDB gen name wxDropTable :: SqlGenerator -> Connection -> TableName -> IO () wxDropTable gen conn name = wxPrimExecute conn $ show $ ppDrop $ sqlDropTable gen name toFieldType :: Int -> SqlType -> FieldType toFieldType _ SqlDecimal = DoubleT toFieldType _ SqlNumeric = DoubleT toFieldType _ SqlReal = DoubleT toFieldType _ SqlFloat = DoubleT toFieldType _ SqlDouble = DoubleT toFieldType _ SqlSmallInt = IntT toFieldType _ SqlInteger = IntT toFieldType _ SqlTinyInt = IntT toFieldType _ SqlBigInt = IntegerT toFieldType _ SqlDate = CalendarTimeT toFieldType _ SqlTime = CalendarTimeT toFieldType _ SqlTimeStamp = CalendarTimeT toFieldType _ SqlBit = BoolT toFieldType n SqlChar = BStrT n toFieldType n SqlVarChar = BStrT n toFieldType n SqlBinary = BStrT n toFieldType n SqlVarBinary = BStrT n toFieldType _ _ = StringT | WxHaskell implementation of ' Database.dbTransaction ' . wxTransaction :: Connection -> IO a -> IO a wxTransaction conn action = handleDbError $ WX.dbTransaction conn action ----------------------------------------------------------- -- Primitive operations ----------------------------------------------------------- -- | Primitive query wxPrimQuery :: GetRec er vr => Connection -- ^ Database connection. -> String -- ^ SQL query -> Scheme -- ^ List of field names to retrieve ^ Phantom argument to get the return type right . -> IO [Record vr] -- ^ Query results wxPrimQuery connection sql scheme rel = handleDbError $ WX.dbQuery connection sql getResults where getResults = getRec wxGetInstances rel scheme -- | Primitive execute : WxHaskell docs says to always wrap dbExecute in dbTransaction wxPrimExecute :: Connection -- ^ Database connection. -> String -- ^ SQL query. -> IO () wxPrimExecute connection sql = handleDbError $ WX.dbExecute connection sql ----------------------------------------------------------- -- Getting data from a statement ----------------------------------------------------------- wxGetInstances :: GetInstances (DbRow a) wxGetInstances = GetInstances { getString = WX.dbRowGetStringMb , getInt = WX.dbRowGetIntMb , getInteger = WX.dbRowGetIntegerMb , getDouble = WX.dbRowGetDoubleMb , getBool = WX.dbRowGetBoolMb , getCalendarTime = wxGetCalendarTime } wxGetCalendarTime :: DbRow a -> String -> IO (Maybe CalendarTime) wxGetCalendarTime r f = WX.dbRowGetClockTimeMb r f >>= mkIOMBCalendarTime mkIOMBCalendarTime :: Maybe ClockTime -> IO (Maybe CalendarTime) mkIOMBCalendarTime Nothing = return Nothing mkIOMBCalendarTime (Just c) = return (Just (toUTCTime c))
null
https://raw.githubusercontent.com/m4dc4p/haskelldb/a1fbc8a2eca8c70ebe382bf4c022275836d9d510/driver-wx/Database/HaskellDB/WX.hs
haskell
--------------------------------------------------------- | License : BSD-style Stability : experimental Portability : non-portable --------------------------------------------------------- ^ user id ^ password | Run an action and close the connection. --------------------------------------------------------- Primitive operations --------------------------------------------------------- | Primitive query ^ Database connection. ^ SQL query ^ List of field names to retrieve ^ Query results | Primitive execute ^ Database connection. ^ SQL query. --------------------------------------------------------- Getting data from a statement ---------------------------------------------------------
Module : Database . HaskellDB.WX Copyright : HWT Group 2003 , 2005 - 2006 Maintainer : WxHaskell < / > interface for HaskellDB module Database.HaskellDB.WX ( WXOptions(..), wxConnect, DriverInterface(..), driver ) where import Data.Maybe import Control.Exception (catch, throwIO) import Control.Monad import System.IO.Unsafe (unsafeInterleaveIO) import System.Time import Database.HaskellDB import Database.HaskellDB.DriverAPI import Database.HaskellDB.Database import Database.HaskellDB.Sql.Generate (SqlGenerator) import Database.HaskellDB.Sql.Print import Database.HaskellDB.PrimQuery import Database.HaskellDB.Query import Database.HaskellDB.FieldType import Graphics.UI.WXCore.WxcClasses (Db) import Graphics.UI.WXCore.Db (DbRow, ColumnInfo(..),TableInfo(..),SqlType(..)) import qualified Graphics.UI.WXCore.Db as WX type Connection = Db () data WXOptions = WXOptions { ^ name binding in ODBC } wxConnect :: SqlGenerator -> WXOptions -> (Database -> IO a) -> IO a wxConnect gen WXOptions{dsn=d,uid=u,pwd=p} action = handleDbError (WX.dbWithConnection d u p (action . mkDatabase gen)) wxConnectOpts :: [(String,String)] -> (Database -> IO a) -> IO a wxConnectOpts opts f = do [a,b,c] <- getOptions ["dsn","uid","pwd"] opts gen <- getGenerator opts wxConnect gen (PostgreSQLOptions {dsn = a, uid = b, pwd = c}) f driver :: DriverInterface driver = defaultdriver {connect = wxConnectOpts} handleDbError :: IO a -> IO a handleDbError io = WX.catchDbError io (fail . WX.dbErrorMsg) mkDatabase :: SqlGenerator -> Connection -> Database mkDatabase gen connection = Database { dbQuery = wxQuery gen connection, dbInsert = wxInsert gen connection, dbInsertQuery = wxInsertQuery gen connection, dbDelete = wxDelete gen connection, dbUpdate = wxUpdate gen connection, dbTables = wxTables connection, dbDescribe = wxDescribe connection, dbTransaction = wxTransaction connection, dbCreateDB = wxCreateDB gen connection, dbCreateTable = wxCreateTable gen connection, dbDropDB = wxDropDB gen connection, dbDropTable = wxDropTable gen connection } wxQuery :: GetRec er vr => SqlGenerator -> Connection -> PrimQuery -> Rel er -> IO [Record vr] wxQuery gen connection qtree rel = wxPrimQuery connection sql scheme rel where sql = show $ ppSql $ sqlQuery gen qtree scheme = attributes qtree wxInsert gen conn table assoc = wxPrimExecute conn $ show $ ppInsert $ sqlInsert gen table assoc wxInsertQuery gen conn table assoc = wxPrimExecute conn $ show $ ppInsert $ sqlInsertQuery gen table assoc wxDelete gen conn table exprs = wxPrimExecute conn $ show $ ppDelete $ sqlDelete gen table exprs wxUpdate gen conn table criteria assigns = wxPrimExecute conn $ show $ ppUpdate $ sqlUpdate gen table criteria assigns wxTables :: Connection -> IO [TableName] wxTables conn = handleDbError $ liftM (map tableName . WX.dbTables) (WX.dbGetInfo conn) wxDescribe :: Connection -> TableName -> IO [(Attribute,FieldDesc)] wxDescribe conn table = do i <- handleDbError $ WX.dbGetTableInfo conn table return $ map toFieldDesc $ tableColumns i where toFieldDesc ColumnInfo {columnName = name, columnSize = size, columnSqlType = sqlType, columnNullable = nullable} = (name, (toFieldType size sqlType, nullable)) wxCreateDB :: SqlGenerator -> Connection -> String -> IO () wxCreateDB gen conn name = wxPrimExecute conn $ show $ ppCreate $ sqlCreateDB gen name wxCreateTable :: SqlGenerator -> Connection -> TableName -> [(Attribute,FieldDesc)] -> IO () wxCreateTable gen conn name as = wxPrimExecute conn $ show $ ppCreate $ sqlCreateTable gen name as wxDropDB :: SqlGenerator -> Connection -> String -> IO () wxDropDB gen conn name = wxPrimExecute conn $ show $ ppDrop $ sqlDropDB gen name wxDropTable :: SqlGenerator -> Connection -> TableName -> IO () wxDropTable gen conn name = wxPrimExecute conn $ show $ ppDrop $ sqlDropTable gen name toFieldType :: Int -> SqlType -> FieldType toFieldType _ SqlDecimal = DoubleT toFieldType _ SqlNumeric = DoubleT toFieldType _ SqlReal = DoubleT toFieldType _ SqlFloat = DoubleT toFieldType _ SqlDouble = DoubleT toFieldType _ SqlSmallInt = IntT toFieldType _ SqlInteger = IntT toFieldType _ SqlTinyInt = IntT toFieldType _ SqlBigInt = IntegerT toFieldType _ SqlDate = CalendarTimeT toFieldType _ SqlTime = CalendarTimeT toFieldType _ SqlTimeStamp = CalendarTimeT toFieldType _ SqlBit = BoolT toFieldType n SqlChar = BStrT n toFieldType n SqlVarChar = BStrT n toFieldType n SqlBinary = BStrT n toFieldType n SqlVarBinary = BStrT n toFieldType _ _ = StringT | WxHaskell implementation of ' Database.dbTransaction ' . wxTransaction :: Connection -> IO a -> IO a wxTransaction conn action = handleDbError $ WX.dbTransaction conn action wxPrimQuery :: GetRec er vr => ^ Phantom argument to get the return type right . wxPrimQuery connection sql scheme rel = handleDbError $ WX.dbQuery connection sql getResults where getResults = getRec wxGetInstances rel scheme : WxHaskell docs says to always wrap dbExecute in dbTransaction -> IO () wxPrimExecute connection sql = handleDbError $ WX.dbExecute connection sql wxGetInstances :: GetInstances (DbRow a) wxGetInstances = GetInstances { getString = WX.dbRowGetStringMb , getInt = WX.dbRowGetIntMb , getInteger = WX.dbRowGetIntegerMb , getDouble = WX.dbRowGetDoubleMb , getBool = WX.dbRowGetBoolMb , getCalendarTime = wxGetCalendarTime } wxGetCalendarTime :: DbRow a -> String -> IO (Maybe CalendarTime) wxGetCalendarTime r f = WX.dbRowGetClockTimeMb r f >>= mkIOMBCalendarTime mkIOMBCalendarTime :: Maybe ClockTime -> IO (Maybe CalendarTime) mkIOMBCalendarTime Nothing = return Nothing mkIOMBCalendarTime (Just c) = return (Just (toUTCTime c))
233a1f470b88da13661bb85ea2ad0bce596c4c31637eb3bb764923bec555cb6d
dvingo/dv.fulcro-template
user.clj
(ns user (:require [clojure.spec.alpha :as s] [clojure.tools.namespace.repl :as tools-ns] [expound.alpha :as expound] [mount.core :as mount] [shadow.cljs.devtools.api :as shadow] ;; this is the top-level dependent component...mount will find the rest via ns requires [{{namespace}}.server.server :refer [http-server]])) ;; ==================== SERVER ==================== (tools-ns/set-refresh-dirs "src/main" "src/dev" "src/test") ;; Change the default output of spec to be more readable (alter-var-root #'s/*explain-out* (constantly expound/printer)) (comment ;; For shadow: start the shadow-cljs server using ./scripts/start-dev.sh start a cljs repl once shadow is listening ( port 9000 , default ) ;; then you can start the watch processes here (ensure the cljs repl has focus in cursive): ;; (shadow/repl :main) (shadow/help) You have to start the node server first . ;; in terminal, run: node target/node-server.js (shadow/repl :node-server) ;; now you can send cljs forms to the repl but you'll need to open another cljs repl ;; as the server has captured output. ) (defn start "Start the web server + services" [] (mount/start)) (defn stop "Stop the web server + services" [] (mount/stop)) (defn restart "Stop, reload code, and restart the server. If there is a compile error, use: ``` (tools-ns/refresh) ``` to recompile, and then use `start` once things are good." [] (stop) (tools-ns/refresh :after 'user/start)) (comment (tools-ns/refresh :after 'user/start) (shadow/repl :main) (stop) (restart))
null
https://raw.githubusercontent.com/dvingo/dv.fulcro-template/3f143d9a06e00749ea7f33c16c002f416fe69415/resources/clj/new/dv.fulcro_template/src/dev/user.clj
clojure
this is the top-level dependent component...mount will find the rest via ns requires ==================== SERVER ==================== Change the default output of spec to be more readable For shadow: start the shadow-cljs server using ./scripts/start-dev.sh then you can start the watch processes here (ensure the cljs repl has focus in cursive): in terminal, run: node target/node-server.js now you can send cljs forms to the repl but you'll need to open another cljs repl as the server has captured output.
(ns user (:require [clojure.spec.alpha :as s] [clojure.tools.namespace.repl :as tools-ns] [expound.alpha :as expound] [mount.core :as mount] [shadow.cljs.devtools.api :as shadow] [{{namespace}}.server.server :refer [http-server]])) (tools-ns/set-refresh-dirs "src/main" "src/dev" "src/test") (alter-var-root #'s/*explain-out* (constantly expound/printer)) (comment start a cljs repl once shadow is listening ( port 9000 , default ) (shadow/repl :main) (shadow/help) You have to start the node server first . (shadow/repl :node-server) ) (defn start "Start the web server + services" [] (mount/start)) (defn stop "Stop the web server + services" [] (mount/stop)) (defn restart "Stop, reload code, and restart the server. If there is a compile error, use: ``` (tools-ns/refresh) ``` to recompile, and then use `start` once things are good." [] (stop) (tools-ns/refresh :after 'user/start)) (comment (tools-ns/refresh :after 'user/start) (shadow/repl :main) (stop) (restart))
653bfc9c10a2d5f2960c6f1f447e2ffa53d3f42e787b254c13f4cb98f3de4101
elastic/apm-agent-ocaml
reporter.mli
include Elastic_apm.Reporter_intf.S module Log : Async.Log.Global_intf module Host : sig type t val server_env_key : string val token_env_key : string val of_env : unit -> t option val make : Uri.t -> token:string -> t end val create : ?client:Blue_http.Client.t -> ?max_messages_per_batch:int -> Host.t -> Elastic_apm.Metadata.t -> t
null
https://raw.githubusercontent.com/elastic/apm-agent-ocaml/50247d756493c5c9700fc95b6f6645f1a6203e65/async_reporter/reporter.mli
ocaml
include Elastic_apm.Reporter_intf.S module Log : Async.Log.Global_intf module Host : sig type t val server_env_key : string val token_env_key : string val of_env : unit -> t option val make : Uri.t -> token:string -> t end val create : ?client:Blue_http.Client.t -> ?max_messages_per_batch:int -> Host.t -> Elastic_apm.Metadata.t -> t
85ba2aedc84b563df51886407234125d6c6806351e60e78337ec0bbc3de524f7
freizl/hoauth2
ZOHO.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # -- | [ZOHO oauth overview](-overview.html) module Network.OAuth2.Provider.ZOHO where import Data.Aeson import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Data.Text.Lazy (Text) import GHC.Generics import Network.OAuth.OAuth2 import Network.OAuth2.Experiment import URI.ByteString.QQ data ZOHO = ZOHO deriving (Eq, Show) type instance IdpUserInfo ZOHO = ZOHOUserResp defaultZohoApp :: IdpApplication 'AuthorizationCode ZOHO defaultZohoApp = AuthorizationCodeIdpApplication { idpAppClientId = "" , idpAppClientSecret = "" , idpAppScope = Set.fromList ["ZohoCRM.users.READ"] , idpAppAuthorizeExtraParams = Map.fromList [("access_type", "offline"), ("prompt", "consent")] , idpAppAuthorizeState = "CHANGE_ME" , idpAppRedirectUri = [uri||] , idpAppName = "default-zoho-App" , idpAppTokenRequestAuthenticationMethod = ClientSecretBasic , idp = defaultZohoIdp } defaultZohoIdp :: Idp ZOHO defaultZohoIdp = Idp { idpFetchUserInfo = authGetJSON @(IdpUserInfo ZOHO) , idpUserInfoEndpoint = [uri||] , idpAuthorizeEndpoint = [uri||] , idpTokenEndpoint = [uri||] } -- `oauth/user/info` url does not work and find answer from -- -api-better-document-oauth-user-info data ZOHOUser = ZOHOUser { email :: Text , fullName :: Text } deriving (Show, Generic) newtype ZOHOUserResp = ZOHOUserResp {users :: [ZOHOUser]} deriving (Show, Generic) instance FromJSON ZOHOUserResp instance FromJSON ZOHOUser where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'}
null
https://raw.githubusercontent.com/freizl/hoauth2/2337ba1affce5b60ee09e425988f15bc23e39147/hoauth2-providers/src/Network/OAuth2/Provider/ZOHO.hs
haskell
# LANGUAGE OverloadedStrings # | [ZOHO oauth overview](-overview.html) `oauth/user/info` url does not work and find answer from -api-better-document-oauth-user-info
# LANGUAGE DeriveGeneric # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # module Network.OAuth2.Provider.ZOHO where import Data.Aeson import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Data.Text.Lazy (Text) import GHC.Generics import Network.OAuth.OAuth2 import Network.OAuth2.Experiment import URI.ByteString.QQ data ZOHO = ZOHO deriving (Eq, Show) type instance IdpUserInfo ZOHO = ZOHOUserResp defaultZohoApp :: IdpApplication 'AuthorizationCode ZOHO defaultZohoApp = AuthorizationCodeIdpApplication { idpAppClientId = "" , idpAppClientSecret = "" , idpAppScope = Set.fromList ["ZohoCRM.users.READ"] , idpAppAuthorizeExtraParams = Map.fromList [("access_type", "offline"), ("prompt", "consent")] , idpAppAuthorizeState = "CHANGE_ME" , idpAppRedirectUri = [uri||] , idpAppName = "default-zoho-App" , idpAppTokenRequestAuthenticationMethod = ClientSecretBasic , idp = defaultZohoIdp } defaultZohoIdp :: Idp ZOHO defaultZohoIdp = Idp { idpFetchUserInfo = authGetJSON @(IdpUserInfo ZOHO) , idpUserInfoEndpoint = [uri||] , idpAuthorizeEndpoint = [uri||] , idpTokenEndpoint = [uri||] } data ZOHOUser = ZOHOUser { email :: Text , fullName :: Text } deriving (Show, Generic) newtype ZOHOUserResp = ZOHOUserResp {users :: [ZOHOUser]} deriving (Show, Generic) instance FromJSON ZOHOUserResp instance FromJSON ZOHOUser where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'}
5dd4718ef0da0eb0cb60d7ffb916cf53aadd2ddeaed657caac37dd6e9da46878
scicloj/scicloj.ml-tutorials
nested_cv.clj
(ns scicloj.ml.nested-cv (:require [tablecloth.api :as tc] [scicloj.metamorph.ml :as ml] [scicloj.metamorph.ml.classification :as clf] [tech.v3.datatype :as dt])) (defn nested-cv [data pipelines metric-fn loss-or-accuracy outer-k inner-k] ;; (let [k-folds (tc/split->seq data :kfold {:k outer-k})] (for [{train :train test :test} k-folds] (let [inner-k-fold (tc/split->seq test :kfold {:k inner-k}) evaluation (ml/evaluate-pipelines pipelines inner-k-fold metric-fn loss-or-accuracy) fit-ctx (-> evaluation first first :fit-ctx) best-pipe-fn (-> evaluation first first :pipe-fn) transform-ctx (best-pipe-fn (merge fit-ctx {:metamorph/data test :metamorph/mode :transform})) metric (metric-fn (-> transform-ctx :model :scicloj.metamorph.ml/target-ds :survived dt/->vector) (-> transform-ctx :metamorph/data :survived dt/->vector))] {:pipe-fn best-pipe-fn :fit-ctx fit-ctx :metric metric}))))
null
https://raw.githubusercontent.com/scicloj/scicloj.ml-tutorials/0ef90e5a7d5cb3aca1c2d2e59f35117b50e264bf/src/scicloj/ml/nested_cv.clj
clojure
(ns scicloj.ml.nested-cv (:require [tablecloth.api :as tc] [scicloj.metamorph.ml :as ml] [scicloj.metamorph.ml.classification :as clf] [tech.v3.datatype :as dt])) (defn nested-cv [data pipelines metric-fn loss-or-accuracy outer-k inner-k] (let [k-folds (tc/split->seq data :kfold {:k outer-k})] (for [{train :train test :test} k-folds] (let [inner-k-fold (tc/split->seq test :kfold {:k inner-k}) evaluation (ml/evaluate-pipelines pipelines inner-k-fold metric-fn loss-or-accuracy) fit-ctx (-> evaluation first first :fit-ctx) best-pipe-fn (-> evaluation first first :pipe-fn) transform-ctx (best-pipe-fn (merge fit-ctx {:metamorph/data test :metamorph/mode :transform})) metric (metric-fn (-> transform-ctx :model :scicloj.metamorph.ml/target-ds :survived dt/->vector) (-> transform-ctx :metamorph/data :survived dt/->vector))] {:pipe-fn best-pipe-fn :fit-ctx fit-ctx :metric metric}))))
fa83db69951552c181adec07d762c7a26ef54350fd73bd878d6f7d16e4c2015d
thlack/surfs
impl.clj
(ns ^:no-doc thlack.surfs.repl.impl (:require [clojure.spec.alpha :as s] [clojure.string :as string] [thlack.surfs.render :as render])) (defn- get-var [tag] (render/tags tag)) (defn- get-meta [tag] (some-> tag (get-var) (meta) (select-keys [:doc :name]))) (defn- get-spec [tag] (some->> tag (get-var) (s/get-spec) (s/describe) (next) (apply hash-map))) (defn- with-spec [tag description] (assoc description :spec (get-spec tag))) (defn describe [tag] (->> tag (get-meta) (with-spec tag) (merge {:tag tag}))) (defn- get-args [{{:keys [args]} :spec}] args) (defn- get-cats' [args] (let [head (first args)] (if (= 'alt head) (vals (apply hash-map (rest args))) (list args)))) (defn- get-cats [args] (->> args (get-cats') (map (fn [c] (map (fn [x] (if (seq? x) (second x) x)) c))))) (defn- signature-string "Get an arglist based on a function spec." [{:keys [tag] :as description}] (->> (get-args description) (get-cats) (map rest) (map #(map symbol %)) (map #(take-nth 2 %)) (map vec) (map #(into [tag] %)) (pr-str))) (defn- doc-string "Get the doc string for a component description" [description] (some-> description (:doc) (string/replace #"^" " ") (string/split-lines) (#(string/join (System/lineSeparator) %)))) (defn doc [tag] (let [description (describe tag)] (->> description (doc-string) (str (signature-string description) (System/lineSeparator)) (println)))) (defn- expand-prop [prop] (if (qualified-keyword? prop) (s/describe prop) prop)) (defn props [tag] (some->> tag (describe) (get-args) (get-cats) (map #(apply hash-map (rest %))) (filter #(contains? % :props)) (first) :props (s/describe) (map expand-prop)))
null
https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/repl/impl.clj
clojure
(ns ^:no-doc thlack.surfs.repl.impl (:require [clojure.spec.alpha :as s] [clojure.string :as string] [thlack.surfs.render :as render])) (defn- get-var [tag] (render/tags tag)) (defn- get-meta [tag] (some-> tag (get-var) (meta) (select-keys [:doc :name]))) (defn- get-spec [tag] (some->> tag (get-var) (s/get-spec) (s/describe) (next) (apply hash-map))) (defn- with-spec [tag description] (assoc description :spec (get-spec tag))) (defn describe [tag] (->> tag (get-meta) (with-spec tag) (merge {:tag tag}))) (defn- get-args [{{:keys [args]} :spec}] args) (defn- get-cats' [args] (let [head (first args)] (if (= 'alt head) (vals (apply hash-map (rest args))) (list args)))) (defn- get-cats [args] (->> args (get-cats') (map (fn [c] (map (fn [x] (if (seq? x) (second x) x)) c))))) (defn- signature-string "Get an arglist based on a function spec." [{:keys [tag] :as description}] (->> (get-args description) (get-cats) (map rest) (map #(map symbol %)) (map #(take-nth 2 %)) (map vec) (map #(into [tag] %)) (pr-str))) (defn- doc-string "Get the doc string for a component description" [description] (some-> description (:doc) (string/replace #"^" " ") (string/split-lines) (#(string/join (System/lineSeparator) %)))) (defn doc [tag] (let [description (describe tag)] (->> description (doc-string) (str (signature-string description) (System/lineSeparator)) (println)))) (defn- expand-prop [prop] (if (qualified-keyword? prop) (s/describe prop) prop)) (defn props [tag] (some->> tag (describe) (get-args) (get-cats) (map #(apply hash-map (rest %))) (filter #(contains? % :props)) (first) :props (s/describe) (map expand-prop)))
041e4252826b16633fec84615f6c72e3ef21668ab720e9ca900a3f0fcc62c0dc
CatalaLang/catala
print.mli
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2022 , contributor : < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . and social benefits computation rules. Copyright (C) 2022 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) val format_item : Shared_ast.decl_ctx -> ?debug:bool -> Format.formatter -> Ast.code_item -> unit val format_program : Shared_ast.decl_ctx -> ?debug:bool -> Format.formatter -> Ast.program -> unit
null
https://raw.githubusercontent.com/CatalaLang/catala/fced0fff54ddeacee74b357196bdac3151c4c0ef/compiler/scalc/print.mli
ocaml
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2022 , contributor : < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . and social benefits computation rules. Copyright (C) 2022 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) val format_item : Shared_ast.decl_ctx -> ?debug:bool -> Format.formatter -> Ast.code_item -> unit val format_program : Shared_ast.decl_ctx -> ?debug:bool -> Format.formatter -> Ast.program -> unit
5879910fdec693a312b1f481d07a443742f9f4ea783dfda77a54afdd0ede358f
LukaKurnjek/plutus-pioneer-program-book
Parameterized.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # OPTIONS_GHC -fno - warn - unused - imports # module Week03.Parameterized where import Control.Monad hiding (fmap) import Data.Aeson (ToJSON, FromJSON) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import GHC.Generics (Generic) import Plutus.Contract import PlutusTx (Data (..)) import qualified PlutusTx import PlutusTx.Prelude hiding (Semigroup(..), unless) import Ledger hiding (singleton) import Ledger.Constraints (TxConstraints) import qualified Ledger.Constraints as Constraints import qualified Ledger.Typed.Scripts as Scripts import Ledger.Ada as Ada import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) import Prelude (IO, Semigroup (..), Show (..), String) import Text.Printf (printf) data VestingParam = VestingParam { beneficiary :: PaymentPubKeyHash , deadline :: POSIXTime } deriving Show PlutusTx.makeLift ''VestingParam # INLINABLE mkValidator # mkValidator :: VestingParam -> () -> () -> ScriptContext -> Bool mkValidator p () () ctx = traceIfFalse "beneficiary's signature missing" signedByBeneficiary && traceIfFalse "deadline not reached" deadlineReached where info :: TxInfo info = scriptContextTxInfo ctx signedByBeneficiary :: Bool signedByBeneficiary = txSignedBy info $ unPaymentPubKeyHash $ beneficiary p deadlineReached :: Bool deadlineReached = contains (from $ deadline p) $ txInfoValidRange info data Vesting instance Scripts.ValidatorTypes Vesting where type instance DatumType Vesting = () type instance RedeemerType Vesting = () typedValidator :: VestingParam -> Scripts.TypedValidator Vesting typedValidator p = Scripts.mkTypedValidator @Vesting ($$(PlutusTx.compile [|| mkValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode p) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.wrapValidator @() @() validator :: VestingParam -> Validator validator = Scripts.validatorScript . typedValidator valHash :: VestingParam -> Ledger.ValidatorHash valHash = Scripts.validatorHash . typedValidator scrAddress :: VestingParam -> Ledger.Address scrAddress = scriptAddress . validator data GiveParams = GiveParams { gpBeneficiary :: !PaymentPubKeyHash , gpDeadline :: !POSIXTime , gpAmount :: !Integer } deriving (Generic, ToJSON, FromJSON, ToSchema) type VestingSchema = Endpoint "give" GiveParams .\/ Endpoint "grab" POSIXTime give :: AsContractError e => GiveParams -> Contract w s e () give gp = do let p = VestingParam { beneficiary = gpBeneficiary gp , deadline = gpDeadline gp } tx = Constraints.mustPayToTheScript () $ Ada.lovelaceValueOf $ gpAmount gp ledgerTx <- submitTxConstraints (typedValidator p) tx void $ awaitTxConfirmed $ getCardanoTxId ledgerTx logInfo @String $ printf "made a gift of %d lovelace to %s with deadline %s" (gpAmount gp) (show $ gpBeneficiary gp) (show $ gpDeadline gp) grab :: forall w s e. AsContractError e => POSIXTime -> Contract w s e () grab d = do now <- currentTime pkh <- ownPaymentPubKeyHash if now < d then logInfo @String $ "too early" else do let p = VestingParam { beneficiary = pkh , deadline = d } utxos <- utxosAt $ scrAddress p if Map.null utxos then logInfo @String $ "no gifts available" else do let orefs = fst <$> Map.toList utxos lookups = Constraints.unspentOutputs utxos <> Constraints.otherScript (validator p) tx :: TxConstraints Void Void tx = mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer | oref <- orefs] <> Constraints.mustValidateIn (from now) ledgerTx <- submitTxConstraintsWith @Void lookups tx void $ awaitTxConfirmed $ getCardanoTxId ledgerTx logInfo @String $ "collected gifts" endpoints :: Contract () VestingSchema Text () endpoints = awaitPromise (give' `select` grab') >> endpoints where give' = endpoint @"give" give grab' = endpoint @"grab" grab mkSchemaDefinitions ''VestingSchema mkKnownCurrencies []
null
https://raw.githubusercontent.com/LukaKurnjek/plutus-pioneer-program-book/0e69b2719dc7412a412a546825a002be5209e733/code/week03/src/Week03/Parameterized.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators #
# LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -fno - warn - unused - imports # module Week03.Parameterized where import Control.Monad hiding (fmap) import Data.Aeson (ToJSON, FromJSON) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import GHC.Generics (Generic) import Plutus.Contract import PlutusTx (Data (..)) import qualified PlutusTx import PlutusTx.Prelude hiding (Semigroup(..), unless) import Ledger hiding (singleton) import Ledger.Constraints (TxConstraints) import qualified Ledger.Constraints as Constraints import qualified Ledger.Typed.Scripts as Scripts import Ledger.Ada as Ada import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage, ToSchema) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) import Prelude (IO, Semigroup (..), Show (..), String) import Text.Printf (printf) data VestingParam = VestingParam { beneficiary :: PaymentPubKeyHash , deadline :: POSIXTime } deriving Show PlutusTx.makeLift ''VestingParam # INLINABLE mkValidator # mkValidator :: VestingParam -> () -> () -> ScriptContext -> Bool mkValidator p () () ctx = traceIfFalse "beneficiary's signature missing" signedByBeneficiary && traceIfFalse "deadline not reached" deadlineReached where info :: TxInfo info = scriptContextTxInfo ctx signedByBeneficiary :: Bool signedByBeneficiary = txSignedBy info $ unPaymentPubKeyHash $ beneficiary p deadlineReached :: Bool deadlineReached = contains (from $ deadline p) $ txInfoValidRange info data Vesting instance Scripts.ValidatorTypes Vesting where type instance DatumType Vesting = () type instance RedeemerType Vesting = () typedValidator :: VestingParam -> Scripts.TypedValidator Vesting typedValidator p = Scripts.mkTypedValidator @Vesting ($$(PlutusTx.compile [|| mkValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode p) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.wrapValidator @() @() validator :: VestingParam -> Validator validator = Scripts.validatorScript . typedValidator valHash :: VestingParam -> Ledger.ValidatorHash valHash = Scripts.validatorHash . typedValidator scrAddress :: VestingParam -> Ledger.Address scrAddress = scriptAddress . validator data GiveParams = GiveParams { gpBeneficiary :: !PaymentPubKeyHash , gpDeadline :: !POSIXTime , gpAmount :: !Integer } deriving (Generic, ToJSON, FromJSON, ToSchema) type VestingSchema = Endpoint "give" GiveParams .\/ Endpoint "grab" POSIXTime give :: AsContractError e => GiveParams -> Contract w s e () give gp = do let p = VestingParam { beneficiary = gpBeneficiary gp , deadline = gpDeadline gp } tx = Constraints.mustPayToTheScript () $ Ada.lovelaceValueOf $ gpAmount gp ledgerTx <- submitTxConstraints (typedValidator p) tx void $ awaitTxConfirmed $ getCardanoTxId ledgerTx logInfo @String $ printf "made a gift of %d lovelace to %s with deadline %s" (gpAmount gp) (show $ gpBeneficiary gp) (show $ gpDeadline gp) grab :: forall w s e. AsContractError e => POSIXTime -> Contract w s e () grab d = do now <- currentTime pkh <- ownPaymentPubKeyHash if now < d then logInfo @String $ "too early" else do let p = VestingParam { beneficiary = pkh , deadline = d } utxos <- utxosAt $ scrAddress p if Map.null utxos then logInfo @String $ "no gifts available" else do let orefs = fst <$> Map.toList utxos lookups = Constraints.unspentOutputs utxos <> Constraints.otherScript (validator p) tx :: TxConstraints Void Void tx = mconcat [Constraints.mustSpendScriptOutput oref unitRedeemer | oref <- orefs] <> Constraints.mustValidateIn (from now) ledgerTx <- submitTxConstraintsWith @Void lookups tx void $ awaitTxConfirmed $ getCardanoTxId ledgerTx logInfo @String $ "collected gifts" endpoints :: Contract () VestingSchema Text () endpoints = awaitPromise (give' `select` grab') >> endpoints where give' = endpoint @"give" give grab' = endpoint @"grab" grab mkSchemaDefinitions ''VestingSchema mkKnownCurrencies []
b97a140ad204ce5e0d3136a52dc6de4ad1e3b8d853c7004b13804124a0f9da46
d-cent/mooncake
mongo.clj
(ns mooncake.integration.db.mongo (:require [midje.sweet :refer :all] [mooncake.db.mongo :as mongo] [mooncake.test.test-helpers.db :as dbh])) (def collection-name "stuff") (defn test-fetch [store] (fact {:midje/name (str (type store) " -- creating mongo store from mongo uri creates a MongoStore which can be used to store-with-id! and fetch")} (mongo/store-with-id! store collection-name :some-index-key {:some-index-key "barry" :some-other-key "other"}) (mongo/fetch store collection-name "barry") => {:some-index-key "barry" :some-other-key "other"})) (defn test-store-with-id [store] (fact {:midje/name (str (type store) " -- storing an item in an empty collection results in just that item being in the collection")} (let [item {:some-index-key "barry" :some-other-key "other"}] (mongo/fetch-all store collection-name) => empty? (mongo/store-with-id! store collection-name :some-index-key item) => item (count (mongo/fetch-all store collection-name)) => 1 (mongo/find-item store collection-name {:some-index-key "barry"}) => item))) (defn test-duplicate-key [store] (fact {:midje/name (str (type store) " -- storing an item with a duplicate key throws an exception")} (let [item {:some-index-key "barry" :some-other-key "other"}] (mongo/store-with-id! store collection-name :some-index-key item) => item (mongo/store-with-id! store collection-name :some-index-key item) => (throws Exception)))) (defn test-find-item [store] (fact {:midje/name (str (type store) " -- find-item queries items based on a query map and returns one if a match is found")} (let [item1 {:some-index-key "barry" :some-other-key "other"} item2 {:some-index-key "rebecca" :some-other-key "bsaa"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/find-item store collection-name {:some-other-key "other"}) => item1 (mongo/find-item store collection-name {:some-other-key "bsaa"}) => item2 (mongo/find-item store collection-name {:some-other-key "foo" :a-third-key "bar"}) => item3 (fact {:midje/name "check that non-existant item returns nil"} (mongo/find-item store collection-name {:some-other-key "nonExisty"}) => nil) (fact {:midje/name "returns nil if query is nil"} (mongo/find-item store collection-name nil) => nil)))) (defn test-find-items-by-alternatives [store] (fact {:midje/name (str (type store) " -- test-find-items-by-alternatives queries items based on values of provided maps")} (let [item1 {:some-index-key "rebecca" :some-other-key "other"} item2 {:some-index-key "barry" :some-other-key "bsaa"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/find-items-by-alternatives store collection-name [{:some-other-key "other"}] {}) => [item1] (mongo/find-items-by-alternatives store collection-name [{:some-other-key "other" :some-index-key "barry"}] {}) => [] (mongo/find-items-by-alternatives store collection-name [{:some-index-key ["barry"]}] {}) => [item2] (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["other" "foo"]}] {}) => (just [item1 item3] :in-any-order) (fact {:midje/name "check that non-existant item returns an empty vector"} (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["nonExisty"]}] {}) => []) (fact {:midje/name "check that non-existant key returns an empty vector"} (mongo/find-items-by-alternatives store collection-name [{:non-existing-key ["nonExisty"]}] {}) => []) (fact "can query by multiple alternatives" (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["other"]} {:some-index-key ["barry"]}] {}) => (just [item1 item2] :in-any-order)) (fact "can sort results by a given column and ordering" (mongo/find-items-by-alternatives store collection-name [{}] {:sort {:some-index-key :ascending}}) => (just [item2 item1 item3]) (mongo/find-items-by-alternatives store collection-name [{}] {:sort {:some-index-key :descending}}) => (just [item3 item1 item2])) (fact "can retrieve results in batches" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2}) => (two-of anything)) (fact "can retrieve results by page" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2 :page-number 2}) => (one-of anything)) (fact "if page number is nil it will default to the first page" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2 :page-number nil}) => (two-of anything))) )) (defn test-find-items-by-timestamps [store] (fact {:midje/name (str (type store) " -- test-find-items-by-timestamp queries items that are older than provided timestamp")} (let [latest-time "2015-08-12T00:00:02.000Z" middle-time "2015-08-12T00:00:01.000Z" oldest-time "2015-08-12T00:00:00.000Z" item1 {:some-index-key "Mal" :published latest-time :relInsertTime 4} item3 {:some-index-key "Wash" :published middle-time :relInsertTime 3} item2 {:some-index-key "Zoe" :published middle-time :relInsertTime 2} item4 {:some-index-key "Kayleigh" :published oldest-time :relInsertTime 1} _ (mongo/store! store collection-name item1) _ (mongo/store! store collection-name item2) _ (mongo/store! store collection-name item3) _ (mongo/store! store collection-name item4) newer-items-requested false older-items-requested true] (fact "can select activities based on timestamp and whether older or newer items are requested" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {} middle-time 3 older-items-requested) => (just [item2 item4]) (mongo/find-items-by-timestamp-and-id store collection-name [{}] {} middle-time 2 newer-items-requested) => (just [item1 item3])) (fact "can sort results by a given column and ordering" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:sort {:published :descending :relInsertTime :descending}} oldest-time 1 newer-items-requested) => (just [item1 item3 item2]) (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:sort {:published :ascending :relInsertTime :ascending}} oldest-time 1 newer-items-requested) => (just [item2 item3 item1])) (fact "limits activity amount for older items" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:limit 2} latest-time 4 older-items-requested ) => (two-of anything)) (fact "doesn't limit activity amount for newer items" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:limit nil} oldest-time 1 newer-items-requested) => (three-of anything))))) (defn test-fetch-total-count-by-query [store] (fact {:midje/name (str (type store) " -- test-fetch-total-count-by-query gets the total number of items which match the query")} (let [item1 {:some-index-key "rebecca" :some-other-key "other"} item2 {:some-index-key "barry" :some-other-key "other"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/fetch-total-count-by-query store collection-name [{}]) => 3 (mongo/fetch-total-count-by-query store collection-name [{:some-other-key "other"}]) => 2))) (defn test-fetch-all-items [store] (fact {:midje/name (str (type store) " -- can fetch all items")} (let [item1 {:a-key 1} item2 {:another-key 2}] (mongo/store! store collection-name item1) (mongo/store! store collection-name item2) (mongo/fetch-all store collection-name) => (just [{:a-key 1} {:another-key 2}] :in-any-order)))) (defn test-upsert [store] (fact {:midje/name (str (type store) " -- upsert inserts a record if it doesn't exist, or replaces it if found with query")} (mongo/upsert! store collection-name {:name "Gandalf"} :colour "white") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "white"}] (mongo/upsert! store collection-name {:name "Gandalf"} :colour "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "grey"}])) (defn bugfix-test-store-with-id-and-then-upsert [store] (fact {:midje/name (str (type store) " -- upsert works correctly after first storing with id")} (mongo/store-with-id! store collection-name :name {:name "Gandalf"}) (mongo/fetch-all store collection-name) => [{:name "Gandalf"}] (mongo/upsert! store collection-name {:name "Gandalf"} :colour "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "grey"}])) (defn test-add-to-set [store] (fact {:midje/name (str (type store) " -- add-to-set adds a single value to an array field, ensuring there are no duplicates")} (fact "can add first value to a set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "white") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white"]}]) (fact "can add second value to a set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white" "grey"]}]) (fact "does not add duplicates to set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white" "grey"]}]))) (def tests [test-fetch test-store-with-id test-upsert test-find-item test-find-items-by-alternatives test-find-items-by-timestamps test-fetch-total-count-by-query test-duplicate-key test-fetch-all-items bugfix-test-store-with-id-and-then-upsert test-add-to-set]) (fact "test both implementations of store" (doseq [test tests] (dbh/with-mongo-do (fn [mongo-db] (let [mongo-store (mongo/create-mongo-store mongo-db) in-memory-store (dbh/create-in-memory-store)] (test mongo-store) (test in-memory-store))))))
null
https://raw.githubusercontent.com/d-cent/mooncake/eb16b7239e7580a73b98f7cdacb324ab4e301f9c/test/mooncake/integration/db/mongo.clj
clojure
(ns mooncake.integration.db.mongo (:require [midje.sweet :refer :all] [mooncake.db.mongo :as mongo] [mooncake.test.test-helpers.db :as dbh])) (def collection-name "stuff") (defn test-fetch [store] (fact {:midje/name (str (type store) " -- creating mongo store from mongo uri creates a MongoStore which can be used to store-with-id! and fetch")} (mongo/store-with-id! store collection-name :some-index-key {:some-index-key "barry" :some-other-key "other"}) (mongo/fetch store collection-name "barry") => {:some-index-key "barry" :some-other-key "other"})) (defn test-store-with-id [store] (fact {:midje/name (str (type store) " -- storing an item in an empty collection results in just that item being in the collection")} (let [item {:some-index-key "barry" :some-other-key "other"}] (mongo/fetch-all store collection-name) => empty? (mongo/store-with-id! store collection-name :some-index-key item) => item (count (mongo/fetch-all store collection-name)) => 1 (mongo/find-item store collection-name {:some-index-key "barry"}) => item))) (defn test-duplicate-key [store] (fact {:midje/name (str (type store) " -- storing an item with a duplicate key throws an exception")} (let [item {:some-index-key "barry" :some-other-key "other"}] (mongo/store-with-id! store collection-name :some-index-key item) => item (mongo/store-with-id! store collection-name :some-index-key item) => (throws Exception)))) (defn test-find-item [store] (fact {:midje/name (str (type store) " -- find-item queries items based on a query map and returns one if a match is found")} (let [item1 {:some-index-key "barry" :some-other-key "other"} item2 {:some-index-key "rebecca" :some-other-key "bsaa"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/find-item store collection-name {:some-other-key "other"}) => item1 (mongo/find-item store collection-name {:some-other-key "bsaa"}) => item2 (mongo/find-item store collection-name {:some-other-key "foo" :a-third-key "bar"}) => item3 (fact {:midje/name "check that non-existant item returns nil"} (mongo/find-item store collection-name {:some-other-key "nonExisty"}) => nil) (fact {:midje/name "returns nil if query is nil"} (mongo/find-item store collection-name nil) => nil)))) (defn test-find-items-by-alternatives [store] (fact {:midje/name (str (type store) " -- test-find-items-by-alternatives queries items based on values of provided maps")} (let [item1 {:some-index-key "rebecca" :some-other-key "other"} item2 {:some-index-key "barry" :some-other-key "bsaa"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/find-items-by-alternatives store collection-name [{:some-other-key "other"}] {}) => [item1] (mongo/find-items-by-alternatives store collection-name [{:some-other-key "other" :some-index-key "barry"}] {}) => [] (mongo/find-items-by-alternatives store collection-name [{:some-index-key ["barry"]}] {}) => [item2] (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["other" "foo"]}] {}) => (just [item1 item3] :in-any-order) (fact {:midje/name "check that non-existant item returns an empty vector"} (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["nonExisty"]}] {}) => []) (fact {:midje/name "check that non-existant key returns an empty vector"} (mongo/find-items-by-alternatives store collection-name [{:non-existing-key ["nonExisty"]}] {}) => []) (fact "can query by multiple alternatives" (mongo/find-items-by-alternatives store collection-name [{:some-other-key ["other"]} {:some-index-key ["barry"]}] {}) => (just [item1 item2] :in-any-order)) (fact "can sort results by a given column and ordering" (mongo/find-items-by-alternatives store collection-name [{}] {:sort {:some-index-key :ascending}}) => (just [item2 item1 item3]) (mongo/find-items-by-alternatives store collection-name [{}] {:sort {:some-index-key :descending}}) => (just [item3 item1 item2])) (fact "can retrieve results in batches" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2}) => (two-of anything)) (fact "can retrieve results by page" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2 :page-number 2}) => (one-of anything)) (fact "if page number is nil it will default to the first page" (mongo/find-items-by-alternatives store collection-name [{}] {:limit 2 :page-number nil}) => (two-of anything))) )) (defn test-find-items-by-timestamps [store] (fact {:midje/name (str (type store) " -- test-find-items-by-timestamp queries items that are older than provided timestamp")} (let [latest-time "2015-08-12T00:00:02.000Z" middle-time "2015-08-12T00:00:01.000Z" oldest-time "2015-08-12T00:00:00.000Z" item1 {:some-index-key "Mal" :published latest-time :relInsertTime 4} item3 {:some-index-key "Wash" :published middle-time :relInsertTime 3} item2 {:some-index-key "Zoe" :published middle-time :relInsertTime 2} item4 {:some-index-key "Kayleigh" :published oldest-time :relInsertTime 1} _ (mongo/store! store collection-name item1) _ (mongo/store! store collection-name item2) _ (mongo/store! store collection-name item3) _ (mongo/store! store collection-name item4) newer-items-requested false older-items-requested true] (fact "can select activities based on timestamp and whether older or newer items are requested" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {} middle-time 3 older-items-requested) => (just [item2 item4]) (mongo/find-items-by-timestamp-and-id store collection-name [{}] {} middle-time 2 newer-items-requested) => (just [item1 item3])) (fact "can sort results by a given column and ordering" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:sort {:published :descending :relInsertTime :descending}} oldest-time 1 newer-items-requested) => (just [item1 item3 item2]) (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:sort {:published :ascending :relInsertTime :ascending}} oldest-time 1 newer-items-requested) => (just [item2 item3 item1])) (fact "limits activity amount for older items" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:limit 2} latest-time 4 older-items-requested ) => (two-of anything)) (fact "doesn't limit activity amount for newer items" (mongo/find-items-by-timestamp-and-id store collection-name [{}] {:limit nil} oldest-time 1 newer-items-requested) => (three-of anything))))) (defn test-fetch-total-count-by-query [store] (fact {:midje/name (str (type store) " -- test-fetch-total-count-by-query gets the total number of items which match the query")} (let [item1 {:some-index-key "rebecca" :some-other-key "other"} item2 {:some-index-key "barry" :some-other-key "other"} item3 {:some-index-key "zane" :some-other-key "foo" :a-third-key "bar"} _ (mongo/store-with-id! store collection-name :some-index-key item1) _ (mongo/store-with-id! store collection-name :some-index-key item2) _ (mongo/store-with-id! store collection-name :some-index-key item3)] (mongo/fetch-total-count-by-query store collection-name [{}]) => 3 (mongo/fetch-total-count-by-query store collection-name [{:some-other-key "other"}]) => 2))) (defn test-fetch-all-items [store] (fact {:midje/name (str (type store) " -- can fetch all items")} (let [item1 {:a-key 1} item2 {:another-key 2}] (mongo/store! store collection-name item1) (mongo/store! store collection-name item2) (mongo/fetch-all store collection-name) => (just [{:a-key 1} {:another-key 2}] :in-any-order)))) (defn test-upsert [store] (fact {:midje/name (str (type store) " -- upsert inserts a record if it doesn't exist, or replaces it if found with query")} (mongo/upsert! store collection-name {:name "Gandalf"} :colour "white") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "white"}] (mongo/upsert! store collection-name {:name "Gandalf"} :colour "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "grey"}])) (defn bugfix-test-store-with-id-and-then-upsert [store] (fact {:midje/name (str (type store) " -- upsert works correctly after first storing with id")} (mongo/store-with-id! store collection-name :name {:name "Gandalf"}) (mongo/fetch-all store collection-name) => [{:name "Gandalf"}] (mongo/upsert! store collection-name {:name "Gandalf"} :colour "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :colour "grey"}])) (defn test-add-to-set [store] (fact {:midje/name (str (type store) " -- add-to-set adds a single value to an array field, ensuring there are no duplicates")} (fact "can add first value to a set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "white") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white"]}]) (fact "can add second value to a set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white" "grey"]}]) (fact "does not add duplicates to set" (mongo/add-to-set! store collection-name {:name "Gandalf"} :beard-colours "grey") (mongo/fetch-all store collection-name) => [{:name "Gandalf" :beard-colours ["white" "grey"]}]))) (def tests [test-fetch test-store-with-id test-upsert test-find-item test-find-items-by-alternatives test-find-items-by-timestamps test-fetch-total-count-by-query test-duplicate-key test-fetch-all-items bugfix-test-store-with-id-and-then-upsert test-add-to-set]) (fact "test both implementations of store" (doseq [test tests] (dbh/with-mongo-do (fn [mongo-db] (let [mongo-store (mongo/create-mongo-store mongo-db) in-memory-store (dbh/create-in-memory-store)] (test mongo-store) (test in-memory-store))))))
6f6dea496fa24d3e8f92887cf80c23e84ffb3845dd47d16e8fa1c39bba1ee462
gigasquid/clj-drone
simple.clj
(ns clj-drone.example.simple (:require [clj-drone.core :refer :all])) (drone-initialize) ;Use ip and port for non-standard drone ip/port ( drone - initialize : default ip ) (drone :take-off) (Thread/sleep 10000) (drone :land)
null
https://raw.githubusercontent.com/gigasquid/clj-drone/b85320a0ab5e4d8589aaf77a0bd57e8a46e2905b/examples/simple.clj
clojure
Use ip and port for non-standard drone ip/port
(ns clj-drone.example.simple (:require [clj-drone.core :refer :all])) (drone-initialize) ( drone - initialize : default ip ) (drone :take-off) (Thread/sleep 10000) (drone :land)
cf1ecdbe3e47ff1caac5c1e21efcf0936e6ce2e9182a2fd21bebd91aae405cdf
zenhack/mule
pair.ml
module type Elt = sig include Comparable.S val sexp_of_t : t -> Sexp.t val t_of_sexp : Sexp.t -> t end module Make(Left:Elt)(Right:Elt) = struct module T = struct type t = (Left.t * Right.t) [@@deriving sexp, compare] end include T include Comparator.Make(T) end
null
https://raw.githubusercontent.com/zenhack/mule/f3e23342906d834abb9659c72a67c1405c936a00/src/mule/lib/util/pair.ml
ocaml
module type Elt = sig include Comparable.S val sexp_of_t : t -> Sexp.t val t_of_sexp : Sexp.t -> t end module Make(Left:Elt)(Right:Elt) = struct module T = struct type t = (Left.t * Right.t) [@@deriving sexp, compare] end include T include Comparator.Make(T) end
243a10c2b019d57d8269abbbc81790cacbec26dda9fb76769b1c0fcfa21c716d
soegaard/metapict
pointilism.rkt
#lang racket (require metapict) ;;; Pointilism ;;; ; Inspired by ; The image shows on the moon saluting the american flag . (def bm (read-bitmap "moonlanding.jpg")) ; read bitmap from disk (defv (w h) (bitmap-size bm)) ; determine width and height (define (draw-points n size) ; draw n circles of radius size (for/draw ([n n]) ; generate random point (w,h) (def x (random w)) (def y (random h)) find color of the ( x , in the image (def c (get-pixel bm x y)) ; use the color to draw a filled circle (color c (fill (circle (pt x y) size))))) (set-curve-pict-size 300 300) (with-window (window 0 w h 0) (draw (draw-points 100 40) (draw-points 200 20) (draw-points 400 10) (draw-points 4000 4)))
null
https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/examples/pointilism.rkt
racket
Inspired by read bitmap from disk determine width and height draw n circles of radius size generate random point (w,h) use the color to draw a filled circle
#lang racket (require metapict) Pointilism The image shows on the moon saluting the american flag . (for/draw ([n n]) (def x (random w)) (def y (random h)) find color of the ( x , in the image (def c (get-pixel bm x y)) (color c (fill (circle (pt x y) size))))) (set-curve-pict-size 300 300) (with-window (window 0 w h 0) (draw (draw-points 100 40) (draw-points 200 20) (draw-points 400 10) (draw-points 4000 4)))
3b0fc6b77fdf03deb2a3e776780e24a43e6e4e4a521177dc9832d71932755969
parenthesin/microservice-boilerplate-malli
http_test.clj
(ns unit.parenthesin.components.http-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [com.stuartsierra.component :as component] [matcher-combinators.test :refer [match?]] [parenthesin.components.http :as components.http] [parenthesin.utils :as u])) (use-fixtures :once u/with-malli-intrumentation) (defn- create-and-start-system! [{:keys [http]}] (component/start-system (component/system-map :http http))) (deftest http-mock-component-test (testing "HttpMock should return mocked reponses and log requests in the atom" (let [system (create-and-start-system! {:http (components.http/new-http-mock {"" {:status 200}})})] (is (match? {:status 200} (components.http/request (:http system) {:url ""}))) (is (match? {:status 500} (components.http/request (:http system) {:url ""}))) (is (match? ["" ""] (map :url (deref (get-in system [:http :requests]))))))))
null
https://raw.githubusercontent.com/parenthesin/microservice-boilerplate-malli/b4bd9fa95f3457dfac47b7b64e00e4f14ba7060c/test/unit/parenthesin/components/http_test.clj
clojure
(ns unit.parenthesin.components.http-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [com.stuartsierra.component :as component] [matcher-combinators.test :refer [match?]] [parenthesin.components.http :as components.http] [parenthesin.utils :as u])) (use-fixtures :once u/with-malli-intrumentation) (defn- create-and-start-system! [{:keys [http]}] (component/start-system (component/system-map :http http))) (deftest http-mock-component-test (testing "HttpMock should return mocked reponses and log requests in the atom" (let [system (create-and-start-system! {:http (components.http/new-http-mock {"" {:status 200}})})] (is (match? {:status 200} (components.http/request (:http system) {:url ""}))) (is (match? {:status 500} (components.http/request (:http system) {:url ""}))) (is (match? ["" ""] (map :url (deref (get-in system [:http :requests]))))))))
75975828f1165d880b530a5e20db72a5ad7b5690b2c3eb873bcea3ffbac2a541
ocaml-flambda/ocaml-jst
misc.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Miscellaneous useful types and functions {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) val fatal_error: string -> 'a val fatal_errorf: ('a, Format.formatter, unit, 'b) format4 -> 'a exception Fatal_error val try_finally : ?always:(unit -> unit) -> ?exceptionally:(unit -> unit) -> (unit -> 'a) -> 'a * [ try_finally work ~always ~exceptionally ] is designed to run code in [ work ] that may fail with an exception , and has two kind of cleanup routines : [ always ] , that must be run after any execution of the function ( typically , freeing system resources ) , and [ exceptionally ] , that should be run only if [ work ] or [ always ] failed with an exception ( typically , undoing user - visible state changes that would only make sense if the function completes correctly ) . For example : { [ let objfile = outputprefix ^ " .cmo " in let oc = open_out_bin objfile in Misc.try_finally ( fun ( ) - > bytecode + + Timings.(accumulate_time ( Generate sourcefile ) ) ( Emitcode.to_file oc modulename objfile ) ; Warnings.check_fatal ( ) ) ~always:(fun ( ) - > close_out oc ) ~exceptionally:(fun _ exn - > remove_file objfile ) ; ] } If [ exceptionally ] fail with an exception , it is propagated as usual . If [ always ] or [ exceptionally ] use exceptions internally for control - flow but do not raise , then [ ] is careful to preserve any exception backtrace coming from [ work ] or [ always ] for easier debugging . in [work] that may fail with an exception, and has two kind of cleanup routines: [always], that must be run after any execution of the function (typically, freeing system resources), and [exceptionally], that should be run only if [work] or [always] failed with an exception (typically, undoing user-visible state changes that would only make sense if the function completes correctly). For example: {[ let objfile = outputprefix ^ ".cmo" in let oc = open_out_bin objfile in Misc.try_finally (fun () -> bytecode ++ Timings.(accumulate_time (Generate sourcefile)) (Emitcode.to_file oc modulename objfile); Warnings.check_fatal ()) ~always:(fun () -> close_out oc) ~exceptionally:(fun _exn -> remove_file objfile); ]} If [exceptionally] fail with an exception, it is propagated as usual. If [always] or [exceptionally] use exceptions internally for control-flow but do not raise, then [try_finally] is careful to preserve any exception backtrace coming from [work] or [always] for easier debugging. *) val reraise_preserving_backtrace : exn -> (unit -> unit) -> 'a (** [reraise_preserving_backtrace e f] is (f (); raise e) except that the current backtrace is preserved, even if [f] uses exceptions internally. *) val map_end: ('a -> 'b) -> 'a list -> 'b list -> 'b list (* [map_end f l t] is [map f l @ t], just more efficient. *) val map_left_right: ('a -> 'b) -> 'a list -> 'b list (* Like [List.map], with guaranteed left-to-right evaluation order *) val for_all2: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool Same as [ List.for_all ] but for a binary predicate . In addition , this [ for_all2 ] never fails : given two lists with different lengths , it returns false . In addition, this [for_all2] never fails: given two lists with different lengths, it returns false. *) val replicate_list: 'a -> int -> 'a list (* [replicate_list elem n] is the list with [n] elements all identical to [elem]. *) val list_remove: 'a -> 'a list -> 'a list [ list_remove x l ] returns a copy of [ l ] with the first element equal to [ x ] removed . element equal to [x] removed. *) val split_last: 'a list -> 'a list * 'a (* Return the last element and the other elements of the given list. *) type ref_and_value = R : 'a ref * 'a -> ref_and_value val protect_refs : ref_and_value list -> (unit -> 'a) -> 'a (** [protect_refs l f] temporarily sets [r] to [v] for each [R (r, v)] in [l] while executing [f]. The previous contents of the references is restored even if [f] raises an exception, without altering the exception backtrace. *) module Stdlib : sig module List : sig type 'a t = 'a list val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int (** The lexicographic order supported by the provided order. There is no constraint on the relative lengths of the lists. *) val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool (** Returns [true] if and only if the given lists have the same length and content with respect to the given equality function. *) val some_if_all_elements_are_some : 'a option t -> 'a t option (** If all elements of the given list are [Some _] then [Some xs] is returned with the [xs] being the contents of those [Some]s, with order preserved. Otherwise return [None]. *) val map2_prefix : ('a -> 'b -> 'c) -> 'a t -> 'b t -> ('c t * 'b t) * [ let r1 , r2 = l1 l2 ] If [ l1 ] is of length n and [ l2 = h2 @ t2 ] with h2 of length n , r1 is [ List.map2 f l1 h1 ] and r2 is t2 . If [l1] is of length n and [l2 = h2 @ t2] with h2 of length n, r1 is [List.map2 f l1 h1] and r2 is t2. *) val split_at : int -> 'a t -> 'a t * 'a t * [ split_at n l ] returns the pair [ before , after ] where [ before ] is the [ n ] first elements of [ l ] and [ after ] the remaining ones . If [ l ] has less than [ n ] elements , raises Invalid_argument . the [n] first elements of [l] and [after] the remaining ones. If [l] has less than [n] elements, raises Invalid_argument. *) val map_sharing : ('a -> 'a) -> 'a t -> 'a t (** [map_sharing f l] is [map f l]. If for all elements of the list [f e == e] then [map_sharing f l == l] *) val is_prefix : equal:('a -> 'a -> bool) -> 'a list -> of_:'a list -> bool (** Returns [true] if and only if the given list, with respect to the given equality function on list members, is a prefix of the list [of_]. *) type 'a longest_common_prefix_result = private { longest_common_prefix : 'a list; first_without_longest_common_prefix : 'a list; second_without_longest_common_prefix : 'a list; } val find_and_chop_longest_common_prefix : equal:('a -> 'a -> bool) -> first:'a list -> second:'a list -> 'a longest_common_prefix_result (** Returns the longest list that, with respect to the provided equality function, is a prefix of both of the given lists. The input lists, each with such longest common prefix removed, are also returned. *) end module Option : sig type 'a t = 'a option val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit end module Array : sig val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool (** Same as [Array.exists2] from the standard library. *) val for_alli : (int -> 'a -> bool) -> 'a array -> bool * Same as [ Array.for_all ] from the standard library , but the function is applied with the index of the element as first argument , and the element itself as second argument . function is applied with the index of the element as first argument, and the element itself as second argument. *) val all_somes : 'a option array -> 'a array option end module String : sig include module type of String module Set : Set.S with type elt = string module Map : Map.S with type key = string module Tbl : Hashtbl.S with type key = string val print : Format.formatter -> t -> unit val for_all : (char -> bool) -> t -> bool val begins_with : ?from:int -> string -> prefix:string -> bool val split_on_string : string -> split_on:string -> string list val split_on_chars : string -> split_on:char list -> string list (** Splits on the last occurrence of the given character. *) val split_last_exn : string -> split_on:char -> string * string val starts_with : prefix:string -> string -> bool val ends_with : suffix:string -> string -> bool end module Int : sig include module type of Int val min : t -> t -> t val max : t -> t -> t end external compare : 'a -> 'a -> int = "%compare" end val find_in_path: string list -> string -> string (* Search a file in a list of directories. *) val find_in_path_rel: string list -> string -> string (* Search a relative file in a list of directories. *) val find_in_path_uncap: string list -> string -> string (* Same, but search also for uncapitalized name, i.e. if name is Foo.ml, allow /path/Foo.ml and /path/foo.ml to match. *) val remove_file: string -> unit (* Delete the given file if it exists. Never raise an error. *) val expand_directory: string -> string -> string (* [expand_directory alt file] eventually expands a [+] at the beginning of file into [alt] (an alternate root directory) *) val split_path_contents: ?sep:char -> string -> string list (* [split_path_contents ?sep s] interprets [s] as the value of a "PATH"-like variable and returns the corresponding list of directories. [s] is split using the platform-specific delimiter, or [~sep] if it is passed. Returns the empty list if [s] is empty. *) val create_hashtable: int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t (* Create a hashtable of the given size and fills it with the given bindings. *) val copy_file: in_channel -> out_channel -> unit [ copy_file ic oc ] reads the contents of file [ ic ] and copies them to [ oc ] . It stops when encountering EOF on [ ic ] . them to [oc]. It stops when encountering EOF on [ic]. *) val copy_file_chunk: in_channel -> out_channel -> int -> unit [ copy_file_chunk ic oc n ] reads [ n ] bytes from [ ic ] and copies them to [ oc ] . It raises [ End_of_file ] when encountering EOF on [ ic ] . them to [oc]. It raises [End_of_file] when encountering EOF on [ic]. *) val string_of_file: in_channel -> string [ string_of_file ic ] reads the contents of file [ ic ] and copies them to a string . It stops when encountering EOF on [ ic ] . them to a string. It stops when encountering EOF on [ic]. *) val output_to_file_via_temporary: ?mode:open_flag list -> string -> (string -> out_channel -> 'a) -> 'a (* Produce output in temporary file, then rename it (as atomically as possible) to the desired output file name. [output_to_file_via_temporary filename fn] opens a temporary file which is passed to [fn] (name + output channel). When [fn] returns, the channel is closed and the temporary file is renamed to [filename]. *) (** Open the given [filename] for writing (in binary mode), pass the [out_channel] to the given function, then close the channel. If the function raises an exception then [filename] will be removed. *) val protect_writing_to_file : filename:string -> f:(out_channel -> 'a) -> 'a val log2: int -> int [ log2 n ] returns [ s ] such that [ n = 1 lsl s ] if [ n ] is a power of 2 if [n] is a power of 2*) val align: int -> int -> int [ align n a ] rounds [ n ] upwards to a multiple of [ a ] ( a power of 2 ) . (a power of 2). *) val no_overflow_add: int -> int -> bool (* [no_overflow_add n1 n2] returns [true] if the computation of [n1 + n2] does not overflow. *) val no_overflow_sub: int -> int -> bool (* [no_overflow_sub n1 n2] returns [true] if the computation of [n1 - n2] does not overflow. *) val no_overflow_mul: int -> int -> bool (* [no_overflow_mul n1 n2] returns [true] if the computation of [n1 * n2] does not overflow. *) val no_overflow_lsl: int -> int -> bool [ no_overflow_lsl n k ] returns [ true ] if the computation of [ n lsl k ] does not overflow . [n lsl k] does not overflow. *) module Int_literal_converter : sig val int : string -> int val int32 : string -> int32 val int64 : string -> int64 val nativeint : string -> nativeint end val chop_extensions: string -> string (* Return the given file name without its extensions. The extensions is the longest suffix starting with a period and not including a directory separator, [.xyz.uvw] for instance. Return the given name if it does not contain an extension. *) val search_substring: string -> string -> int -> int [ search_substring pat str start ] returns the position of the first occurrence of string [ pat ] in string [ str ] . Search starts at offset [ start ] in [ str ] . Raise [ Not_found ] if [ pat ] does not occur . occurrence of string [pat] in string [str]. Search starts at offset [start] in [str]. Raise [Not_found] if [pat] does not occur. *) val replace_substring: before:string -> after:string -> string -> string (* [replace_substring ~before ~after str] replaces all occurrences of [before] with [after] in [str] and returns the resulting string. *) val rev_split_words: string -> string list (* [rev_split_words s] splits [s] in blank-separated words, and returns the list of words in reverse order. *) val get_ref: 'a list ref -> 'a list (* [get_ref lr] returns the content of the list reference [lr] and reset its content to the empty list. *) val set_or_ignore : ('a -> 'b option) -> 'b option ref -> 'a -> unit (* [set_or_ignore f opt x] sets [opt] to [f x] if it returns [Some _], or leaves it unmodified if it returns [None]. *) val fst3: 'a * 'b * 'c -> 'a val snd3: 'a * 'b * 'c -> 'b val thd3: 'a * 'b * 'c -> 'c val fst4: 'a * 'b * 'c * 'd -> 'a val snd4: 'a * 'b * 'c * 'd -> 'b val thd4: 'a * 'b * 'c * 'd -> 'c val for4: 'a * 'b * 'c * 'd -> 'd module LongString : sig type t = bytes array val create : int -> t val length : t -> int val get : t -> int -> char val set : t -> int -> char -> unit val blit : t -> int -> t -> int -> int -> unit val blit_string : string -> int -> t -> int -> int -> unit val output : out_channel -> t -> int -> int -> unit val input_bytes_into : t -> in_channel -> int -> unit val input_bytes : in_channel -> int -> t end val edit_distance : string -> string -> int -> int option * [ edit_distance a b cutoff ] computes the edit distance between strings [ a ] and [ b ] . To help efficiency , it uses a cutoff : if the distance [ d ] is smaller than [ cutoff ] , it returns [ Some d ] , else [ None ] . The distance algorithm currently used is Damerau - Levenshtein : it computes the number of insertion , deletion , substitution of letters , or swapping of adjacent letters to go from one word to the other . The particular algorithm may change in the future . strings [a] and [b]. To help efficiency, it uses a cutoff: if the distance [d] is smaller than [cutoff], it returns [Some d], else [None]. The distance algorithm currently used is Damerau-Levenshtein: it computes the number of insertion, deletion, substitution of letters, or swapping of adjacent letters to go from one word to the other. The particular algorithm may change in the future. *) val spellcheck : string list -> string -> string list * [ spellcheck env name ] takes a list of names [ env ] that exist in the current environment and an erroneous [ name ] , and returns a list of suggestions taken from [ env ] , that are close enough to [ name ] that it may be a typo for one of them . the current environment and an erroneous [name], and returns a list of suggestions taken from [env], that are close enough to [name] that it may be a typo for one of them. *) val did_you_mean : Format.formatter -> (unit -> string list) -> unit (** [did_you_mean ppf get_choices] hints that the user may have meant one of the option returned by calling [get_choices]. It does nothing if the returned list is empty. The [unit -> ...] thunking is meant to delay any potentially-slow computation (typically computing edit-distance with many things from the current environment) to when the hint message is to be printed. You should print an understandable error message before calling [did_you_mean], so that users get a clear notification of the failure even if producing the hint is slow. *) val cut_at : string -> char -> string * string * [ String.cut_at s c ] returns a pair containing the sub - string before the first occurrence of [ c ] in [ s ] , and the sub - string after the first occurrence of [ c ] in [ s ] . [ let ( before , after ) = String.cut_at s c in before ^ String.make 1 c ^ after ] is the identity if [ s ] contains [ c ] . Raise [ Not_found ] if the character does not appear in the string @since 4.01 the first occurrence of [c] in [s], and the sub-string after the first occurrence of [c] in [s]. [let (before, after) = String.cut_at s c in before ^ String.make 1 c ^ after] is the identity if [s] contains [c]. Raise [Not_found] if the character does not appear in the string @since 4.01 *) val ordinal_suffix : int -> string * [ ordinal_suffix n ] is the appropriate suffix to append to the numeral [ n ] as an ordinal number : [ 1 ] - > [ " st " ] , [ 2 ] - > [ " nd " ] , [ 3 ] - > [ " rd " ] , [ 4 ] - > [ " th " ] , and so on . Handles larger numbers ( e.g. , [ 42 ] - > [ " nd " ] ) and the numbers 11 - -13 ( which all get [ " th " ] ) correctly . an ordinal number: [1] -> ["st"], [2] -> ["nd"], [3] -> ["rd"], [4] -> ["th"], and so on. Handles larger numbers (e.g., [42] -> ["nd"]) and the numbers 11--13 (which all get ["th"]) correctly. *) Color handling module Color : sig type color = | Black | Red | Green | Yellow | Blue | Magenta | Cyan | White ;; type style = | FG of color (* foreground *) | BG of color (* background *) | Bold | Reset type Format.stag += Style of style list val ansi_of_style_l : style list -> string (* ANSI escape sequence for the given style *) type styles = { error: style list; warning: style list; loc: style list; } val default_styles: styles val get_styles: unit -> styles val set_styles: styles -> unit type setting = Auto | Always | Never val default_setting : setting val setup : setting option -> unit [ setup opt ] will enable or disable color handling on standard formatters according to the value of color setting [ opt ] . Only the first call to this function has an effect . according to the value of color setting [opt]. Only the first call to this function has an effect. *) val set_color_tag_handling : Format.formatter -> unit (* adds functions to support color tags to the given formatter. *) end (* See the -error-style option *) module Error_style : sig type setting = | Contextual | Short val default_setting : setting end val normalise_eol : string -> string * [ normalise_eol s ] returns a fresh copy of [ s ] with any ' \r ' characters removed . Intended for pre - processing text which will subsequently be printed on a channel which performs EOL transformations ( i.e. Windows ) removed. Intended for pre-processing text which will subsequently be printed on a channel which performs EOL transformations (i.e. Windows) *) val delete_eol_spaces : string -> string (** [delete_eol_spaces s] returns a fresh copy of [s] with any end of line spaces removed. Intended to normalize the output of the toplevel for tests. *) val pp_two_columns : ?sep:string -> ?max_lines:int -> Format.formatter -> (string * string) list -> unit * [ pp_two_columns ? sep ? max_lines ppf l ] prints the lines in [ l ] as two columns separated by [ sep ] ( " | " by default ) . [ max_lines ] can be used to indicate a maximum number of lines to print -- an ellipsis gets inserted at the middle if the input has too many lines . Example : { v pp_two_columns ~max_lines:3 Format.std_formatter [ " abc " , " hello " ; " def " , " zzz " ; " a " , " bllbl " ; " bb " , " dddddd " ; ] v } prints { v abc | hello ... bb | dddddd v } columns separated by [sep] ("|" by default). [max_lines] can be used to indicate a maximum number of lines to print -- an ellipsis gets inserted at the middle if the input has too many lines. Example: {v pp_two_columns ~max_lines:3 Format.std_formatter [ "abc", "hello"; "def", "zzz"; "a" , "bllbl"; "bb" , "dddddd"; ] v} prints {v abc | hello ... bb | dddddd v} *) (** configuration variables *) val show_config_and_exit : unit -> unit val show_config_variable_and_exit : string -> unit val get_build_path_prefix_map: unit -> Build_path_prefix_map.map option (** Returns the map encoded in the [BUILD_PATH_PREFIX_MAP] environment variable. *) val debug_prefix_map_flags: unit -> string list * Returns the list of [ --debug - prefix - map ] flags to be passed to the assembler , built from the [ BUILD_PATH_PREFIX_MAP ] environment variable . assembler, built from the [BUILD_PATH_PREFIX_MAP] environment variable. *) val print_if : Format.formatter -> bool ref -> (Format.formatter -> 'a -> unit) -> 'a -> 'a * [ print_if ppf flag fmt x ] prints [ x ] with [ fmt ] on [ ppf ] if [ b ] is true . type filepath = string type alerts = string Stdlib.String.Map.t module Bitmap : sig type t val make : int -> t val set : t -> int -> unit val clear : t -> int -> unit val get : t -> int -> bool val iter : (int -> unit) -> t -> unit end module Magic_number : sig * a typical magic number is " Caml1999I011 " ; it is formed of an alphanumeric prefix , here Caml1990I , followed by a version , here 011 . The prefix identifies the kind of the versioned data : here the I indicates that it is the magic number for .cmi files . All magic numbers have the same byte length , [ ] , and this is important for users as it gives them the number of bytes to read to obtain the byte sequence that should be a magic number . Typical user code will look like : { [ let ic = open_in_bin path in let magic = try with End_of_file - > ... in match Magic_number.parse magic with | Error parse_error - > ... | Ok info - > ... ] } A given compiler version expects one specific version for each kind of object file , and will fail if given an unsupported version . Because versions grow monotonically , you can compare the parsed version with the expected " current version " for a kind , to tell whether the wrong - magic object file comes from the past or from the future . An example of code block that expects the " currently supported version " of a given kind of magic numbers , here [ Cmxa ] , is as follows : { [ let ic = open_in_bin path in begin try Magic_number.(expect_current Cmxa ( get_info ic ) ) with | Parse_error error - > ... | Unexpected error - > ... end ; ... ] } Parse errors distinguish inputs that are [ Not_a_magic_number str ] , which are likely to come from the file being completely different , and [ Truncated str ] , raised by headers that are the ( possibly empty ) prefix of a valid magic number . Unexpected errors correspond to valid magic numbers that are not the one expected , either because it corresponds to a different kind , or to a newer or older version . The helper functions [ explain_parse_error ] and [ explain_unexpected_error ] will generate a textual explanation of each error , for use in error messages . @since 4.11.0 alphanumeric prefix, here Caml1990I, followed by a version, here 011. The prefix identifies the kind of the versioned data: here the I indicates that it is the magic number for .cmi files. All magic numbers have the same byte length, [magic_length], and this is important for users as it gives them the number of bytes to read to obtain the byte sequence that should be a magic number. Typical user code will look like: {[ let ic = open_in_bin path in let magic = try really_input_string ic Magic_number.magic_length with End_of_file -> ... in match Magic_number.parse magic with | Error parse_error -> ... | Ok info -> ... ]} A given compiler version expects one specific version for each kind of object file, and will fail if given an unsupported version. Because versions grow monotonically, you can compare the parsed version with the expected "current version" for a kind, to tell whether the wrong-magic object file comes from the past or from the future. An example of code block that expects the "currently supported version" of a given kind of magic numbers, here [Cmxa], is as follows: {[ let ic = open_in_bin path in begin try Magic_number.(expect_current Cmxa (get_info ic)) with | Parse_error error -> ... | Unexpected error -> ... end; ... ]} Parse errors distinguish inputs that are [Not_a_magic_number str], which are likely to come from the file being completely different, and [Truncated str], raised by headers that are the (possibly empty) prefix of a valid magic number. Unexpected errors correspond to valid magic numbers that are not the one expected, either because it corresponds to a different kind, or to a newer or older version. The helper functions [explain_parse_error] and [explain_unexpected_error] will generate a textual explanation of each error, for use in error messages. @since 4.11.0 *) type native_obj_config = { flambda : bool; } (** native object files have a format and magic number that depend on certain native-compiler configuration parameters. This configuration space is expressed by the [native_obj_config] type. *) val native_obj_config : native_obj_config (** the native object file configuration of the active/configured compiler. *) type version = int type kind = | Exec | Cmi | Cmo | Cma | Cmx of native_obj_config | Cmxa of native_obj_config | Cmxs | Cmt | Ast_impl | Ast_intf type info = { kind: kind; version: version; * Note : some versions of the compiler use the same [ version ] suffix for all kinds , but others use different versions counters for different kinds . We may only assume that versions are growing monotonically ( not necessarily always by one ) between compiler versions . for all kinds, but others use different versions counters for different kinds. We may only assume that versions are growing monotonically (not necessarily always by one) between compiler versions. *) } type raw = string * the type of raw magic numbers , such as " Caml1999A027 " for the .cma files of OCaml 4.10 such as "Caml1999A027" for the .cma files of OCaml 4.10 *) * { 3 Parsing magic numbers } type parse_error = | Truncated of string | Not_a_magic_number of string val explain_parse_error : kind option -> parse_error -> string (** Produces an explanation for a parse error. If no kind is provided, we use an unspecific formulation suggesting that any compiler-produced object file would have been satisfying. *) val parse : raw -> (info, parse_error) result (** Parses a raw magic number *) val read_info : in_channel -> (info, parse_error) result (** Read a raw magic number from an input channel. If the data read [str] is not a valid magic number, it can be recovered from the [Truncated str | Not_a_magic_number str] payload of the [Error parse_error] case. If parsing succeeds with an [Ok info] result, we know that exactly [magic_length] bytes have been consumed from the input_channel. If you also wish to enforce that the magic number is at the current version, see {!read_current_info} below. *) val magic_length : int (** all magic numbers take the same number of bytes *) (** {3 Checking that magic numbers are current} *) type 'a unexpected = { expected : 'a; actual : 'a } type unexpected_error = | Kind of kind unexpected | Version of kind * version unexpected val check_current : kind -> info -> (unit, unexpected_error) result (** [check_current kind info] checks that the provided magic [info] is the current version of [kind]'s magic header. *) val explain_unexpected_error : unexpected_error -> string (** Provides an explanation of the [unexpected_error]. *) type error = | Parse_error of parse_error | Unexpected_error of unexpected_error val read_current_info : expected_kind:kind option -> in_channel -> (info, error) result (** Read a magic number as [read_info], and check that it is the current version as its kind. If the [expected_kind] argument is [None], any kind is accepted. *) * { 3 Information on magic numbers } val string_of_kind : kind -> string (** a user-printable string for a kind, eg. "exec" or "cmo", to use in error messages. *) val human_name_of_kind : kind -> string (** a user-meaningful name for a kind, eg. "executable file" or "bytecode object file", to use in error messages. *) val current_raw : kind -> raw (** the current magic number of each kind *) val current_version : kind -> version (** the current version of each kind *) * { 3 Raw representations } Mainly for internal usage and testing . Mainly for internal usage and testing. *) type raw_kind = string (** the type of raw magic numbers kinds, such as "Caml1999A" for .cma files *) val parse_kind : raw_kind -> kind option (** parse a raw kind into a kind *) val raw_kind : kind -> raw_kind (** the current raw representation of a kind. In some cases the raw representation of a kind has changed over compiler versions, so other files of the same kind may have different raw kinds. Note that all currently known cases are parsed correctly by [parse_kind]. *) val raw : info -> raw (** A valid raw representation of the magic number. Due to past and future changes in the string representation of magic numbers, we cannot guarantee that the raw strings returned for past and future versions actually match the expectations of those compilers. The representation is accurate for current versions, and it is correctly parsed back into the desired version by the parsing functions above. *) (**/**) val all_kinds : kind list end
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/utils/misc.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Miscellaneous useful types and functions {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. * [reraise_preserving_backtrace e f] is (f (); raise e) except that the current backtrace is preserved, even if [f] uses exceptions internally. [map_end f l t] is [map f l @ t], just more efficient. Like [List.map], with guaranteed left-to-right evaluation order [replicate_list elem n] is the list with [n] elements all identical to [elem]. Return the last element and the other elements of the given list. * [protect_refs l f] temporarily sets [r] to [v] for each [R (r, v)] in [l] while executing [f]. The previous contents of the references is restored even if [f] raises an exception, without altering the exception backtrace. * The lexicographic order supported by the provided order. There is no constraint on the relative lengths of the lists. * Returns [true] if and only if the given lists have the same length and content with respect to the given equality function. * If all elements of the given list are [Some _] then [Some xs] is returned with the [xs] being the contents of those [Some]s, with order preserved. Otherwise return [None]. * [map_sharing f l] is [map f l]. If for all elements of the list [f e == e] then [map_sharing f l == l] * Returns [true] if and only if the given list, with respect to the given equality function on list members, is a prefix of the list [of_]. * Returns the longest list that, with respect to the provided equality function, is a prefix of both of the given lists. The input lists, each with such longest common prefix removed, are also returned. * Same as [Array.exists2] from the standard library. * Splits on the last occurrence of the given character. Search a file in a list of directories. Search a relative file in a list of directories. Same, but search also for uncapitalized name, i.e. if name is Foo.ml, allow /path/Foo.ml and /path/foo.ml to match. Delete the given file if it exists. Never raise an error. [expand_directory alt file] eventually expands a [+] at the beginning of file into [alt] (an alternate root directory) [split_path_contents ?sep s] interprets [s] as the value of a "PATH"-like variable and returns the corresponding list of directories. [s] is split using the platform-specific delimiter, or [~sep] if it is passed. Returns the empty list if [s] is empty. Create a hashtable of the given size and fills it with the given bindings. Produce output in temporary file, then rename it (as atomically as possible) to the desired output file name. [output_to_file_via_temporary filename fn] opens a temporary file which is passed to [fn] (name + output channel). When [fn] returns, the channel is closed and the temporary file is renamed to [filename]. * Open the given [filename] for writing (in binary mode), pass the [out_channel] to the given function, then close the channel. If the function raises an exception then [filename] will be removed. [no_overflow_add n1 n2] returns [true] if the computation of [n1 + n2] does not overflow. [no_overflow_sub n1 n2] returns [true] if the computation of [n1 - n2] does not overflow. [no_overflow_mul n1 n2] returns [true] if the computation of [n1 * n2] does not overflow. Return the given file name without its extensions. The extensions is the longest suffix starting with a period and not including a directory separator, [.xyz.uvw] for instance. Return the given name if it does not contain an extension. [replace_substring ~before ~after str] replaces all occurrences of [before] with [after] in [str] and returns the resulting string. [rev_split_words s] splits [s] in blank-separated words, and returns the list of words in reverse order. [get_ref lr] returns the content of the list reference [lr] and reset its content to the empty list. [set_or_ignore f opt x] sets [opt] to [f x] if it returns [Some _], or leaves it unmodified if it returns [None]. * [did_you_mean ppf get_choices] hints that the user may have meant one of the option returned by calling [get_choices]. It does nothing if the returned list is empty. The [unit -> ...] thunking is meant to delay any potentially-slow computation (typically computing edit-distance with many things from the current environment) to when the hint message is to be printed. You should print an understandable error message before calling [did_you_mean], so that users get a clear notification of the failure even if producing the hint is slow. foreground background ANSI escape sequence for the given style adds functions to support color tags to the given formatter. See the -error-style option * [delete_eol_spaces s] returns a fresh copy of [s] with any end of line spaces removed. Intended to normalize the output of the toplevel for tests. * configuration variables * Returns the map encoded in the [BUILD_PATH_PREFIX_MAP] environment variable. * native object files have a format and magic number that depend on certain native-compiler configuration parameters. This configuration space is expressed by the [native_obj_config] type. * the native object file configuration of the active/configured compiler. * Produces an explanation for a parse error. If no kind is provided, we use an unspecific formulation suggesting that any compiler-produced object file would have been satisfying. * Parses a raw magic number * Read a raw magic number from an input channel. If the data read [str] is not a valid magic number, it can be recovered from the [Truncated str | Not_a_magic_number str] payload of the [Error parse_error] case. If parsing succeeds with an [Ok info] result, we know that exactly [magic_length] bytes have been consumed from the input_channel. If you also wish to enforce that the magic number is at the current version, see {!read_current_info} below. * all magic numbers take the same number of bytes * {3 Checking that magic numbers are current} * [check_current kind info] checks that the provided magic [info] is the current version of [kind]'s magic header. * Provides an explanation of the [unexpected_error]. * Read a magic number as [read_info], and check that it is the current version as its kind. If the [expected_kind] argument is [None], any kind is accepted. * a user-printable string for a kind, eg. "exec" or "cmo", to use in error messages. * a user-meaningful name for a kind, eg. "executable file" or "bytecode object file", to use in error messages. * the current magic number of each kind * the current version of each kind * the type of raw magic numbers kinds, such as "Caml1999A" for .cma files * parse a raw kind into a kind * the current raw representation of a kind. In some cases the raw representation of a kind has changed over compiler versions, so other files of the same kind may have different raw kinds. Note that all currently known cases are parsed correctly by [parse_kind]. * A valid raw representation of the magic number. Due to past and future changes in the string representation of magic numbers, we cannot guarantee that the raw strings returned for past and future versions actually match the expectations of those compilers. The representation is accurate for current versions, and it is correctly parsed back into the desired version by the parsing functions above. */*
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the val fatal_error: string -> 'a val fatal_errorf: ('a, Format.formatter, unit, 'b) format4 -> 'a exception Fatal_error val try_finally : ?always:(unit -> unit) -> ?exceptionally:(unit -> unit) -> (unit -> 'a) -> 'a * [ try_finally work ~always ~exceptionally ] is designed to run code in [ work ] that may fail with an exception , and has two kind of cleanup routines : [ always ] , that must be run after any execution of the function ( typically , freeing system resources ) , and [ exceptionally ] , that should be run only if [ work ] or [ always ] failed with an exception ( typically , undoing user - visible state changes that would only make sense if the function completes correctly ) . For example : { [ let objfile = outputprefix ^ " .cmo " in let oc = open_out_bin objfile in Misc.try_finally ( fun ( ) - > bytecode + + Timings.(accumulate_time ( Generate sourcefile ) ) ( Emitcode.to_file oc modulename objfile ) ; Warnings.check_fatal ( ) ) ~always:(fun ( ) - > close_out oc ) ~exceptionally:(fun _ exn - > remove_file objfile ) ; ] } If [ exceptionally ] fail with an exception , it is propagated as usual . If [ always ] or [ exceptionally ] use exceptions internally for control - flow but do not raise , then [ ] is careful to preserve any exception backtrace coming from [ work ] or [ always ] for easier debugging . in [work] that may fail with an exception, and has two kind of cleanup routines: [always], that must be run after any execution of the function (typically, freeing system resources), and [exceptionally], that should be run only if [work] or [always] failed with an exception (typically, undoing user-visible state changes that would only make sense if the function completes correctly). For example: {[ let objfile = outputprefix ^ ".cmo" in let oc = open_out_bin objfile in Misc.try_finally (fun () -> bytecode ++ Timings.(accumulate_time (Generate sourcefile)) (Emitcode.to_file oc modulename objfile); Warnings.check_fatal ()) ~always:(fun () -> close_out oc) ~exceptionally:(fun _exn -> remove_file objfile); ]} If [exceptionally] fail with an exception, it is propagated as usual. If [always] or [exceptionally] use exceptions internally for control-flow but do not raise, then [try_finally] is careful to preserve any exception backtrace coming from [work] or [always] for easier debugging. *) val reraise_preserving_backtrace : exn -> (unit -> unit) -> 'a val map_end: ('a -> 'b) -> 'a list -> 'b list -> 'b list val map_left_right: ('a -> 'b) -> 'a list -> 'b list val for_all2: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool Same as [ List.for_all ] but for a binary predicate . In addition , this [ for_all2 ] never fails : given two lists with different lengths , it returns false . In addition, this [for_all2] never fails: given two lists with different lengths, it returns false. *) val replicate_list: 'a -> int -> 'a list val list_remove: 'a -> 'a list -> 'a list [ list_remove x l ] returns a copy of [ l ] with the first element equal to [ x ] removed . element equal to [x] removed. *) val split_last: 'a list -> 'a list * 'a type ref_and_value = R : 'a ref * 'a -> ref_and_value val protect_refs : ref_and_value list -> (unit -> 'a) -> 'a module Stdlib : sig module List : sig type 'a t = 'a list val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val some_if_all_elements_are_some : 'a option t -> 'a t option val map2_prefix : ('a -> 'b -> 'c) -> 'a t -> 'b t -> ('c t * 'b t) * [ let r1 , r2 = l1 l2 ] If [ l1 ] is of length n and [ l2 = h2 @ t2 ] with h2 of length n , r1 is [ List.map2 f l1 h1 ] and r2 is t2 . If [l1] is of length n and [l2 = h2 @ t2] with h2 of length n, r1 is [List.map2 f l1 h1] and r2 is t2. *) val split_at : int -> 'a t -> 'a t * 'a t * [ split_at n l ] returns the pair [ before , after ] where [ before ] is the [ n ] first elements of [ l ] and [ after ] the remaining ones . If [ l ] has less than [ n ] elements , raises Invalid_argument . the [n] first elements of [l] and [after] the remaining ones. If [l] has less than [n] elements, raises Invalid_argument. *) val map_sharing : ('a -> 'a) -> 'a t -> 'a t val is_prefix : equal:('a -> 'a -> bool) -> 'a list -> of_:'a list -> bool type 'a longest_common_prefix_result = private { longest_common_prefix : 'a list; first_without_longest_common_prefix : 'a list; second_without_longest_common_prefix : 'a list; } val find_and_chop_longest_common_prefix : equal:('a -> 'a -> bool) -> first:'a list -> second:'a list -> 'a longest_common_prefix_result end module Option : sig type 'a t = 'a option val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit end module Array : sig val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool val for_alli : (int -> 'a -> bool) -> 'a array -> bool * Same as [ Array.for_all ] from the standard library , but the function is applied with the index of the element as first argument , and the element itself as second argument . function is applied with the index of the element as first argument, and the element itself as second argument. *) val all_somes : 'a option array -> 'a array option end module String : sig include module type of String module Set : Set.S with type elt = string module Map : Map.S with type key = string module Tbl : Hashtbl.S with type key = string val print : Format.formatter -> t -> unit val for_all : (char -> bool) -> t -> bool val begins_with : ?from:int -> string -> prefix:string -> bool val split_on_string : string -> split_on:string -> string list val split_on_chars : string -> split_on:char list -> string list val split_last_exn : string -> split_on:char -> string * string val starts_with : prefix:string -> string -> bool val ends_with : suffix:string -> string -> bool end module Int : sig include module type of Int val min : t -> t -> t val max : t -> t -> t end external compare : 'a -> 'a -> int = "%compare" end val find_in_path: string list -> string -> string val find_in_path_rel: string list -> string -> string val find_in_path_uncap: string list -> string -> string val remove_file: string -> unit val expand_directory: string -> string -> string val split_path_contents: ?sep:char -> string -> string list val create_hashtable: int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t val copy_file: in_channel -> out_channel -> unit [ copy_file ic oc ] reads the contents of file [ ic ] and copies them to [ oc ] . It stops when encountering EOF on [ ic ] . them to [oc]. It stops when encountering EOF on [ic]. *) val copy_file_chunk: in_channel -> out_channel -> int -> unit [ copy_file_chunk ic oc n ] reads [ n ] bytes from [ ic ] and copies them to [ oc ] . It raises [ End_of_file ] when encountering EOF on [ ic ] . them to [oc]. It raises [End_of_file] when encountering EOF on [ic]. *) val string_of_file: in_channel -> string [ string_of_file ic ] reads the contents of file [ ic ] and copies them to a string . It stops when encountering EOF on [ ic ] . them to a string. It stops when encountering EOF on [ic]. *) val output_to_file_via_temporary: ?mode:open_flag list -> string -> (string -> out_channel -> 'a) -> 'a val protect_writing_to_file : filename:string -> f:(out_channel -> 'a) -> 'a val log2: int -> int [ log2 n ] returns [ s ] such that [ n = 1 lsl s ] if [ n ] is a power of 2 if [n] is a power of 2*) val align: int -> int -> int [ align n a ] rounds [ n ] upwards to a multiple of [ a ] ( a power of 2 ) . (a power of 2). *) val no_overflow_add: int -> int -> bool val no_overflow_sub: int -> int -> bool val no_overflow_mul: int -> int -> bool val no_overflow_lsl: int -> int -> bool [ no_overflow_lsl n k ] returns [ true ] if the computation of [ n lsl k ] does not overflow . [n lsl k] does not overflow. *) module Int_literal_converter : sig val int : string -> int val int32 : string -> int32 val int64 : string -> int64 val nativeint : string -> nativeint end val chop_extensions: string -> string val search_substring: string -> string -> int -> int [ search_substring pat str start ] returns the position of the first occurrence of string [ pat ] in string [ str ] . Search starts at offset [ start ] in [ str ] . Raise [ Not_found ] if [ pat ] does not occur . occurrence of string [pat] in string [str]. Search starts at offset [start] in [str]. Raise [Not_found] if [pat] does not occur. *) val replace_substring: before:string -> after:string -> string -> string val rev_split_words: string -> string list val get_ref: 'a list ref -> 'a list val set_or_ignore : ('a -> 'b option) -> 'b option ref -> 'a -> unit val fst3: 'a * 'b * 'c -> 'a val snd3: 'a * 'b * 'c -> 'b val thd3: 'a * 'b * 'c -> 'c val fst4: 'a * 'b * 'c * 'd -> 'a val snd4: 'a * 'b * 'c * 'd -> 'b val thd4: 'a * 'b * 'c * 'd -> 'c val for4: 'a * 'b * 'c * 'd -> 'd module LongString : sig type t = bytes array val create : int -> t val length : t -> int val get : t -> int -> char val set : t -> int -> char -> unit val blit : t -> int -> t -> int -> int -> unit val blit_string : string -> int -> t -> int -> int -> unit val output : out_channel -> t -> int -> int -> unit val input_bytes_into : t -> in_channel -> int -> unit val input_bytes : in_channel -> int -> t end val edit_distance : string -> string -> int -> int option * [ edit_distance a b cutoff ] computes the edit distance between strings [ a ] and [ b ] . To help efficiency , it uses a cutoff : if the distance [ d ] is smaller than [ cutoff ] , it returns [ Some d ] , else [ None ] . The distance algorithm currently used is Damerau - Levenshtein : it computes the number of insertion , deletion , substitution of letters , or swapping of adjacent letters to go from one word to the other . The particular algorithm may change in the future . strings [a] and [b]. To help efficiency, it uses a cutoff: if the distance [d] is smaller than [cutoff], it returns [Some d], else [None]. The distance algorithm currently used is Damerau-Levenshtein: it computes the number of insertion, deletion, substitution of letters, or swapping of adjacent letters to go from one word to the other. The particular algorithm may change in the future. *) val spellcheck : string list -> string -> string list * [ spellcheck env name ] takes a list of names [ env ] that exist in the current environment and an erroneous [ name ] , and returns a list of suggestions taken from [ env ] , that are close enough to [ name ] that it may be a typo for one of them . the current environment and an erroneous [name], and returns a list of suggestions taken from [env], that are close enough to [name] that it may be a typo for one of them. *) val did_you_mean : Format.formatter -> (unit -> string list) -> unit val cut_at : string -> char -> string * string * [ String.cut_at s c ] returns a pair containing the sub - string before the first occurrence of [ c ] in [ s ] , and the sub - string after the first occurrence of [ c ] in [ s ] . [ let ( before , after ) = String.cut_at s c in before ^ String.make 1 c ^ after ] is the identity if [ s ] contains [ c ] . Raise [ Not_found ] if the character does not appear in the string @since 4.01 the first occurrence of [c] in [s], and the sub-string after the first occurrence of [c] in [s]. [let (before, after) = String.cut_at s c in before ^ String.make 1 c ^ after] is the identity if [s] contains [c]. Raise [Not_found] if the character does not appear in the string @since 4.01 *) val ordinal_suffix : int -> string * [ ordinal_suffix n ] is the appropriate suffix to append to the numeral [ n ] as an ordinal number : [ 1 ] - > [ " st " ] , [ 2 ] - > [ " nd " ] , [ 3 ] - > [ " rd " ] , [ 4 ] - > [ " th " ] , and so on . Handles larger numbers ( e.g. , [ 42 ] - > [ " nd " ] ) and the numbers 11 - -13 ( which all get [ " th " ] ) correctly . an ordinal number: [1] -> ["st"], [2] -> ["nd"], [3] -> ["rd"], [4] -> ["th"], and so on. Handles larger numbers (e.g., [42] -> ["nd"]) and the numbers 11--13 (which all get ["th"]) correctly. *) Color handling module Color : sig type color = | Black | Red | Green | Yellow | Blue | Magenta | Cyan | White ;; type style = | Bold | Reset type Format.stag += Style of style list val ansi_of_style_l : style list -> string type styles = { error: style list; warning: style list; loc: style list; } val default_styles: styles val get_styles: unit -> styles val set_styles: styles -> unit type setting = Auto | Always | Never val default_setting : setting val setup : setting option -> unit [ setup opt ] will enable or disable color handling on standard formatters according to the value of color setting [ opt ] . Only the first call to this function has an effect . according to the value of color setting [opt]. Only the first call to this function has an effect. *) val set_color_tag_handling : Format.formatter -> unit end module Error_style : sig type setting = | Contextual | Short val default_setting : setting end val normalise_eol : string -> string * [ normalise_eol s ] returns a fresh copy of [ s ] with any ' \r ' characters removed . Intended for pre - processing text which will subsequently be printed on a channel which performs EOL transformations ( i.e. Windows ) removed. Intended for pre-processing text which will subsequently be printed on a channel which performs EOL transformations (i.e. Windows) *) val delete_eol_spaces : string -> string val pp_two_columns : ?sep:string -> ?max_lines:int -> Format.formatter -> (string * string) list -> unit * [ pp_two_columns ? sep ? max_lines ppf l ] prints the lines in [ l ] as two columns separated by [ sep ] ( " | " by default ) . [ max_lines ] can be used to indicate a maximum number of lines to print -- an ellipsis gets inserted at the middle if the input has too many lines . Example : { v pp_two_columns ~max_lines:3 Format.std_formatter [ " abc " , " hello " ; " def " , " zzz " ; " a " , " bllbl " ; " bb " , " dddddd " ; ] v } prints { v abc | hello ... bb | dddddd v } columns separated by [sep] ("|" by default). [max_lines] can be used to indicate a maximum number of lines to print -- an ellipsis gets inserted at the middle if the input has too many lines. Example: {v pp_two_columns ~max_lines:3 Format.std_formatter [ "abc", "hello"; "def", "zzz"; "a" , "bllbl"; "bb" , "dddddd"; ] v} prints {v abc | hello ... bb | dddddd v} *) val show_config_and_exit : unit -> unit val show_config_variable_and_exit : string -> unit val get_build_path_prefix_map: unit -> Build_path_prefix_map.map option val debug_prefix_map_flags: unit -> string list * Returns the list of [ --debug - prefix - map ] flags to be passed to the assembler , built from the [ BUILD_PATH_PREFIX_MAP ] environment variable . assembler, built from the [BUILD_PATH_PREFIX_MAP] environment variable. *) val print_if : Format.formatter -> bool ref -> (Format.formatter -> 'a -> unit) -> 'a -> 'a * [ print_if ppf flag fmt x ] prints [ x ] with [ fmt ] on [ ppf ] if [ b ] is true . type filepath = string type alerts = string Stdlib.String.Map.t module Bitmap : sig type t val make : int -> t val set : t -> int -> unit val clear : t -> int -> unit val get : t -> int -> bool val iter : (int -> unit) -> t -> unit end module Magic_number : sig * a typical magic number is " Caml1999I011 " ; it is formed of an alphanumeric prefix , here Caml1990I , followed by a version , here 011 . The prefix identifies the kind of the versioned data : here the I indicates that it is the magic number for .cmi files . All magic numbers have the same byte length , [ ] , and this is important for users as it gives them the number of bytes to read to obtain the byte sequence that should be a magic number . Typical user code will look like : { [ let ic = open_in_bin path in let magic = try with End_of_file - > ... in match Magic_number.parse magic with | Error parse_error - > ... | Ok info - > ... ] } A given compiler version expects one specific version for each kind of object file , and will fail if given an unsupported version . Because versions grow monotonically , you can compare the parsed version with the expected " current version " for a kind , to tell whether the wrong - magic object file comes from the past or from the future . An example of code block that expects the " currently supported version " of a given kind of magic numbers , here [ Cmxa ] , is as follows : { [ let ic = open_in_bin path in begin try Magic_number.(expect_current Cmxa ( get_info ic ) ) with | Parse_error error - > ... | Unexpected error - > ... end ; ... ] } Parse errors distinguish inputs that are [ Not_a_magic_number str ] , which are likely to come from the file being completely different , and [ Truncated str ] , raised by headers that are the ( possibly empty ) prefix of a valid magic number . Unexpected errors correspond to valid magic numbers that are not the one expected , either because it corresponds to a different kind , or to a newer or older version . The helper functions [ explain_parse_error ] and [ explain_unexpected_error ] will generate a textual explanation of each error , for use in error messages . @since 4.11.0 alphanumeric prefix, here Caml1990I, followed by a version, here 011. The prefix identifies the kind of the versioned data: here the I indicates that it is the magic number for .cmi files. All magic numbers have the same byte length, [magic_length], and this is important for users as it gives them the number of bytes to read to obtain the byte sequence that should be a magic number. Typical user code will look like: {[ let ic = open_in_bin path in let magic = try really_input_string ic Magic_number.magic_length with End_of_file -> ... in match Magic_number.parse magic with | Error parse_error -> ... | Ok info -> ... ]} A given compiler version expects one specific version for each kind of object file, and will fail if given an unsupported version. Because versions grow monotonically, you can compare the parsed version with the expected "current version" for a kind, to tell whether the wrong-magic object file comes from the past or from the future. An example of code block that expects the "currently supported version" of a given kind of magic numbers, here [Cmxa], is as follows: {[ let ic = open_in_bin path in begin try Magic_number.(expect_current Cmxa (get_info ic)) with | Parse_error error -> ... | Unexpected error -> ... end; ... ]} Parse errors distinguish inputs that are [Not_a_magic_number str], which are likely to come from the file being completely different, and [Truncated str], raised by headers that are the (possibly empty) prefix of a valid magic number. Unexpected errors correspond to valid magic numbers that are not the one expected, either because it corresponds to a different kind, or to a newer or older version. The helper functions [explain_parse_error] and [explain_unexpected_error] will generate a textual explanation of each error, for use in error messages. @since 4.11.0 *) type native_obj_config = { flambda : bool; } val native_obj_config : native_obj_config type version = int type kind = | Exec | Cmi | Cmo | Cma | Cmx of native_obj_config | Cmxa of native_obj_config | Cmxs | Cmt | Ast_impl | Ast_intf type info = { kind: kind; version: version; * Note : some versions of the compiler use the same [ version ] suffix for all kinds , but others use different versions counters for different kinds . We may only assume that versions are growing monotonically ( not necessarily always by one ) between compiler versions . for all kinds, but others use different versions counters for different kinds. We may only assume that versions are growing monotonically (not necessarily always by one) between compiler versions. *) } type raw = string * the type of raw magic numbers , such as " Caml1999A027 " for the .cma files of OCaml 4.10 such as "Caml1999A027" for the .cma files of OCaml 4.10 *) * { 3 Parsing magic numbers } type parse_error = | Truncated of string | Not_a_magic_number of string val explain_parse_error : kind option -> parse_error -> string val parse : raw -> (info, parse_error) result val read_info : in_channel -> (info, parse_error) result val magic_length : int type 'a unexpected = { expected : 'a; actual : 'a } type unexpected_error = | Kind of kind unexpected | Version of kind * version unexpected val check_current : kind -> info -> (unit, unexpected_error) result val explain_unexpected_error : unexpected_error -> string type error = | Parse_error of parse_error | Unexpected_error of unexpected_error val read_current_info : expected_kind:kind option -> in_channel -> (info, error) result * { 3 Information on magic numbers } val string_of_kind : kind -> string val human_name_of_kind : kind -> string val current_raw : kind -> raw val current_version : kind -> version * { 3 Raw representations } Mainly for internal usage and testing . Mainly for internal usage and testing. *) type raw_kind = string val parse_kind : raw_kind -> kind option val raw_kind : kind -> raw_kind val raw : info -> raw val all_kinds : kind list end
d11b095e70eff7677302b66cdfc3f298e591c44b15973048aa35faa4e2a7db37
xu-hao/QueryArrow
Local.hs
# LANGUAGE FlexibleContexts , MultiParamTypeClasses , FlexibleInstances , OverloadedStrings , GADTs , ExistentialQuantification , TemplateHaskell , ForeignFunctionInterface # module QueryArrow.FFI.C.Local where import Foreign.StablePtr import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import Foreign.Storable import System.Log.Logger (errorM, infoM) import QueryArrow.FFI.Service import QueryArrow.FFI.Service.Local foreign export ccall hs_local :: Ptr (StablePtr (QueryArrowService Session)) -> IO Int hs_local :: Ptr (StablePtr (QueryArrowService Session)) -> IO Int hs_local svcptrptr = do ptr <- newStablePtr localService poke svcptrptr ptr return 0
null
https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-ffi-c-local/src/QueryArrow/FFI/C/Local.hs
haskell
# LANGUAGE FlexibleContexts , MultiParamTypeClasses , FlexibleInstances , OverloadedStrings , GADTs , ExistentialQuantification , TemplateHaskell , ForeignFunctionInterface # module QueryArrow.FFI.C.Local where import Foreign.StablePtr import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import Foreign.Storable import System.Log.Logger (errorM, infoM) import QueryArrow.FFI.Service import QueryArrow.FFI.Service.Local foreign export ccall hs_local :: Ptr (StablePtr (QueryArrowService Session)) -> IO Int hs_local :: Ptr (StablePtr (QueryArrowService Session)) -> IO Int hs_local svcptrptr = do ptr <- newStablePtr localService poke svcptrptr ptr return 0
743de67396406daddd50b37f91ca15c9391fe7463f66e99de5072c8607aa46b3
facebook/infer
RacerDFileAnalysis.ml
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module AccessExpression = HilExp.AccessExpression module F = Format module MF = MarkupFormatter let describe_exp = MF.wrap_monospaced RacerDDomain.pp_exp let describe_pname = MF.wrap_monospaced (Procname.pp_simplified_string ~withclass:true) let pp_access fmt (t : RacerDDomain.AccessSnapshot.t) = match t.elem.access with | Read {exp} | Write {exp} -> describe_exp fmt exp | ContainerRead {exp; pname} | ContainerWrite {exp; pname} -> F.fprintf fmt "container %a via call to %a" describe_exp exp describe_pname pname | InterfaceCall _ as access -> RacerDDomain.Access.pp fmt access type reported_access = { threads: RacerDDomain.ThreadsDomain.t ; snapshot: RacerDDomain.AccessSnapshot.t ; tenv: Tenv.t ; procname: Procname.t } module ReportedSet : sig (** Type for deduplicating and storing reports. *) type t val reset : t -> t (** Reset recorded writes and reads, while maintaining the same [IssueLog.t]. *) val empty_of_issue_log : IssueLog.t -> t (** Create a set of reports containing the given [IssueLog.t] but otherwise having no records of previous reports. *) val to_issue_log : t -> IssueLog.t (** Recover deduplicated [IssueLog.t] from [t]. *) val deduplicate : f:(reported_access -> IssueLog.t -> IssueLog.t) -> reported_access -> t -> t (** Deduplicate [f]. *) end = struct type reported_set = { sites: CallSite.Set.t ; writes: Procname.Set.t ; reads: Procname.Set.t ; unannotated_calls: Procname.Set.t } let empty_reported_set = { sites= CallSite.Set.empty ; reads= Procname.Set.empty ; writes= Procname.Set.empty ; unannotated_calls= Procname.Set.empty } type t = reported_set * IssueLog.t let empty_of_issue_log issue_log = (empty_reported_set, issue_log) let to_issue_log = snd let reset (reported_set, issue_log) = ({reported_set with writes= Procname.Set.empty; reads= Procname.Set.empty}, issue_log) let is_duplicate {snapshot; procname} (reported_set, _) = let call_site = CallSite.make procname (RacerDDomain.AccessSnapshot.get_loc snapshot) in CallSite.Set.mem call_site reported_set.sites || match snapshot.elem.access with | Write _ | ContainerWrite _ -> Procname.Set.mem procname reported_set.writes | Read _ | ContainerRead _ -> Procname.Set.mem procname reported_set.reads | InterfaceCall _ -> Procname.Set.mem procname reported_set.unannotated_calls let update {snapshot; procname} (reported_set, issue_log) = let call_site = CallSite.make procname (RacerDDomain.AccessSnapshot.get_loc snapshot) in let sites = CallSite.Set.add call_site reported_set.sites in let reported_set = {reported_set with sites} in let reported_set = match snapshot.elem.access with | Write _ | ContainerWrite _ -> {reported_set with writes= Procname.Set.add procname reported_set.writes} | Read _ | ContainerRead _ -> {reported_set with reads= Procname.Set.add procname reported_set.reads} | InterfaceCall _ -> { reported_set with unannotated_calls= Procname.Set.add procname reported_set.unannotated_calls } in (reported_set, issue_log) let deduplicate ~f reported_access ((reported_set, issue_log) as acc) = if Config.deduplicate && is_duplicate reported_access acc then acc else update reported_access (reported_set, f reported_access issue_log) end module PathModuloThis : Caml.Map.OrderedType with type t = AccessPath.t = struct type t = AccessPath.t type var_ = Var.t let compare_var_ = Var.compare_modulo_this let compare = [%compare: (var_ * Typ.t) * AccessPath.access list] end (** Map containing reported accesses, which groups them in lists, by abstract location. The equivalence relation used for grouping them is equality of access paths. This is slightly complicated because local variables contain the pname of the function declaring them. Here we want a purely name-based comparison, and in particular that [this == this] regardless the method declaring it. Hence the redefined comparison functions. *) module ReportMap : sig type t val empty : t val add : reported_access -> t -> t val fold : (reported_access list -> 'a -> 'a) -> t -> 'a -> 'a val filter_container_accesses : (PathModuloThis.t -> bool) -> t -> t end = struct module Key = struct type t = Location of PathModuloThis.t | Container of PathModuloThis.t | Call of Procname.t [@@deriving compare] let of_access (access : RacerDDomain.Access.t) = match access with | Read {exp} | Write {exp} -> Location (AccessExpression.to_access_path exp) | ContainerRead {exp} | ContainerWrite {exp} -> Container (AccessExpression.to_access_path exp) | InterfaceCall {pname} -> Call pname end module M = Caml.Map.Make (Key) type t = reported_access list M.t let empty = M.empty let add (rep : reported_access) map = let access = rep.snapshot.elem.access in let k = Key.of_access access in M.update k (function None -> Some [rep] | Some reps -> Some (rep :: reps)) map let filter_container_accesses f map = M.filter (fun k _ -> match k with Container p -> f p | _ -> true) map let fold f map a = let f _ v acc = f v acc in M.fold f map a end let should_report_guardedby_violation classname ({snapshot; tenv; procname} : reported_access) = let is_uitthread param = match String.lowercase param with | "ui thread" | "ui-thread" | "ui_thread" | "uithread" -> true | _ -> false in let field_is_annotated_guardedby field_name (f, _, a) = Fieldname.equal f field_name && List.exists a ~f:(fun (annot : Annot.t) -> Annotations.annot_ends_with annot Annotations.guarded_by && match annot.parameters with | [param] -> not (Annot.has_matching_str_value ~pred:is_uitthread param.value) | _ -> false ) in (not snapshot.elem.lock) && RacerDDomain.AccessSnapshot.is_write snapshot && Procname.is_java procname && restrict check to access paths of length one match RacerDDomain.Access.get_access_exp snapshot.elem.access |> AccessExpression.to_accesses |> fun (base, accesses) -> (base, List.filter accesses ~f:HilExp.Access.is_field_or_array_access) with | AccessExpression.Base (_, base_type), [HilExp.Access.FieldAccess field_name] -> ( match base_type.desc with | Tstruct base_name | Tptr ({desc= Tstruct base_name}, _) -> is the base class a subclass of the one containing the GuardedBy annotation ? PatternMatch.is_subtype tenv base_name classname && Tenv.lookup tenv base_name |> Option.exists ~f:(fun ({fields; statics} : Struct.t) -> let f fld = field_is_annotated_guardedby field_name fld in List.exists fields ~f || List.exists statics ~f ) | _ -> false ) | _ -> false type report_kind = | GuardedByViolation | WriteWriteRace of RacerDDomain.AccessSnapshot.t option * one of conflicting access , if there are any * one of several conflicting accesses | UnannotatedInterface let make_trace ~report_kind original_exp = let open RacerDDomain in let loc_trace_of_path path = AccessSnapshot.make_loc_trace path in let original_trace = loc_trace_of_path original_exp in let get_end_loc trace = Option.map (List.last trace) ~f:(function {Errlog.lt_loc} -> lt_loc) in let original_end = get_end_loc original_trace in let make_with_conflicts conflict_sink original_trace ~label1 ~label2 = create a trace for one of the conflicts and append it to the trace for the original sink let conflict_trace = loc_trace_of_path conflict_sink in let conflict_end = get_end_loc conflict_trace in ( Errlog.concat_traces [(label1, original_trace); (label2, conflict_trace)] , original_end , conflict_end ) in match report_kind with | ReadWriteRace conflict -> make_with_conflicts conflict original_trace ~label1:"<Read trace>" ~label2:"<Write trace>" | WriteWriteRace (Some conflict) -> make_with_conflicts conflict original_trace ~label1:"<Write on unknown thread>" ~label2:"<Write on background thread>" | GuardedByViolation | WriteWriteRace None | UnannotatedInterface -> (original_trace, original_end, None) * Explain why we are reporting this access , in Java let get_reporting_explanation_java report_kind tenv pname thread = best explanation is always that the current class or method is annotated thread - safe . try for that first . that first. *) let annotation_explanation_opt = if RacerDModels.is_thread_safe_method pname tenv then Some (F.asprintf "@\n Reporting because current method is annotated %a or overrides an annotated method." MF.pp_monospaced "@ThreadSafe" ) else match RacerDModels.get_litho_explanation tenv pname with | Some _ as expl_opt -> expl_opt | None -> ( match RacerDModels.get_current_class_and_threadsafe_superclasses tenv pname with | Some (current_class, (thread_safe_class :: _ as thread_safe_annotated_classes)) -> Some ( if List.mem ~equal:Typ.Name.equal thread_safe_annotated_classes current_class then F.asprintf "@\n Reporting because the current class is annotated %a" MF.pp_monospaced "@ThreadSafe" else F.asprintf "@\n Reporting because a superclass %a is annotated %a" (MF.wrap_monospaced Typ.Name.pp) thread_safe_class MF.pp_monospaced "@ThreadSafe" ) | _ -> None ) in let issue_type, explanation = match (report_kind, annotation_explanation_opt) with | GuardedByViolation, _ -> ( IssueType.guardedby_violation , F.asprintf "@\n Reporting because field is annotated %a" MF.pp_monospaced "@GuardedBy" ) | UnannotatedInterface, Some threadsafe_explanation -> (IssueType.interface_not_thread_safe, F.asprintf "%s." threadsafe_explanation) | UnannotatedInterface, None -> Logging.die InternalError "Reporting non-threadsafe interface call, but can't find a @ThreadSafe annotation" | _, Some threadsafe_explanation when RacerDDomain.ThreadsDomain.is_any thread -> ( IssueType.thread_safety_violation , F.asprintf "%s, so we assume that this method can run in parallel with other non-private methods \ in the class (including itself)." threadsafe_explanation ) | _, Some threadsafe_explanation -> ( IssueType.thread_safety_violation , F.asprintf "%s. Although this access is not known to run on a background thread, it may happen in \ parallel with another access that does." threadsafe_explanation ) | _, None -> failed to explain based on @ThreadSafe annotation ; have to justify using background thread if RacerDDomain.ThreadsDomain.is_any thread then ( IssueType.thread_safety_violation , F.asprintf "@\n Reporting because this access may occur on a background thread." ) else ( IssueType.thread_safety_violation , F.asprintf "@\n\ \ Reporting because another access to the same memory occurs on a background thread, \ although this access may not." ) in (issue_type, explanation) * Explain why we are reporting this access , in C++ let get_reporting_explanation_cpp = (IssueType.lock_consistency_violation, "") (** Explain why we are reporting this access *) let get_reporting_explanation report_kind tenv pname thread = if Procname.is_java pname || Procname.is_csharp pname then get_reporting_explanation_java report_kind tenv pname thread else get_reporting_explanation_cpp let log_issue current_pname ~issue_log ~loc ~ltr ~access issue_type error_message = Reporting.log_issue_external current_pname ~issue_log ~loc ~ltr ~access issue_type error_message let report_thread_safety_violation ~make_description ~report_kind ({threads; snapshot; tenv; procname= pname} : reported_access) issue_log = let open RacerDDomain in let final_pname = List.last snapshot.trace |> Option.value_map ~default:pname ~f:CallSite.pname in let final_sink_site = CallSite.make final_pname snapshot.loc in let initial_sink_site = CallSite.make pname (AccessSnapshot.get_loc snapshot) in let loc = CallSite.loc initial_sink_site in let ltr, original_end, conflict_end = make_trace ~report_kind snapshot in (* what the potential bug is *) let description = make_description pname final_sink_site initial_sink_site snapshot in (* why we are reporting it *) let issue_type, explanation = get_reporting_explanation report_kind tenv pname threads in let error_message = F.sprintf "%s%s" description explanation in let end_locs = Option.to_list original_end @ Option.to_list conflict_end in let access = IssueAuxData.encode end_locs in log_issue pname ~issue_log ~loc ~ltr ~access RacerD issue_type error_message let report_unannotated_interface_violation reported_pname reported_access issue_log = match Procname.base_of reported_pname with | Procname.Java java_pname -> let class_name = Procname.Java.get_class_name java_pname in let make_description _ _ _ _ = F.asprintf "Unprotected call to method %a of un-annotated interface %a. Consider annotating the \ interface with %a or adding a lock." describe_pname reported_pname MF.pp_monospaced class_name MF.pp_monospaced "@ThreadSafe" in report_thread_safety_violation ~make_description ~report_kind:UnannotatedInterface reported_access issue_log | _ -> skip reporting on C++ issue_log let report_thread_safety_violation ~acc ~make_description ~report_kind reported_access = ReportedSet.deduplicate ~f:(report_thread_safety_violation ~make_description ~report_kind) reported_access acc let report_unannotated_interface_violation ~acc reported_pname reported_access = ReportedSet.deduplicate reported_access acc ~f:(report_unannotated_interface_violation reported_pname) let make_read_write_race_description ~read_is_sync (conflict : reported_access) pname final_sink_site initial_sink_site final_sink = let pp_conflict fmt {procname} = F.pp_print_string fmt (Procname.to_simplified_string ~withclass:true procname) in let conflicts_description = Format.asprintf "Potentially races with%s write in method %a" (if read_is_sync then " unsynchronized" else "") (MF.wrap_monospaced pp_conflict) conflict in Format.asprintf "Read/Write race. Non-private method %a%s reads%s from %a. %s." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") (if read_is_sync then " with synchronization" else " without synchronization") pp_access final_sink conflicts_description let make_guardedby_violation_description pname final_sink_site initial_sink_site final_sink = Format.asprintf "GuardedBy violation. Non-private method %a%s accesses %a outside of synchronization." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") pp_access final_sink let make_unprotected_write_description pname final_sink_site initial_sink_site final_sink = Format.asprintf "Unprotected write. Non-private method %a%s %s %a outside of synchronization." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") ( if RacerDDomain.AccessSnapshot.is_container_write final_sink then "mutates" else "writes to field" ) pp_access final_sink let report_on_write_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let conflict = if ThreadsDomain.is_any reported_access.threads then (* unprotected write in method that may run in parallel with itself. warn *) None else (* unprotected write, but not on a method that may run in parallel with itself (i.e., not a self race). find accesses on a background thread this access might conflict with and report them *) List.find_map accesses ~f:(fun {snapshot= other_snapshot; threads= other_threads} -> if AccessSnapshot.is_write other_snapshot && ThreadsDomain.is_any other_threads then Some other_snapshot else None ) in if AccessSnapshot.is_unprotected reported_access.snapshot && (Option.is_some conflict || ThreadsDomain.is_any reported_access.threads) then report_thread_safety_violation ~acc ~make_description:make_unprotected_write_description ~report_kind:(WriteWriteRace conflict) reported_access else acc (** unprotected read. report all writes as conflicts for java/csharp. *) let report_on_unprotected_read_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let is_conflict {snapshot; threads= other_threads} = AccessSnapshot.is_write snapshot && (ThreadsDomain.is_any reported_access.threads || ThreadsDomain.is_any other_threads) in List.find ~f:is_conflict accesses |> Option.value_map ~default:acc ~f:(fun conflict -> let make_description = make_read_write_race_description ~read_is_sync:false conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) (** protected read. report unprotected writes and opposite protected writes as conflicts *) let report_on_protected_read_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let can_conflict (snapshot1 : AccessSnapshot.t) (snapshot2 : AccessSnapshot.t) = if snapshot1.elem.lock && snapshot2.elem.lock then false else ThreadsDomain.can_conflict snapshot1.elem.thread snapshot2.elem.thread in let is_conflict {snapshot= other_snapshot; threads= other_threads} = if AccessSnapshot.is_unprotected other_snapshot then AccessSnapshot.is_write other_snapshot && ThreadsDomain.is_any other_threads else AccessSnapshot.is_write other_snapshot && can_conflict reported_access.snapshot other_snapshot in List.find accesses ~f:is_conflict |> Option.value_map ~default:acc ~f:(fun conflict -> (* protected read with conflicting unprotected write(s). warn. *) let make_description = make_read_write_race_description ~read_is_sync:true conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) * main reporting hook for Java & C # let report_unsafe_access_java_csharp accesses acc ({snapshot; threads; tenv; procname= pname} as reported_access) = let open RacerDDomain in let open RacerDModels in match snapshot.elem.access with | InterfaceCall {pname= reported_pname} when AccessSnapshot.is_unprotected snapshot && ThreadsDomain.is_any threads && is_marked_thread_safe pname tenv -> un - annotated interface call + no lock in method marked thread - safe . warn report_unannotated_interface_violation ~acc reported_pname reported_access | InterfaceCall _ -> acc | Write _ | ContainerWrite _ -> report_on_write_java_csharp accesses acc reported_access | (Read _ | ContainerRead _) when AccessSnapshot.is_unprotected snapshot -> report_on_unprotected_read_java_csharp accesses acc reported_access | Read _ | ContainerRead _ -> report_on_protected_read_java_csharp accesses acc reported_access (** main reporting hook for C langs *) let report_unsafe_access_objc_cpp accesses acc ({snapshot} as reported_access) = let open RacerDDomain in match snapshot.elem.access with | InterfaceCall _ | Write _ | ContainerWrite _ -> Do not report unprotected writes for ObjC_Cpp acc | (Read _ | ContainerRead _) when AccessSnapshot.is_unprotected snapshot -> (* unprotected read. for c++ filter out unprotected writes *) let is_conflict {snapshot} = AccessSnapshot.is_write snapshot && not (AccessSnapshot.is_unprotected snapshot) in List.find ~f:is_conflict accesses |> Option.value_map ~default:acc ~f:(fun conflict -> let make_description = make_read_write_race_description ~read_is_sync:false conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) | Read _ | ContainerRead _ -> Do not report protected reads for ObjC_Cpp acc (** report hook dispatching to language specific functions *) let report_unsafe_access accesses acc ({procname} as reported_access) = match (Procname.base_of procname : Procname.t) with | Java _ | CSharp _ -> report_unsafe_access_java_csharp accesses acc reported_access | ObjC_Cpp _ -> report_unsafe_access_objc_cpp accesses acc reported_access | _ -> acc * Report accesses that may race with each other . Principles for race reporting . Two accesses are excluded if they are both protected by the same lock or are known to be on the same thread . Otherwise they are in conflict . We want to report conflicting accesses one of which is a write . To cut down on duplication noise we do n't always report at both sites ( line numbers ) involved in a race . \-- If a protected access races with an unprotected one , we do n't report the protected but we do report the unprotected one ( and we point to the protected from the unprotected one ) . This way the report is at the line number in a race - pair where the programmer should take action . \-- Similarly , if a threaded and unthreaded ( not known to be threaded ) access race , we report at the unthreaded site . Also , we avoid reporting multiple races at the same line ( which can happen a lot in an interprocedural scenario ) or multiple accesses to the same field in a single method , expecting that the programmer already gets signal from one report . To report all the races with separate warnings leads to a lot of noise . But note , we never suppress all the potential issues in a class : if we do n't report any races , it means we did n't find any . The above is tempered at the moment by abstractions of " same lock " and " same thread " : we are currently not distinguishing different locks , and are treating " known to be confined to a thread " as if " known to be confined to UI thread " . Principles for race reporting. Two accesses are excluded if they are both protected by the same lock or are known to be on the same thread. Otherwise they are in conflict. We want to report conflicting accesses one of which is a write. To cut down on duplication noise we don't always report at both sites (line numbers) involved in a race. \-- If a protected access races with an unprotected one, we don't report the protected but we do report the unprotected one (and we point to the protected from the unprotected one). This way the report is at the line number in a race-pair where the programmer should take action. \-- Similarly, if a threaded and unthreaded (not known to be threaded) access race, we report at the unthreaded site. Also, we avoid reporting multiple races at the same line (which can happen a lot in an interprocedural scenario) or multiple accesses to the same field in a single method, expecting that the programmer already gets signal from one report. To report all the races with separate warnings leads to a lot of noise. But note, we never suppress all the potential issues in a class: if we don't report any races, it means we didn't find any. The above is tempered at the moment by abstractions of "same lock" and "same thread": we are currently not distinguishing different locks, and are treating "known to be confined to a thread" as if "known to be confined to UI thread". *) let report_unsafe_accesses ~issue_log classname aggregated_access_map = let open RacerDDomain in let report_accesses_on_location reportable_accesses init = (* Don't report on location if all accesses are on non-concurrent contexts *) if List.for_all reportable_accesses ~f:(fun ({threads} : reported_access) -> ThreadsDomain.is_any threads |> not ) then init else List.fold reportable_accesses ~init ~f:(report_unsafe_access reportable_accesses) in let report_guardedby_violations_on_location grouped_accesses init = if Config.racerd_guardedby then List.fold grouped_accesses ~init ~f:(fun acc r -> if should_report_guardedby_violation classname r then report_thread_safety_violation ~acc ~report_kind:GuardedByViolation ~make_description:make_guardedby_violation_description r else acc ) else init in let report grouped_accesses acc = (* reset the reported reads and writes for each memory location *) ReportedSet.reset acc |> report_guardedby_violations_on_location grouped_accesses |> report_accesses_on_location grouped_accesses in ReportedSet.empty_of_issue_log issue_log |> ReportMap.fold report aggregated_access_map |> ReportedSet.to_issue_log let should_report_on_proc file_exe_env proc_name = Attributes.load proc_name |> Option.exists ~f:(fun attrs -> let tenv = Exe_env.get_proc_tenv file_exe_env proc_name in let is_not_private = not ProcAttributes.(equal_access (get_access attrs) Private) in match (Procname.base_of proc_name : Procname.t) with | CSharp _ -> is_not_private | Java java_pname -> return true if procedure is at an abstraction boundary or reporting has been explicitly requested via @ThreadSafe in java requested via @ThreadSafe in java *) RacerDModels.is_thread_safe_method proc_name tenv || is_not_private && (not (Procname.Java.is_class_initializer java_pname)) && (not (Procname.Java.is_autogen_method java_pname)) && not Annotations.(attrs_return_annot_ends_with attrs visibleForTesting) | ObjC_Cpp _ when Procname.is_cpp_lambda proc_name -> do not report on lambdas ; they are essentially private though do not appear as such false | ObjC_Cpp {kind= CPPMethod _ | CPPConstructor _ | CPPDestructor _} -> is_not_private | ObjC_Cpp {kind= ObjCClassMethod | ObjCInstanceMethod; class_name} -> Tenv.lookup tenv class_name |> Option.exists ~f:(fun {Struct.exported_objc_methods} -> List.mem ~equal:Procname.equal exported_objc_methods proc_name ) | _ -> false ) create a map from [ abstraction of a memory loc ] - > accesses that may touch that memory . the abstraction of a location is an access path like x.f.g whose concretization is the set of memory cells that x.f.g may point to during execution may touch that memory loc. the abstraction of a location is an access path like x.f.g whose concretization is the set of memory cells that x.f.g may point to during execution *) let make_results_table exe_env summaries = let open RacerDDomain in let aggregate_post tenv procname acc {threads; accesses} = AccessDomain.fold (fun snapshot acc -> ReportMap.add {threads; snapshot; tenv; procname} acc) accesses acc in List.fold summaries ~init:ReportMap.empty ~f:(fun acc (procname, summary) -> if should_report_on_proc exe_env procname then let tenv = Exe_env.get_proc_tenv exe_env procname in aggregate_post tenv procname acc summary else acc ) let class_has_concurrent_method class_summaries = let open RacerDDomain in let method_has_concurrent_context (_, summary) = match (summary.threads : ThreadsDomain.t) with NoThread -> false | _ -> true in List.exists class_summaries ~f:method_has_concurrent_context let should_report_on_class (classname : Typ.Name.t) class_summaries = (not (RacerDModels.class_is_ignored_by_racerd classname)) && match classname with | JavaClass _ -> do n't do top - level reports on classes generated when compiling coroutines not (RacerDModels.is_kotlin_coroutine_generated classname) | CSharpClass _ -> true | CppClass _ | ObjcClass _ | ObjcProtocol _ | CStruct _ -> class_has_concurrent_method class_summaries | CUnion _ | ErlangType _ | HackClass _ -> false (** aggregate all of the procedures in the file env by their declaring class. this lets us analyze each class individually *) let aggregate_by_class {InterproceduralAnalysis.procedures; analyze_file_dependency} = List.fold procedures ~init:Typ.Name.Map.empty ~f:(fun acc procname -> Procname.get_class_type_name procname |> Option.bind ~f:(fun classname -> analyze_file_dependency procname |> Option.map ~f:(fun summary -> Typ.Name.Map.update classname (fun summaries_opt -> Some ((procname, summary) :: Option.value ~default:[] summaries_opt) ) acc ) ) |> Option.value ~default:acc ) |> Typ.Name.Map.filter should_report_on_class let get_synchronized_container_fields_of analyze tenv classname = let open RacerDDomain in let last_field_of_access_expression acc_exp = let _, path = HilExp.AccessExpression.to_access_path acc_exp in List.last path |> Option.bind ~f:(function AccessPath.FieldAccess fieldname -> Some fieldname | _ -> None) in let add_synchronized_container_field acc_exp attr acc = match attr with | Attribute.Synchronized -> last_field_of_access_expression acc_exp |> Option.fold ~init:acc ~f:(fun acc fieldname -> Fieldname.Set.add fieldname acc) | _ -> acc in Tenv.lookup tenv classname |> Option.value_map ~default:[] ~f:(fun (tstruct : Struct.t) -> tstruct.methods) |> List.rev_filter ~f:(function | Procname.Java j -> Procname.Java.(is_class_initializer j || is_constructor j) | _ -> false ) |> List.rev_filter_map ~f:analyze |> List.rev_map ~f:(fun (summary : summary) -> summary.attributes) |> List.fold ~init:Fieldname.Set.empty ~f:(fun acc attributes -> AttributeMapDomain.fold add_synchronized_container_field attributes acc ) let get_synchronized_container_fields_of, clear_sync_container_cache = let cache = Typ.Name.Hash.create 5 in ( (fun analyze tenv classname -> match Typ.Name.Hash.find_opt cache classname with | Some fieldset -> fieldset | None -> let fieldset = get_synchronized_container_fields_of analyze tenv classname in Typ.Name.Hash.add cache classname fieldset ; fieldset ) , fun () -> Typ.Name.Hash.clear cache ) let should_keep_container_access analyze tenv ((_base, path) : PathModuloThis.t) = let should_keep_access_ending_at_field fieldname = let classname = Fieldname.get_class_name fieldname in let sync_container_fields = get_synchronized_container_fields_of analyze tenv classname in not (Fieldname.Set.mem fieldname sync_container_fields) in let rec should_keep_container_access_inner rev_path = match rev_path with | [] -> true | AccessPath.ArrayAccess _ :: rest -> should_keep_container_access_inner rest | AccessPath.FieldAccess fieldname :: _ -> should_keep_access_ending_at_field fieldname in List.rev path |> should_keep_container_access_inner (** Gathers results by analyzing all the methods in a file, then post-processes the results to check an (approximation of) thread safety *) let analyze ({InterproceduralAnalysis.file_exe_env; analyze_file_dependency} as file_t) = let synchronized_container_filter = function | Typ.JavaClass _ -> let tenv = Exe_env.load_java_global_tenv file_exe_env in ReportMap.filter_container_accesses (should_keep_container_access analyze_file_dependency tenv) | _ -> Fn.id in let class_map = aggregate_by_class file_t in let result = Typ.Name.Map.fold (fun classname methods issue_log -> make_results_table file_exe_env methods |> synchronized_container_filter classname |> report_unsafe_accesses ~issue_log classname ) class_map IssueLog.empty in clear_sync_container_cache () ; result
null
https://raw.githubusercontent.com/facebook/infer/7f5c21d32d57578fe05aa1c1eef82ad1a101dc4f/infer/src/concurrency/RacerDFileAnalysis.ml
ocaml
* Type for deduplicating and storing reports. * Reset recorded writes and reads, while maintaining the same [IssueLog.t]. * Create a set of reports containing the given [IssueLog.t] but otherwise having no records of previous reports. * Recover deduplicated [IssueLog.t] from [t]. * Deduplicate [f]. * Map containing reported accesses, which groups them in lists, by abstract location. The equivalence relation used for grouping them is equality of access paths. This is slightly complicated because local variables contain the pname of the function declaring them. Here we want a purely name-based comparison, and in particular that [this == this] regardless the method declaring it. Hence the redefined comparison functions. * Explain why we are reporting this access what the potential bug is why we are reporting it unprotected write in method that may run in parallel with itself. warn unprotected write, but not on a method that may run in parallel with itself (i.e., not a self race). find accesses on a background thread this access might conflict with and report them * unprotected read. report all writes as conflicts for java/csharp. * protected read. report unprotected writes and opposite protected writes as conflicts protected read with conflicting unprotected write(s). warn. * main reporting hook for C langs unprotected read. for c++ filter out unprotected writes * report hook dispatching to language specific functions Don't report on location if all accesses are on non-concurrent contexts reset the reported reads and writes for each memory location * aggregate all of the procedures in the file env by their declaring class. this lets us analyze each class individually * Gathers results by analyzing all the methods in a file, then post-processes the results to check an (approximation of) thread safety
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module AccessExpression = HilExp.AccessExpression module F = Format module MF = MarkupFormatter let describe_exp = MF.wrap_monospaced RacerDDomain.pp_exp let describe_pname = MF.wrap_monospaced (Procname.pp_simplified_string ~withclass:true) let pp_access fmt (t : RacerDDomain.AccessSnapshot.t) = match t.elem.access with | Read {exp} | Write {exp} -> describe_exp fmt exp | ContainerRead {exp; pname} | ContainerWrite {exp; pname} -> F.fprintf fmt "container %a via call to %a" describe_exp exp describe_pname pname | InterfaceCall _ as access -> RacerDDomain.Access.pp fmt access type reported_access = { threads: RacerDDomain.ThreadsDomain.t ; snapshot: RacerDDomain.AccessSnapshot.t ; tenv: Tenv.t ; procname: Procname.t } module ReportedSet : sig type t val reset : t -> t val empty_of_issue_log : IssueLog.t -> t val to_issue_log : t -> IssueLog.t val deduplicate : f:(reported_access -> IssueLog.t -> IssueLog.t) -> reported_access -> t -> t end = struct type reported_set = { sites: CallSite.Set.t ; writes: Procname.Set.t ; reads: Procname.Set.t ; unannotated_calls: Procname.Set.t } let empty_reported_set = { sites= CallSite.Set.empty ; reads= Procname.Set.empty ; writes= Procname.Set.empty ; unannotated_calls= Procname.Set.empty } type t = reported_set * IssueLog.t let empty_of_issue_log issue_log = (empty_reported_set, issue_log) let to_issue_log = snd let reset (reported_set, issue_log) = ({reported_set with writes= Procname.Set.empty; reads= Procname.Set.empty}, issue_log) let is_duplicate {snapshot; procname} (reported_set, _) = let call_site = CallSite.make procname (RacerDDomain.AccessSnapshot.get_loc snapshot) in CallSite.Set.mem call_site reported_set.sites || match snapshot.elem.access with | Write _ | ContainerWrite _ -> Procname.Set.mem procname reported_set.writes | Read _ | ContainerRead _ -> Procname.Set.mem procname reported_set.reads | InterfaceCall _ -> Procname.Set.mem procname reported_set.unannotated_calls let update {snapshot; procname} (reported_set, issue_log) = let call_site = CallSite.make procname (RacerDDomain.AccessSnapshot.get_loc snapshot) in let sites = CallSite.Set.add call_site reported_set.sites in let reported_set = {reported_set with sites} in let reported_set = match snapshot.elem.access with | Write _ | ContainerWrite _ -> {reported_set with writes= Procname.Set.add procname reported_set.writes} | Read _ | ContainerRead _ -> {reported_set with reads= Procname.Set.add procname reported_set.reads} | InterfaceCall _ -> { reported_set with unannotated_calls= Procname.Set.add procname reported_set.unannotated_calls } in (reported_set, issue_log) let deduplicate ~f reported_access ((reported_set, issue_log) as acc) = if Config.deduplicate && is_duplicate reported_access acc then acc else update reported_access (reported_set, f reported_access issue_log) end module PathModuloThis : Caml.Map.OrderedType with type t = AccessPath.t = struct type t = AccessPath.t type var_ = Var.t let compare_var_ = Var.compare_modulo_this let compare = [%compare: (var_ * Typ.t) * AccessPath.access list] end module ReportMap : sig type t val empty : t val add : reported_access -> t -> t val fold : (reported_access list -> 'a -> 'a) -> t -> 'a -> 'a val filter_container_accesses : (PathModuloThis.t -> bool) -> t -> t end = struct module Key = struct type t = Location of PathModuloThis.t | Container of PathModuloThis.t | Call of Procname.t [@@deriving compare] let of_access (access : RacerDDomain.Access.t) = match access with | Read {exp} | Write {exp} -> Location (AccessExpression.to_access_path exp) | ContainerRead {exp} | ContainerWrite {exp} -> Container (AccessExpression.to_access_path exp) | InterfaceCall {pname} -> Call pname end module M = Caml.Map.Make (Key) type t = reported_access list M.t let empty = M.empty let add (rep : reported_access) map = let access = rep.snapshot.elem.access in let k = Key.of_access access in M.update k (function None -> Some [rep] | Some reps -> Some (rep :: reps)) map let filter_container_accesses f map = M.filter (fun k _ -> match k with Container p -> f p | _ -> true) map let fold f map a = let f _ v acc = f v acc in M.fold f map a end let should_report_guardedby_violation classname ({snapshot; tenv; procname} : reported_access) = let is_uitthread param = match String.lowercase param with | "ui thread" | "ui-thread" | "ui_thread" | "uithread" -> true | _ -> false in let field_is_annotated_guardedby field_name (f, _, a) = Fieldname.equal f field_name && List.exists a ~f:(fun (annot : Annot.t) -> Annotations.annot_ends_with annot Annotations.guarded_by && match annot.parameters with | [param] -> not (Annot.has_matching_str_value ~pred:is_uitthread param.value) | _ -> false ) in (not snapshot.elem.lock) && RacerDDomain.AccessSnapshot.is_write snapshot && Procname.is_java procname && restrict check to access paths of length one match RacerDDomain.Access.get_access_exp snapshot.elem.access |> AccessExpression.to_accesses |> fun (base, accesses) -> (base, List.filter accesses ~f:HilExp.Access.is_field_or_array_access) with | AccessExpression.Base (_, base_type), [HilExp.Access.FieldAccess field_name] -> ( match base_type.desc with | Tstruct base_name | Tptr ({desc= Tstruct base_name}, _) -> is the base class a subclass of the one containing the GuardedBy annotation ? PatternMatch.is_subtype tenv base_name classname && Tenv.lookup tenv base_name |> Option.exists ~f:(fun ({fields; statics} : Struct.t) -> let f fld = field_is_annotated_guardedby field_name fld in List.exists fields ~f || List.exists statics ~f ) | _ -> false ) | _ -> false type report_kind = | GuardedByViolation | WriteWriteRace of RacerDDomain.AccessSnapshot.t option * one of conflicting access , if there are any * one of several conflicting accesses | UnannotatedInterface let make_trace ~report_kind original_exp = let open RacerDDomain in let loc_trace_of_path path = AccessSnapshot.make_loc_trace path in let original_trace = loc_trace_of_path original_exp in let get_end_loc trace = Option.map (List.last trace) ~f:(function {Errlog.lt_loc} -> lt_loc) in let original_end = get_end_loc original_trace in let make_with_conflicts conflict_sink original_trace ~label1 ~label2 = create a trace for one of the conflicts and append it to the trace for the original sink let conflict_trace = loc_trace_of_path conflict_sink in let conflict_end = get_end_loc conflict_trace in ( Errlog.concat_traces [(label1, original_trace); (label2, conflict_trace)] , original_end , conflict_end ) in match report_kind with | ReadWriteRace conflict -> make_with_conflicts conflict original_trace ~label1:"<Read trace>" ~label2:"<Write trace>" | WriteWriteRace (Some conflict) -> make_with_conflicts conflict original_trace ~label1:"<Write on unknown thread>" ~label2:"<Write on background thread>" | GuardedByViolation | WriteWriteRace None | UnannotatedInterface -> (original_trace, original_end, None) * Explain why we are reporting this access , in Java let get_reporting_explanation_java report_kind tenv pname thread = best explanation is always that the current class or method is annotated thread - safe . try for that first . that first. *) let annotation_explanation_opt = if RacerDModels.is_thread_safe_method pname tenv then Some (F.asprintf "@\n Reporting because current method is annotated %a or overrides an annotated method." MF.pp_monospaced "@ThreadSafe" ) else match RacerDModels.get_litho_explanation tenv pname with | Some _ as expl_opt -> expl_opt | None -> ( match RacerDModels.get_current_class_and_threadsafe_superclasses tenv pname with | Some (current_class, (thread_safe_class :: _ as thread_safe_annotated_classes)) -> Some ( if List.mem ~equal:Typ.Name.equal thread_safe_annotated_classes current_class then F.asprintf "@\n Reporting because the current class is annotated %a" MF.pp_monospaced "@ThreadSafe" else F.asprintf "@\n Reporting because a superclass %a is annotated %a" (MF.wrap_monospaced Typ.Name.pp) thread_safe_class MF.pp_monospaced "@ThreadSafe" ) | _ -> None ) in let issue_type, explanation = match (report_kind, annotation_explanation_opt) with | GuardedByViolation, _ -> ( IssueType.guardedby_violation , F.asprintf "@\n Reporting because field is annotated %a" MF.pp_monospaced "@GuardedBy" ) | UnannotatedInterface, Some threadsafe_explanation -> (IssueType.interface_not_thread_safe, F.asprintf "%s." threadsafe_explanation) | UnannotatedInterface, None -> Logging.die InternalError "Reporting non-threadsafe interface call, but can't find a @ThreadSafe annotation" | _, Some threadsafe_explanation when RacerDDomain.ThreadsDomain.is_any thread -> ( IssueType.thread_safety_violation , F.asprintf "%s, so we assume that this method can run in parallel with other non-private methods \ in the class (including itself)." threadsafe_explanation ) | _, Some threadsafe_explanation -> ( IssueType.thread_safety_violation , F.asprintf "%s. Although this access is not known to run on a background thread, it may happen in \ parallel with another access that does." threadsafe_explanation ) | _, None -> failed to explain based on @ThreadSafe annotation ; have to justify using background thread if RacerDDomain.ThreadsDomain.is_any thread then ( IssueType.thread_safety_violation , F.asprintf "@\n Reporting because this access may occur on a background thread." ) else ( IssueType.thread_safety_violation , F.asprintf "@\n\ \ Reporting because another access to the same memory occurs on a background thread, \ although this access may not." ) in (issue_type, explanation) * Explain why we are reporting this access , in C++ let get_reporting_explanation_cpp = (IssueType.lock_consistency_violation, "") let get_reporting_explanation report_kind tenv pname thread = if Procname.is_java pname || Procname.is_csharp pname then get_reporting_explanation_java report_kind tenv pname thread else get_reporting_explanation_cpp let log_issue current_pname ~issue_log ~loc ~ltr ~access issue_type error_message = Reporting.log_issue_external current_pname ~issue_log ~loc ~ltr ~access issue_type error_message let report_thread_safety_violation ~make_description ~report_kind ({threads; snapshot; tenv; procname= pname} : reported_access) issue_log = let open RacerDDomain in let final_pname = List.last snapshot.trace |> Option.value_map ~default:pname ~f:CallSite.pname in let final_sink_site = CallSite.make final_pname snapshot.loc in let initial_sink_site = CallSite.make pname (AccessSnapshot.get_loc snapshot) in let loc = CallSite.loc initial_sink_site in let ltr, original_end, conflict_end = make_trace ~report_kind snapshot in let description = make_description pname final_sink_site initial_sink_site snapshot in let issue_type, explanation = get_reporting_explanation report_kind tenv pname threads in let error_message = F.sprintf "%s%s" description explanation in let end_locs = Option.to_list original_end @ Option.to_list conflict_end in let access = IssueAuxData.encode end_locs in log_issue pname ~issue_log ~loc ~ltr ~access RacerD issue_type error_message let report_unannotated_interface_violation reported_pname reported_access issue_log = match Procname.base_of reported_pname with | Procname.Java java_pname -> let class_name = Procname.Java.get_class_name java_pname in let make_description _ _ _ _ = F.asprintf "Unprotected call to method %a of un-annotated interface %a. Consider annotating the \ interface with %a or adding a lock." describe_pname reported_pname MF.pp_monospaced class_name MF.pp_monospaced "@ThreadSafe" in report_thread_safety_violation ~make_description ~report_kind:UnannotatedInterface reported_access issue_log | _ -> skip reporting on C++ issue_log let report_thread_safety_violation ~acc ~make_description ~report_kind reported_access = ReportedSet.deduplicate ~f:(report_thread_safety_violation ~make_description ~report_kind) reported_access acc let report_unannotated_interface_violation ~acc reported_pname reported_access = ReportedSet.deduplicate reported_access acc ~f:(report_unannotated_interface_violation reported_pname) let make_read_write_race_description ~read_is_sync (conflict : reported_access) pname final_sink_site initial_sink_site final_sink = let pp_conflict fmt {procname} = F.pp_print_string fmt (Procname.to_simplified_string ~withclass:true procname) in let conflicts_description = Format.asprintf "Potentially races with%s write in method %a" (if read_is_sync then " unsynchronized" else "") (MF.wrap_monospaced pp_conflict) conflict in Format.asprintf "Read/Write race. Non-private method %a%s reads%s from %a. %s." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") (if read_is_sync then " with synchronization" else " without synchronization") pp_access final_sink conflicts_description let make_guardedby_violation_description pname final_sink_site initial_sink_site final_sink = Format.asprintf "GuardedBy violation. Non-private method %a%s accesses %a outside of synchronization." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") pp_access final_sink let make_unprotected_write_description pname final_sink_site initial_sink_site final_sink = Format.asprintf "Unprotected write. Non-private method %a%s %s %a outside of synchronization." describe_pname pname (if CallSite.equal final_sink_site initial_sink_site then "" else " indirectly") ( if RacerDDomain.AccessSnapshot.is_container_write final_sink then "mutates" else "writes to field" ) pp_access final_sink let report_on_write_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let conflict = if ThreadsDomain.is_any reported_access.threads then None else List.find_map accesses ~f:(fun {snapshot= other_snapshot; threads= other_threads} -> if AccessSnapshot.is_write other_snapshot && ThreadsDomain.is_any other_threads then Some other_snapshot else None ) in if AccessSnapshot.is_unprotected reported_access.snapshot && (Option.is_some conflict || ThreadsDomain.is_any reported_access.threads) then report_thread_safety_violation ~acc ~make_description:make_unprotected_write_description ~report_kind:(WriteWriteRace conflict) reported_access else acc let report_on_unprotected_read_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let is_conflict {snapshot; threads= other_threads} = AccessSnapshot.is_write snapshot && (ThreadsDomain.is_any reported_access.threads || ThreadsDomain.is_any other_threads) in List.find ~f:is_conflict accesses |> Option.value_map ~default:acc ~f:(fun conflict -> let make_description = make_read_write_race_description ~read_is_sync:false conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) let report_on_protected_read_java_csharp accesses acc (reported_access : reported_access) = let open RacerDDomain in let can_conflict (snapshot1 : AccessSnapshot.t) (snapshot2 : AccessSnapshot.t) = if snapshot1.elem.lock && snapshot2.elem.lock then false else ThreadsDomain.can_conflict snapshot1.elem.thread snapshot2.elem.thread in let is_conflict {snapshot= other_snapshot; threads= other_threads} = if AccessSnapshot.is_unprotected other_snapshot then AccessSnapshot.is_write other_snapshot && ThreadsDomain.is_any other_threads else AccessSnapshot.is_write other_snapshot && can_conflict reported_access.snapshot other_snapshot in List.find accesses ~f:is_conflict |> Option.value_map ~default:acc ~f:(fun conflict -> let make_description = make_read_write_race_description ~read_is_sync:true conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) * main reporting hook for Java & C # let report_unsafe_access_java_csharp accesses acc ({snapshot; threads; tenv; procname= pname} as reported_access) = let open RacerDDomain in let open RacerDModels in match snapshot.elem.access with | InterfaceCall {pname= reported_pname} when AccessSnapshot.is_unprotected snapshot && ThreadsDomain.is_any threads && is_marked_thread_safe pname tenv -> un - annotated interface call + no lock in method marked thread - safe . warn report_unannotated_interface_violation ~acc reported_pname reported_access | InterfaceCall _ -> acc | Write _ | ContainerWrite _ -> report_on_write_java_csharp accesses acc reported_access | (Read _ | ContainerRead _) when AccessSnapshot.is_unprotected snapshot -> report_on_unprotected_read_java_csharp accesses acc reported_access | Read _ | ContainerRead _ -> report_on_protected_read_java_csharp accesses acc reported_access let report_unsafe_access_objc_cpp accesses acc ({snapshot} as reported_access) = let open RacerDDomain in match snapshot.elem.access with | InterfaceCall _ | Write _ | ContainerWrite _ -> Do not report unprotected writes for ObjC_Cpp acc | (Read _ | ContainerRead _) when AccessSnapshot.is_unprotected snapshot -> let is_conflict {snapshot} = AccessSnapshot.is_write snapshot && not (AccessSnapshot.is_unprotected snapshot) in List.find ~f:is_conflict accesses |> Option.value_map ~default:acc ~f:(fun conflict -> let make_description = make_read_write_race_description ~read_is_sync:false conflict in let report_kind = ReadWriteRace conflict.snapshot in report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) | Read _ | ContainerRead _ -> Do not report protected reads for ObjC_Cpp acc let report_unsafe_access accesses acc ({procname} as reported_access) = match (Procname.base_of procname : Procname.t) with | Java _ | CSharp _ -> report_unsafe_access_java_csharp accesses acc reported_access | ObjC_Cpp _ -> report_unsafe_access_objc_cpp accesses acc reported_access | _ -> acc * Report accesses that may race with each other . Principles for race reporting . Two accesses are excluded if they are both protected by the same lock or are known to be on the same thread . Otherwise they are in conflict . We want to report conflicting accesses one of which is a write . To cut down on duplication noise we do n't always report at both sites ( line numbers ) involved in a race . \-- If a protected access races with an unprotected one , we do n't report the protected but we do report the unprotected one ( and we point to the protected from the unprotected one ) . This way the report is at the line number in a race - pair where the programmer should take action . \-- Similarly , if a threaded and unthreaded ( not known to be threaded ) access race , we report at the unthreaded site . Also , we avoid reporting multiple races at the same line ( which can happen a lot in an interprocedural scenario ) or multiple accesses to the same field in a single method , expecting that the programmer already gets signal from one report . To report all the races with separate warnings leads to a lot of noise . But note , we never suppress all the potential issues in a class : if we do n't report any races , it means we did n't find any . The above is tempered at the moment by abstractions of " same lock " and " same thread " : we are currently not distinguishing different locks , and are treating " known to be confined to a thread " as if " known to be confined to UI thread " . Principles for race reporting. Two accesses are excluded if they are both protected by the same lock or are known to be on the same thread. Otherwise they are in conflict. We want to report conflicting accesses one of which is a write. To cut down on duplication noise we don't always report at both sites (line numbers) involved in a race. \-- If a protected access races with an unprotected one, we don't report the protected but we do report the unprotected one (and we point to the protected from the unprotected one). This way the report is at the line number in a race-pair where the programmer should take action. \-- Similarly, if a threaded and unthreaded (not known to be threaded) access race, we report at the unthreaded site. Also, we avoid reporting multiple races at the same line (which can happen a lot in an interprocedural scenario) or multiple accesses to the same field in a single method, expecting that the programmer already gets signal from one report. To report all the races with separate warnings leads to a lot of noise. But note, we never suppress all the potential issues in a class: if we don't report any races, it means we didn't find any. The above is tempered at the moment by abstractions of "same lock" and "same thread": we are currently not distinguishing different locks, and are treating "known to be confined to a thread" as if "known to be confined to UI thread". *) let report_unsafe_accesses ~issue_log classname aggregated_access_map = let open RacerDDomain in let report_accesses_on_location reportable_accesses init = if List.for_all reportable_accesses ~f:(fun ({threads} : reported_access) -> ThreadsDomain.is_any threads |> not ) then init else List.fold reportable_accesses ~init ~f:(report_unsafe_access reportable_accesses) in let report_guardedby_violations_on_location grouped_accesses init = if Config.racerd_guardedby then List.fold grouped_accesses ~init ~f:(fun acc r -> if should_report_guardedby_violation classname r then report_thread_safety_violation ~acc ~report_kind:GuardedByViolation ~make_description:make_guardedby_violation_description r else acc ) else init in let report grouped_accesses acc = ReportedSet.reset acc |> report_guardedby_violations_on_location grouped_accesses |> report_accesses_on_location grouped_accesses in ReportedSet.empty_of_issue_log issue_log |> ReportMap.fold report aggregated_access_map |> ReportedSet.to_issue_log let should_report_on_proc file_exe_env proc_name = Attributes.load proc_name |> Option.exists ~f:(fun attrs -> let tenv = Exe_env.get_proc_tenv file_exe_env proc_name in let is_not_private = not ProcAttributes.(equal_access (get_access attrs) Private) in match (Procname.base_of proc_name : Procname.t) with | CSharp _ -> is_not_private | Java java_pname -> return true if procedure is at an abstraction boundary or reporting has been explicitly requested via @ThreadSafe in java requested via @ThreadSafe in java *) RacerDModels.is_thread_safe_method proc_name tenv || is_not_private && (not (Procname.Java.is_class_initializer java_pname)) && (not (Procname.Java.is_autogen_method java_pname)) && not Annotations.(attrs_return_annot_ends_with attrs visibleForTesting) | ObjC_Cpp _ when Procname.is_cpp_lambda proc_name -> do not report on lambdas ; they are essentially private though do not appear as such false | ObjC_Cpp {kind= CPPMethod _ | CPPConstructor _ | CPPDestructor _} -> is_not_private | ObjC_Cpp {kind= ObjCClassMethod | ObjCInstanceMethod; class_name} -> Tenv.lookup tenv class_name |> Option.exists ~f:(fun {Struct.exported_objc_methods} -> List.mem ~equal:Procname.equal exported_objc_methods proc_name ) | _ -> false ) create a map from [ abstraction of a memory loc ] - > accesses that may touch that memory . the abstraction of a location is an access path like x.f.g whose concretization is the set of memory cells that x.f.g may point to during execution may touch that memory loc. the abstraction of a location is an access path like x.f.g whose concretization is the set of memory cells that x.f.g may point to during execution *) let make_results_table exe_env summaries = let open RacerDDomain in let aggregate_post tenv procname acc {threads; accesses} = AccessDomain.fold (fun snapshot acc -> ReportMap.add {threads; snapshot; tenv; procname} acc) accesses acc in List.fold summaries ~init:ReportMap.empty ~f:(fun acc (procname, summary) -> if should_report_on_proc exe_env procname then let tenv = Exe_env.get_proc_tenv exe_env procname in aggregate_post tenv procname acc summary else acc ) let class_has_concurrent_method class_summaries = let open RacerDDomain in let method_has_concurrent_context (_, summary) = match (summary.threads : ThreadsDomain.t) with NoThread -> false | _ -> true in List.exists class_summaries ~f:method_has_concurrent_context let should_report_on_class (classname : Typ.Name.t) class_summaries = (not (RacerDModels.class_is_ignored_by_racerd classname)) && match classname with | JavaClass _ -> do n't do top - level reports on classes generated when compiling coroutines not (RacerDModels.is_kotlin_coroutine_generated classname) | CSharpClass _ -> true | CppClass _ | ObjcClass _ | ObjcProtocol _ | CStruct _ -> class_has_concurrent_method class_summaries | CUnion _ | ErlangType _ | HackClass _ -> false let aggregate_by_class {InterproceduralAnalysis.procedures; analyze_file_dependency} = List.fold procedures ~init:Typ.Name.Map.empty ~f:(fun acc procname -> Procname.get_class_type_name procname |> Option.bind ~f:(fun classname -> analyze_file_dependency procname |> Option.map ~f:(fun summary -> Typ.Name.Map.update classname (fun summaries_opt -> Some ((procname, summary) :: Option.value ~default:[] summaries_opt) ) acc ) ) |> Option.value ~default:acc ) |> Typ.Name.Map.filter should_report_on_class let get_synchronized_container_fields_of analyze tenv classname = let open RacerDDomain in let last_field_of_access_expression acc_exp = let _, path = HilExp.AccessExpression.to_access_path acc_exp in List.last path |> Option.bind ~f:(function AccessPath.FieldAccess fieldname -> Some fieldname | _ -> None) in let add_synchronized_container_field acc_exp attr acc = match attr with | Attribute.Synchronized -> last_field_of_access_expression acc_exp |> Option.fold ~init:acc ~f:(fun acc fieldname -> Fieldname.Set.add fieldname acc) | _ -> acc in Tenv.lookup tenv classname |> Option.value_map ~default:[] ~f:(fun (tstruct : Struct.t) -> tstruct.methods) |> List.rev_filter ~f:(function | Procname.Java j -> Procname.Java.(is_class_initializer j || is_constructor j) | _ -> false ) |> List.rev_filter_map ~f:analyze |> List.rev_map ~f:(fun (summary : summary) -> summary.attributes) |> List.fold ~init:Fieldname.Set.empty ~f:(fun acc attributes -> AttributeMapDomain.fold add_synchronized_container_field attributes acc ) let get_synchronized_container_fields_of, clear_sync_container_cache = let cache = Typ.Name.Hash.create 5 in ( (fun analyze tenv classname -> match Typ.Name.Hash.find_opt cache classname with | Some fieldset -> fieldset | None -> let fieldset = get_synchronized_container_fields_of analyze tenv classname in Typ.Name.Hash.add cache classname fieldset ; fieldset ) , fun () -> Typ.Name.Hash.clear cache ) let should_keep_container_access analyze tenv ((_base, path) : PathModuloThis.t) = let should_keep_access_ending_at_field fieldname = let classname = Fieldname.get_class_name fieldname in let sync_container_fields = get_synchronized_container_fields_of analyze tenv classname in not (Fieldname.Set.mem fieldname sync_container_fields) in let rec should_keep_container_access_inner rev_path = match rev_path with | [] -> true | AccessPath.ArrayAccess _ :: rest -> should_keep_container_access_inner rest | AccessPath.FieldAccess fieldname :: _ -> should_keep_access_ending_at_field fieldname in List.rev path |> should_keep_container_access_inner let analyze ({InterproceduralAnalysis.file_exe_env; analyze_file_dependency} as file_t) = let synchronized_container_filter = function | Typ.JavaClass _ -> let tenv = Exe_env.load_java_global_tenv file_exe_env in ReportMap.filter_container_accesses (should_keep_container_access analyze_file_dependency tenv) | _ -> Fn.id in let class_map = aggregate_by_class file_t in let result = Typ.Name.Map.fold (fun classname methods issue_log -> make_results_table file_exe_env methods |> synchronized_container_filter classname |> report_unsafe_accesses ~issue_log classname ) class_map IssueLog.empty in clear_sync_container_cache () ; result
8bb9954241d96c9496e9e67ac117b9a533b6e6679495a4fcd3d31b559bffd52f
GlideAngle/flare-timing
Goal.hs
module Flight.Gap.Fraction.Goal (NominalGoal(..)) where import GHC.Generics (Generic) import "newtype" Control.Newtype (Newtype(..)) import Data.Via.Scientific ( DecimalPlaces(..) , deriveDecimalPlaces, deriveJsonViaSci, deriveShowValueViaSci ) newtype NominalGoal = NominalGoal Rational deriving (Eq, Ord, Generic) instance Newtype NominalGoal Rational where pack = NominalGoal unpack (NominalGoal a) = a deriveDecimalPlaces (DecimalPlaces 8) ''NominalGoal deriveJsonViaSci ''NominalGoal deriveShowValueViaSci ''NominalGoal
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/gap-allot/library/Flight/Gap/Fraction/Goal.hs
haskell
module Flight.Gap.Fraction.Goal (NominalGoal(..)) where import GHC.Generics (Generic) import "newtype" Control.Newtype (Newtype(..)) import Data.Via.Scientific ( DecimalPlaces(..) , deriveDecimalPlaces, deriveJsonViaSci, deriveShowValueViaSci ) newtype NominalGoal = NominalGoal Rational deriving (Eq, Ord, Generic) instance Newtype NominalGoal Rational where pack = NominalGoal unpack (NominalGoal a) = a deriveDecimalPlaces (DecimalPlaces 8) ''NominalGoal deriveJsonViaSci ''NominalGoal deriveShowValueViaSci ''NominalGoal
40997208a77a030ba05d5d297019a67ff41a1be7bc3a53bab18e6439aad220c3
javalib-team/sawja
birA3.ml
* This file is part of SAWJA * Copyright ( c)2009 Delphine Demange ( INRIA ) * Copyright ( c)2009 ( INRIA ) * Copyright ( c)2010 ( INRIA ) * Copyright ( c)2016 ( ENS Rennes ) * Copyright ( c)2016 ( CNRS ) * * This program is free software : you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation , either version 3 of * the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * General Public License for more details . * * You should have received a copy of the GNU General Public * License along with this program . If not , see * < / > . * This file is part of SAWJA * Copyright (c)2009 Delphine Demange (INRIA) * Copyright (c)2009 David Pichardie (INRIA) * Copyright (c)2010 Vincent Monfort (INRIA) * Copyright (c)2016 David Pichardie (ENS Rennes) * Copyright (c)2016 Laurent Guillo (CNRS) * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * </>. *) open !Javalib_pack open JBasics open JCode include Cmn type tvar = JBasics.value_type * var type expr = | Const of const | Var of tvar | Unop of unop * tvar | Binop of binop * tvar * tvar | Field of tvar * JBasics.class_name * JBasics.field_signature | StaticField of JBasics.class_name * JBasics.field_signature let type_of_tvar (t,_) = t let type_of_expr = function | Var (t,_) -> t | Const i -> begin match i with | `ANull | `Class _ | `MethodHandle _ | `MethodType _ | `String _ -> TObject (TClass java_lang_object) | `Int _ -> TBasic `Int | `Double _ -> TBasic `Double | `Float _ -> TBasic `Float | `Long _ -> TBasic `Long end | Field (_,_,f) | StaticField (_,f) -> fs_type f | Unop (Cast t,_) -> TObject t | Unop (u,_) -> TBasic (match u with | Neg t -> basic_to_num t | Conv c -> (match c with | I2L | F2L | D2L -> `Long | I2F | L2F | D2F -> `Float | I2D | L2D | F2D -> `Double | L2I | F2I | D2I | I2B | I2C | I2S -> `Int) | ArrayLength | InstanceOf _ -> `Int | _ -> assert false) | Binop (ArrayLoad t,_,_) -> t | Binop (b,_,_) -> TBasic (match b with | ArrayLoad _ -> assert false | Add t | Sub t | Mult t | Div t | Rem t -> (match t with | `Int2Bool -> `Int | `Long -> `Long | `Double -> `Double | `Float -> `Float) | IShl | IShr | IAnd | IOr | IXor | IUshr -> `Int | LShl | LShr | LAnd | LOr | LXor | LUshr -> `Long | CMP _ -> `Int) type check = | CheckNullPointer of tvar | CheckArrayBound of tvar * tvar | CheckArrayStore of tvar * tvar | CheckNegativeArraySize of tvar | CheckCast of tvar * object_type | CheckArithmetic of tvar | CheckLink of jopcode type instr = | Nop | AffectVar of var * expr | AffectArray of tvar * tvar * tvar | AffectField of tvar * class_name * field_signature * tvar | AffectStaticField of class_name * field_signature * tvar | Alloc of var * JBasics.class_name | Goto of int | Ifd of ( [ `Eq | `Ge | `Gt | `Le | `Lt | `Ne ] * tvar * tvar ) * int | Throw of tvar | Return of tvar option | New of var * class_name * value_type list * (tvar list) (* var := class (parameters) *) | NewArray of var * value_type * (tvar list) (* var := value_type[e1]...[e2] *) | InvokeStatic of var option * class_name * method_signature * tvar list | InvokeVirtual of var option * tvar * virtual_call_kind * method_signature * tvar list | InvokeNonVirtual of var option * tvar * class_name * method_signature * tvar list | InvokeDynamic of var option * JBasics.bootstrap_method * JBasics.method_signature * tvar list | MonitorEnter of tvar | MonitorExit of tvar | MayInit of class_name | Check of check type t = { bir : Bir.bir; code is a copy of bir.code modulo a cast from jBir.instr to A3Bir.instr code : instr array; } let empty = { bir = Bir.empty; code = [||]; } let vars m = m.bir.Bir.bir_vars let params m = m.bir.Bir.bir_params let code m = m.code let exc_tbl m = m.bir.Bir.bir_exc_tbl let line_number_table m = m.bir.Bir.bir_line_number_table let fresh_counter = ref 0 let make_fresh_var (code:t) : var = incr fresh_counter; make_var code.bir.Bir.bir_dico (FreshVar(!fresh_counter)) (*let pc_bc2ir m = m.bir.Bir.bir_pc_bc2ir*) let pc_ir2bc m = m.bir.Bir.bir_pc_ir2bc let get_source_line_number pc_ir m = Bir.bir_get_source_line_number pc_ir m.bir let exception_edges m = Bir.bir_exception_edges m.bir let print m = Bir.bir_print m.bir let jump_target m = Bir.bir_jump_target m.bir (************* PRINT ************) let rec print_tvar ?(show_type=true) = function | (t,x) -> if show_type then Printf.sprintf "%s:%s" (var_name_g x) (print_typ t) else var_name_g x and print_expr ?(show_type=true) first_level = function | Const i -> print_const i | Var x -> print_tvar ~show_type:show_type x | Field (v,c,f) -> Printf.sprintf "%s.%s" (print_tvar ~show_type:show_type v) (JUtil.print_field c f) | StaticField (c,f) -> Printf.sprintf "%s.%s" (JPrint.class_name c) (fs_name f) | Unop (ArrayLength,e) -> Printf.sprintf "%s.length" (print_tvar ~show_type:show_type e) | Unop (Cast ot,e) -> Printf.sprintf "(%s) %s" (Javalib.JPrint.object_type ot) (print_tvar ~show_type:show_type e) | Unop (op,e) -> Printf.sprintf "%s(%s)" (print_unop op) (print_tvar ~show_type:show_type e) | Binop (ArrayLoad t,e1,e2) -> Printf.sprintf "%s[%s]:%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) (print_typ t) | Binop (Add _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s+%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Sub _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s-%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Mult _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s*%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Div _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s/%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (op,e1,e2) -> Printf.sprintf "%s(%s,%s)" (print_binop op) (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) let print_cmp ?(show_type=true) (c,e1,e2) = match c with | `Eq -> Printf.sprintf "%s == %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Ne -> Printf.sprintf "%s != %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Lt -> Printf.sprintf "%s < %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Ge -> Printf.sprintf "%s >= %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Gt -> Printf.sprintf "%s > %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Le -> Printf.sprintf "%s <= %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) let print_instr ?(show_type=true) = function | Nop -> "nop" | AffectVar (x,e) -> Printf.sprintf "%s := %s" (var_name_g x) (print_expr ~show_type:show_type true e) | AffectStaticField (c,f,e) -> Printf.sprintf "%s.%s := %s" (JPrint.class_name c) (fs_name f) (print_tvar ~show_type:show_type e) | AffectField (v,c,f,e2) -> Printf.sprintf "%s.%s := %s" (print_tvar ~show_type:show_type v) (JUtil.print_field c f) (print_tvar ~show_type:show_type e2) | AffectArray (v,e2,e3) -> Printf.sprintf "%s[%s] := %s" (print_tvar ~show_type:show_type v) (print_tvar ~show_type:show_type e2) (print_tvar ~show_type:show_type e3) | Goto i -> Printf.sprintf "goto %d" i | Ifd (g, el) -> Printf.sprintf "if (%s) goto %d" (print_cmp ~show_type:show_type g) el | Throw e -> Printf.sprintf "throw %s" (print_tvar ~show_type:show_type e) | Return None -> Printf.sprintf "return" | Return (Some e) -> Printf.sprintf "return %s" (print_tvar ~show_type:show_type e) | Alloc (x,c) -> Printf.sprintf "%s := ALLOC %s" (var_name_g x) (JPrint.class_name c) | New (x,c,_,le) -> Printf.sprintf "%s := new %s(%s)" (var_name_g x) (JPrint.class_name c) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | NewArray (x,c,le) -> Printf.sprintf "%s := new %s%s" (var_name_g x) (JPrint.value_type c) (JUtil.print_list_sep "" (fun e -> Printf.sprintf "[%s]" (print_tvar ~show_type:show_type e)) le) | InvokeStatic (None,c,ms,le) -> Printf.sprintf "%s.%s(%s) // static" (JPrint.class_name c) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeStatic (Some x,c,ms,le) -> Printf.sprintf "%s := %s.%s(%s) // static" (var_name_g x) (JPrint.class_name c) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeDynamic (None,_,ms,le) -> Printf.sprintf "DYNAMIC[%s](%s)" (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeDynamic (Some x,_,ms,le) -> Printf.sprintf "%s := DYNAMIC[%s](%s)" (var_name_g x) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeVirtual (r,x,k,ms,le) -> Printf.sprintf "%s%s.%s(%s) // %s" (match r with | None -> "" | Some x -> Printf.sprintf "%s := " (var_name_g x)) (print_tvar ~show_type:show_type x) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) (match k with | VirtualCall objt -> "virtual "^(JPrint.object_type objt) | InterfaceCall cn -> "interface "^(JPrint.class_name cn) ) | InvokeNonVirtual (r,x,kd,ms,le) -> Printf.sprintf "%s%s.%s.%s(%s)" (match r with | None -> "" | Some x -> Printf.sprintf "%s := " (var_name_g x)) (print_tvar ~show_type:show_type x) (JPrint.class_name kd) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | MonitorEnter e -> Printf.sprintf "monitorenter(%s)" (print_tvar ~show_type:show_type e) | MonitorExit e -> Printf.sprintf "monitorexit(%s)" (print_tvar ~show_type:show_type e) | MayInit c -> Printf.sprintf "mayinit %s" (JPrint.class_name c) | Check c -> begin match c with CheckNullPointer e -> Printf.sprintf "notnull %s" (print_tvar ~show_type:show_type e) | CheckArrayBound (a,i) -> Printf.sprintf "checkbound %s[%s]" (print_tvar ~show_type:show_type a) (print_tvar ~show_type:show_type i) | CheckArrayStore (a,v) -> Printf.sprintf "checkstore %s[] <- %s" (print_tvar ~show_type:show_type a) (print_tvar ~show_type:show_type v) | CheckNegativeArraySize e -> Printf.sprintf "checknegsize %s" (print_tvar ~show_type:show_type e) | CheckCast (e,t) -> Printf.sprintf "checkcast %s:%s" (print_tvar ~show_type:show_type e) (JDumpBasics.object_value_signature t) | CheckArithmetic e -> Printf.sprintf "notzero %s" (print_tvar ~show_type:show_type e) | CheckLink op -> Printf.sprintf "checklink (%s)" (JPrint.jopcode op) end let print_expr ?(show_type=true) = print_expr ~show_type:show_type true exception Bad_Multiarray_dimension = Bir.Bad_Multiarray_dimension exception Bad_stack = Bir.Bad_stack exception Subroutine = Bir.Subroutine exception InvalidClassFile = Bir.InvalidClassFile exception Content_constraint_on_Uninit = Bir.Content_constraint_on_Uninit exception Type_constraint_on_Uninit = Bir.Type_constraint_on_Uninit exception NonemptyStack_backward_jump = Bir.NonemptyStack_backward_jump exception Uninit_is_not_expr = Bir.Uninit_is_not_expr exception Exc_expr2tvar let expr2tvar expr = match expr with | Bir.Var (t,v) -> (t,v) | _ -> begin Printf.printf "expr2tvar fails on expr %s\n" (Bir.print_expr expr); raise Exc_expr2tvar end let bir2a3bir_binop = function | Bir.ArrayLoad t -> ArrayLoad t | Bir.Add t -> Add t | Bir.Sub t -> Sub t | Bir.Mult t -> Mult t | Bir.Div t -> Div t | Bir.Rem t -> Rem t | Bir.IShl -> IShl | Bir.IShr -> IShr | Bir.LShl -> LShl | Bir.LShr -> LShr | Bir.IAnd -> IAnd | Bir.IOr -> IOr | Bir.IXor -> IXor | Bir.IUshr -> IUshr | Bir.LAnd -> LAnd | Bir.LOr -> LOr | Bir.LXor -> LXor | Bir.LUshr -> LUshr | Bir.CMP c -> CMP c let bir2a3bir_expr e = match e with | Bir.Const c -> Const c | Bir.Var (t,v) -> Var (t,v) | Bir.Unop (unop, expr) -> Unop(unop,expr2tvar expr) | Bir.Binop(binop,expr1,expr2) -> Binop(bir2a3bir_binop binop,expr2tvar expr1,expr2tvar expr2) | Bir.Field(expr,cn,fs) -> Field (expr2tvar expr, cn, fs) | Bir.StaticField(cn,fs) -> StaticField(cn,fs) let kind2kind = function | Bir.VirtualCall objt -> VirtualCall objt | Bir.InterfaceCall cn -> InterfaceCall cn let check2check = function | Bir.CheckNullPointer e -> CheckNullPointer (expr2tvar e) | Bir.CheckArrayBound (e1, e2) -> CheckArrayBound (expr2tvar e1, expr2tvar e2) | Bir.CheckArrayStore (e1,e2) -> CheckArrayStore (expr2tvar e1, expr2tvar e2) | Bir.CheckNegativeArraySize e -> CheckNegativeArraySize (expr2tvar e) | Bir.CheckCast (e,t) -> CheckCast (expr2tvar e,t) | Bir.CheckArithmetic e -> CheckArithmetic (expr2tvar e) | Bir.CheckLink op -> CheckLink op let bir2a3bir_instr = function Bir.Nop -> Nop | Bir.AffectVar (v,expr) -> AffectVar (v,bir2a3bir_expr expr) | Bir.AffectArray(e1,e2,e3) -> AffectArray(expr2tvar e1, expr2tvar e2, expr2tvar e3) | Bir.AffectField(e1,cn,fs,e2) -> AffectField(expr2tvar e1,cn,fs,expr2tvar e2) | Bir.AffectStaticField(cn,fs,e) -> AffectStaticField(cn,fs,expr2tvar e) | Bir.Alloc(v,cn) -> Alloc(v,cn) | Bir.Goto i -> Goto i | Bir.Ifd ((cmp,e1,e2),i) -> Ifd ((cmp, expr2tvar e1,expr2tvar e2),i) | Bir.Throw e -> Throw (expr2tvar e) | Bir.Return (Some e) -> Return (Some (expr2tvar e)) | Bir.Return None -> Return None | Bir.New(v,cn,vtl,el) -> New (v,cn,vtl,List.map expr2tvar el) | Bir.NewArray(v,vt,el) -> NewArray(v,vt,List.map expr2tvar el) | Bir.InvokeDynamic(v,cn,ms,el) -> InvokeDynamic(v,cn,ms,List.map expr2tvar el) | Bir.InvokeStatic(v,cn,ms,el) -> InvokeStatic(v,cn,ms,List.map expr2tvar el) | Bir.InvokeVirtual(optv,expr, kind, ms, el) ->InvokeVirtual(optv, expr2tvar expr, kind2kind kind, ms, List.map expr2tvar el) | Bir.InvokeNonVirtual(optv, e, cn, ms, el) -> InvokeNonVirtual(optv,expr2tvar e, cn, ms, List.map expr2tvar el) | Bir.MonitorEnter e -> MonitorEnter (expr2tvar e) | Bir.MonitorExit e -> MonitorExit (expr2tvar e) | Bir.MayInit cn -> MayInit cn | Bir.Check c -> Check (check2check c) let bir2a3bir bir = try { bir = bir; code = Array.map bir2a3bir_instr bir.Bir.bir_code; } with Exc_expr2tvar -> List.iter (Printf.printf " %s\n") (Bir.bir_print bir); assert false (*************** FIELD Resolution ********************) let a3_code_map (f: instr -> instr) (m: t) : t = { m with code = Array.init (Array.length m.code) (fun i -> f m.code.(i)) } let a3_resolve_field prog cn fs = let class_node = JProgram.get_node prog cn in let res_node = JControlFlow.resolve_field_strong fs class_node in JProgram.get_name res_node let a3_resolve_field_in_expr prog (e: expr) : expr = match e with | Field (v,cn,fs) -> Field (v, a3_resolve_field prog cn fs, fs) | StaticField (cn,fs) -> StaticField (a3_resolve_field prog cn fs, fs) | Const _ | Var _ | Unop _ | Binop _ -> e let a3_field_resolve_in_code prog (inst:instr) : instr = match inst with | AffectVar(x,e) -> AffectVar(x, a3_resolve_field_in_expr prog e) | AffectField (x,cn,fs,y) -> AffectField(x, a3_resolve_field prog cn fs, fs, y) | AffectStaticField (cn,fs,e) -> AffectStaticField(a3_resolve_field prog cn fs, fs, e) | Nop | AffectArray _ | Goto _ | Ifd _ | Throw _ | Return _ | Alloc _ | New _ | NewArray _ | InvokeDynamic _ | InvokeStatic _ | InvokeVirtual _ | InvokeNonVirtual _ | MonitorEnter _ | MonitorExit _ | MayInit _ | Check _ -> inst let resolve_all_fields (prog: t JProgram.program) : t JProgram.program = JProgram.map_program (fun _ _ -> a3_code_map (a3_field_resolve_in_code prog)) None prog (*************** FIELD Resolution END ********************) module PrintIR = struct type p_instr = Bir.instr type p_code = t type p_handler = exception_handler let iter_code f m = Bir.iter_code f m.bir let iter_exc_handler f m = Bir.iter_exc_handler f m.bir let method_param_names = Bir.method_param_names (fun x -> x.bir) let inst_html = Bir.inst_html (fun x -> x.bir) let exc_handler_html = Bir.exc_handler_html end module Printer = JPrintHtml.Make(PrintIR) let print_class = Printer.print_class let print_program = Printer.print_program open JPrintPlugin.NewCodePrinter module MakeBirLikeFunctions = struct include Bir.IRUtil let method_param_names = Bir.method_param_names (fun x -> x.bir) include Bir.MakeCodeExcFunctions type p_code = t type p_instr = instr type p_expr = expr let find_ast_node_of_expr = function | Const _ -> None | Binop (ArrayLoad vt,_,_) -> Some (AdaptedASTGrammar.Expression (AdaptedASTGrammar.ArrayAccess (Some vt))) | Binop (_,_,_) -> None | Unop (InstanceOf ot,_) -> Some (AdaptedASTGrammar.Expression(AdaptedASTGrammar.InstanceOf ot)) | Unop (Cast ot,_) -> Some (AdaptedASTGrammar.Expression(AdaptedASTGrammar.Cast ot)) | Unop (_,_) -> None | Var (vt,var) -> Some (AdaptedASTGrammar.Name (AdaptedASTGrammar.SimpleName (var_name_g var,Some vt))) | Field (_,_,fs) | StaticField (_,fs) -> Some (AdaptedASTGrammar.Name (AdaptedASTGrammar.SimpleName (fs_name fs,Some (fs_type fs)))) let inst_disp' printf pp cod = let printf_esc = (fun i -> JPrintUtil.replace_forb_xml_ch ~repl_amp:true (printf i)) in printf_esc (cod.code).(pp) let get_source_line_number pp code = Bir.bir_get_source_line_number pp code.bir let inst_disp = inst_disp' (print_instr ~show_type:true) let to_plugin_warning jm pp_warn_map = to_plugin_warning' (fun c -> c.bir.Bir.bir_code) (fun c -> c.bir.Bir.bir_exc_tbl) jm pp_warn_map Bir.MakeBirLikeFunctions.find_ast_node find_ast_node_of_expr end module PluginPrinter = JPrintPlugin.NewCodePrinter.Make(MakeBirLikeFunctions)
null
https://raw.githubusercontent.com/javalib-team/sawja/8b09d26dd119b2cad6d3f469310881eaa6ceb403/src/birA3.ml
ocaml
var := class (parameters) var := value_type[e1]...[e2] let pc_bc2ir m = m.bir.Bir.bir_pc_bc2ir ************ PRINT *********** ************** FIELD Resolution ******************* ************** FIELD Resolution END *******************
* This file is part of SAWJA * Copyright ( c)2009 Delphine Demange ( INRIA ) * Copyright ( c)2009 ( INRIA ) * Copyright ( c)2010 ( INRIA ) * Copyright ( c)2016 ( ENS Rennes ) * Copyright ( c)2016 ( CNRS ) * * This program is free software : you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation , either version 3 of * the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * General Public License for more details . * * You should have received a copy of the GNU General Public * License along with this program . If not , see * < / > . * This file is part of SAWJA * Copyright (c)2009 Delphine Demange (INRIA) * Copyright (c)2009 David Pichardie (INRIA) * Copyright (c)2010 Vincent Monfort (INRIA) * Copyright (c)2016 David Pichardie (ENS Rennes) * Copyright (c)2016 Laurent Guillo (CNRS) * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * </>. *) open !Javalib_pack open JBasics open JCode include Cmn type tvar = JBasics.value_type * var type expr = | Const of const | Var of tvar | Unop of unop * tvar | Binop of binop * tvar * tvar | Field of tvar * JBasics.class_name * JBasics.field_signature | StaticField of JBasics.class_name * JBasics.field_signature let type_of_tvar (t,_) = t let type_of_expr = function | Var (t,_) -> t | Const i -> begin match i with | `ANull | `Class _ | `MethodHandle _ | `MethodType _ | `String _ -> TObject (TClass java_lang_object) | `Int _ -> TBasic `Int | `Double _ -> TBasic `Double | `Float _ -> TBasic `Float | `Long _ -> TBasic `Long end | Field (_,_,f) | StaticField (_,f) -> fs_type f | Unop (Cast t,_) -> TObject t | Unop (u,_) -> TBasic (match u with | Neg t -> basic_to_num t | Conv c -> (match c with | I2L | F2L | D2L -> `Long | I2F | L2F | D2F -> `Float | I2D | L2D | F2D -> `Double | L2I | F2I | D2I | I2B | I2C | I2S -> `Int) | ArrayLength | InstanceOf _ -> `Int | _ -> assert false) | Binop (ArrayLoad t,_,_) -> t | Binop (b,_,_) -> TBasic (match b with | ArrayLoad _ -> assert false | Add t | Sub t | Mult t | Div t | Rem t -> (match t with | `Int2Bool -> `Int | `Long -> `Long | `Double -> `Double | `Float -> `Float) | IShl | IShr | IAnd | IOr | IXor | IUshr -> `Int | LShl | LShr | LAnd | LOr | LXor | LUshr -> `Long | CMP _ -> `Int) type check = | CheckNullPointer of tvar | CheckArrayBound of tvar * tvar | CheckArrayStore of tvar * tvar | CheckNegativeArraySize of tvar | CheckCast of tvar * object_type | CheckArithmetic of tvar | CheckLink of jopcode type instr = | Nop | AffectVar of var * expr | AffectArray of tvar * tvar * tvar | AffectField of tvar * class_name * field_signature * tvar | AffectStaticField of class_name * field_signature * tvar | Alloc of var * JBasics.class_name | Goto of int | Ifd of ( [ `Eq | `Ge | `Gt | `Le | `Lt | `Ne ] * tvar * tvar ) * int | Throw of tvar | Return of tvar option | New of var * class_name * value_type list * (tvar list) | NewArray of var * value_type * (tvar list) | InvokeStatic of var option * class_name * method_signature * tvar list | InvokeVirtual of var option * tvar * virtual_call_kind * method_signature * tvar list | InvokeNonVirtual of var option * tvar * class_name * method_signature * tvar list | InvokeDynamic of var option * JBasics.bootstrap_method * JBasics.method_signature * tvar list | MonitorEnter of tvar | MonitorExit of tvar | MayInit of class_name | Check of check type t = { bir : Bir.bir; code is a copy of bir.code modulo a cast from jBir.instr to A3Bir.instr code : instr array; } let empty = { bir = Bir.empty; code = [||]; } let vars m = m.bir.Bir.bir_vars let params m = m.bir.Bir.bir_params let code m = m.code let exc_tbl m = m.bir.Bir.bir_exc_tbl let line_number_table m = m.bir.Bir.bir_line_number_table let fresh_counter = ref 0 let make_fresh_var (code:t) : var = incr fresh_counter; make_var code.bir.Bir.bir_dico (FreshVar(!fresh_counter)) let pc_ir2bc m = m.bir.Bir.bir_pc_ir2bc let get_source_line_number pc_ir m = Bir.bir_get_source_line_number pc_ir m.bir let exception_edges m = Bir.bir_exception_edges m.bir let print m = Bir.bir_print m.bir let jump_target m = Bir.bir_jump_target m.bir let rec print_tvar ?(show_type=true) = function | (t,x) -> if show_type then Printf.sprintf "%s:%s" (var_name_g x) (print_typ t) else var_name_g x and print_expr ?(show_type=true) first_level = function | Const i -> print_const i | Var x -> print_tvar ~show_type:show_type x | Field (v,c,f) -> Printf.sprintf "%s.%s" (print_tvar ~show_type:show_type v) (JUtil.print_field c f) | StaticField (c,f) -> Printf.sprintf "%s.%s" (JPrint.class_name c) (fs_name f) | Unop (ArrayLength,e) -> Printf.sprintf "%s.length" (print_tvar ~show_type:show_type e) | Unop (Cast ot,e) -> Printf.sprintf "(%s) %s" (Javalib.JPrint.object_type ot) (print_tvar ~show_type:show_type e) | Unop (op,e) -> Printf.sprintf "%s(%s)" (print_unop op) (print_tvar ~show_type:show_type e) | Binop (ArrayLoad t,e1,e2) -> Printf.sprintf "%s[%s]:%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) (print_typ t) | Binop (Add _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s+%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Sub _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s-%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Mult _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s*%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (Div _,e1,e2) -> JUtil.bracket first_level (Printf.sprintf "%s/%s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2)) | Binop (op,e1,e2) -> Printf.sprintf "%s(%s,%s)" (print_binop op) (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) let print_cmp ?(show_type=true) (c,e1,e2) = match c with | `Eq -> Printf.sprintf "%s == %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Ne -> Printf.sprintf "%s != %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Lt -> Printf.sprintf "%s < %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Ge -> Printf.sprintf "%s >= %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Gt -> Printf.sprintf "%s > %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) | `Le -> Printf.sprintf "%s <= %s" (print_tvar ~show_type:show_type e1) (print_tvar ~show_type:show_type e2) let print_instr ?(show_type=true) = function | Nop -> "nop" | AffectVar (x,e) -> Printf.sprintf "%s := %s" (var_name_g x) (print_expr ~show_type:show_type true e) | AffectStaticField (c,f,e) -> Printf.sprintf "%s.%s := %s" (JPrint.class_name c) (fs_name f) (print_tvar ~show_type:show_type e) | AffectField (v,c,f,e2) -> Printf.sprintf "%s.%s := %s" (print_tvar ~show_type:show_type v) (JUtil.print_field c f) (print_tvar ~show_type:show_type e2) | AffectArray (v,e2,e3) -> Printf.sprintf "%s[%s] := %s" (print_tvar ~show_type:show_type v) (print_tvar ~show_type:show_type e2) (print_tvar ~show_type:show_type e3) | Goto i -> Printf.sprintf "goto %d" i | Ifd (g, el) -> Printf.sprintf "if (%s) goto %d" (print_cmp ~show_type:show_type g) el | Throw e -> Printf.sprintf "throw %s" (print_tvar ~show_type:show_type e) | Return None -> Printf.sprintf "return" | Return (Some e) -> Printf.sprintf "return %s" (print_tvar ~show_type:show_type e) | Alloc (x,c) -> Printf.sprintf "%s := ALLOC %s" (var_name_g x) (JPrint.class_name c) | New (x,c,_,le) -> Printf.sprintf "%s := new %s(%s)" (var_name_g x) (JPrint.class_name c) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | NewArray (x,c,le) -> Printf.sprintf "%s := new %s%s" (var_name_g x) (JPrint.value_type c) (JUtil.print_list_sep "" (fun e -> Printf.sprintf "[%s]" (print_tvar ~show_type:show_type e)) le) | InvokeStatic (None,c,ms,le) -> Printf.sprintf "%s.%s(%s) // static" (JPrint.class_name c) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeStatic (Some x,c,ms,le) -> Printf.sprintf "%s := %s.%s(%s) // static" (var_name_g x) (JPrint.class_name c) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeDynamic (None,_,ms,le) -> Printf.sprintf "DYNAMIC[%s](%s)" (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeDynamic (Some x,_,ms,le) -> Printf.sprintf "%s := DYNAMIC[%s](%s)" (var_name_g x) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | InvokeVirtual (r,x,k,ms,le) -> Printf.sprintf "%s%s.%s(%s) // %s" (match r with | None -> "" | Some x -> Printf.sprintf "%s := " (var_name_g x)) (print_tvar ~show_type:show_type x) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) (match k with | VirtualCall objt -> "virtual "^(JPrint.object_type objt) | InterfaceCall cn -> "interface "^(JPrint.class_name cn) ) | InvokeNonVirtual (r,x,kd,ms,le) -> Printf.sprintf "%s%s.%s.%s(%s)" (match r with | None -> "" | Some x -> Printf.sprintf "%s := " (var_name_g x)) (print_tvar ~show_type:show_type x) (JPrint.class_name kd) (ms_name ms) (JUtil.print_list_sep "," (print_tvar ~show_type:show_type) le) | MonitorEnter e -> Printf.sprintf "monitorenter(%s)" (print_tvar ~show_type:show_type e) | MonitorExit e -> Printf.sprintf "monitorexit(%s)" (print_tvar ~show_type:show_type e) | MayInit c -> Printf.sprintf "mayinit %s" (JPrint.class_name c) | Check c -> begin match c with CheckNullPointer e -> Printf.sprintf "notnull %s" (print_tvar ~show_type:show_type e) | CheckArrayBound (a,i) -> Printf.sprintf "checkbound %s[%s]" (print_tvar ~show_type:show_type a) (print_tvar ~show_type:show_type i) | CheckArrayStore (a,v) -> Printf.sprintf "checkstore %s[] <- %s" (print_tvar ~show_type:show_type a) (print_tvar ~show_type:show_type v) | CheckNegativeArraySize e -> Printf.sprintf "checknegsize %s" (print_tvar ~show_type:show_type e) | CheckCast (e,t) -> Printf.sprintf "checkcast %s:%s" (print_tvar ~show_type:show_type e) (JDumpBasics.object_value_signature t) | CheckArithmetic e -> Printf.sprintf "notzero %s" (print_tvar ~show_type:show_type e) | CheckLink op -> Printf.sprintf "checklink (%s)" (JPrint.jopcode op) end let print_expr ?(show_type=true) = print_expr ~show_type:show_type true exception Bad_Multiarray_dimension = Bir.Bad_Multiarray_dimension exception Bad_stack = Bir.Bad_stack exception Subroutine = Bir.Subroutine exception InvalidClassFile = Bir.InvalidClassFile exception Content_constraint_on_Uninit = Bir.Content_constraint_on_Uninit exception Type_constraint_on_Uninit = Bir.Type_constraint_on_Uninit exception NonemptyStack_backward_jump = Bir.NonemptyStack_backward_jump exception Uninit_is_not_expr = Bir.Uninit_is_not_expr exception Exc_expr2tvar let expr2tvar expr = match expr with | Bir.Var (t,v) -> (t,v) | _ -> begin Printf.printf "expr2tvar fails on expr %s\n" (Bir.print_expr expr); raise Exc_expr2tvar end let bir2a3bir_binop = function | Bir.ArrayLoad t -> ArrayLoad t | Bir.Add t -> Add t | Bir.Sub t -> Sub t | Bir.Mult t -> Mult t | Bir.Div t -> Div t | Bir.Rem t -> Rem t | Bir.IShl -> IShl | Bir.IShr -> IShr | Bir.LShl -> LShl | Bir.LShr -> LShr | Bir.IAnd -> IAnd | Bir.IOr -> IOr | Bir.IXor -> IXor | Bir.IUshr -> IUshr | Bir.LAnd -> LAnd | Bir.LOr -> LOr | Bir.LXor -> LXor | Bir.LUshr -> LUshr | Bir.CMP c -> CMP c let bir2a3bir_expr e = match e with | Bir.Const c -> Const c | Bir.Var (t,v) -> Var (t,v) | Bir.Unop (unop, expr) -> Unop(unop,expr2tvar expr) | Bir.Binop(binop,expr1,expr2) -> Binop(bir2a3bir_binop binop,expr2tvar expr1,expr2tvar expr2) | Bir.Field(expr,cn,fs) -> Field (expr2tvar expr, cn, fs) | Bir.StaticField(cn,fs) -> StaticField(cn,fs) let kind2kind = function | Bir.VirtualCall objt -> VirtualCall objt | Bir.InterfaceCall cn -> InterfaceCall cn let check2check = function | Bir.CheckNullPointer e -> CheckNullPointer (expr2tvar e) | Bir.CheckArrayBound (e1, e2) -> CheckArrayBound (expr2tvar e1, expr2tvar e2) | Bir.CheckArrayStore (e1,e2) -> CheckArrayStore (expr2tvar e1, expr2tvar e2) | Bir.CheckNegativeArraySize e -> CheckNegativeArraySize (expr2tvar e) | Bir.CheckCast (e,t) -> CheckCast (expr2tvar e,t) | Bir.CheckArithmetic e -> CheckArithmetic (expr2tvar e) | Bir.CheckLink op -> CheckLink op let bir2a3bir_instr = function Bir.Nop -> Nop | Bir.AffectVar (v,expr) -> AffectVar (v,bir2a3bir_expr expr) | Bir.AffectArray(e1,e2,e3) -> AffectArray(expr2tvar e1, expr2tvar e2, expr2tvar e3) | Bir.AffectField(e1,cn,fs,e2) -> AffectField(expr2tvar e1,cn,fs,expr2tvar e2) | Bir.AffectStaticField(cn,fs,e) -> AffectStaticField(cn,fs,expr2tvar e) | Bir.Alloc(v,cn) -> Alloc(v,cn) | Bir.Goto i -> Goto i | Bir.Ifd ((cmp,e1,e2),i) -> Ifd ((cmp, expr2tvar e1,expr2tvar e2),i) | Bir.Throw e -> Throw (expr2tvar e) | Bir.Return (Some e) -> Return (Some (expr2tvar e)) | Bir.Return None -> Return None | Bir.New(v,cn,vtl,el) -> New (v,cn,vtl,List.map expr2tvar el) | Bir.NewArray(v,vt,el) -> NewArray(v,vt,List.map expr2tvar el) | Bir.InvokeDynamic(v,cn,ms,el) -> InvokeDynamic(v,cn,ms,List.map expr2tvar el) | Bir.InvokeStatic(v,cn,ms,el) -> InvokeStatic(v,cn,ms,List.map expr2tvar el) | Bir.InvokeVirtual(optv,expr, kind, ms, el) ->InvokeVirtual(optv, expr2tvar expr, kind2kind kind, ms, List.map expr2tvar el) | Bir.InvokeNonVirtual(optv, e, cn, ms, el) -> InvokeNonVirtual(optv,expr2tvar e, cn, ms, List.map expr2tvar el) | Bir.MonitorEnter e -> MonitorEnter (expr2tvar e) | Bir.MonitorExit e -> MonitorExit (expr2tvar e) | Bir.MayInit cn -> MayInit cn | Bir.Check c -> Check (check2check c) let bir2a3bir bir = try { bir = bir; code = Array.map bir2a3bir_instr bir.Bir.bir_code; } with Exc_expr2tvar -> List.iter (Printf.printf " %s\n") (Bir.bir_print bir); assert false let a3_code_map (f: instr -> instr) (m: t) : t = { m with code = Array.init (Array.length m.code) (fun i -> f m.code.(i)) } let a3_resolve_field prog cn fs = let class_node = JProgram.get_node prog cn in let res_node = JControlFlow.resolve_field_strong fs class_node in JProgram.get_name res_node let a3_resolve_field_in_expr prog (e: expr) : expr = match e with | Field (v,cn,fs) -> Field (v, a3_resolve_field prog cn fs, fs) | StaticField (cn,fs) -> StaticField (a3_resolve_field prog cn fs, fs) | Const _ | Var _ | Unop _ | Binop _ -> e let a3_field_resolve_in_code prog (inst:instr) : instr = match inst with | AffectVar(x,e) -> AffectVar(x, a3_resolve_field_in_expr prog e) | AffectField (x,cn,fs,y) -> AffectField(x, a3_resolve_field prog cn fs, fs, y) | AffectStaticField (cn,fs,e) -> AffectStaticField(a3_resolve_field prog cn fs, fs, e) | Nop | AffectArray _ | Goto _ | Ifd _ | Throw _ | Return _ | Alloc _ | New _ | NewArray _ | InvokeDynamic _ | InvokeStatic _ | InvokeVirtual _ | InvokeNonVirtual _ | MonitorEnter _ | MonitorExit _ | MayInit _ | Check _ -> inst let resolve_all_fields (prog: t JProgram.program) : t JProgram.program = JProgram.map_program (fun _ _ -> a3_code_map (a3_field_resolve_in_code prog)) None prog module PrintIR = struct type p_instr = Bir.instr type p_code = t type p_handler = exception_handler let iter_code f m = Bir.iter_code f m.bir let iter_exc_handler f m = Bir.iter_exc_handler f m.bir let method_param_names = Bir.method_param_names (fun x -> x.bir) let inst_html = Bir.inst_html (fun x -> x.bir) let exc_handler_html = Bir.exc_handler_html end module Printer = JPrintHtml.Make(PrintIR) let print_class = Printer.print_class let print_program = Printer.print_program open JPrintPlugin.NewCodePrinter module MakeBirLikeFunctions = struct include Bir.IRUtil let method_param_names = Bir.method_param_names (fun x -> x.bir) include Bir.MakeCodeExcFunctions type p_code = t type p_instr = instr type p_expr = expr let find_ast_node_of_expr = function | Const _ -> None | Binop (ArrayLoad vt,_,_) -> Some (AdaptedASTGrammar.Expression (AdaptedASTGrammar.ArrayAccess (Some vt))) | Binop (_,_,_) -> None | Unop (InstanceOf ot,_) -> Some (AdaptedASTGrammar.Expression(AdaptedASTGrammar.InstanceOf ot)) | Unop (Cast ot,_) -> Some (AdaptedASTGrammar.Expression(AdaptedASTGrammar.Cast ot)) | Unop (_,_) -> None | Var (vt,var) -> Some (AdaptedASTGrammar.Name (AdaptedASTGrammar.SimpleName (var_name_g var,Some vt))) | Field (_,_,fs) | StaticField (_,fs) -> Some (AdaptedASTGrammar.Name (AdaptedASTGrammar.SimpleName (fs_name fs,Some (fs_type fs)))) let inst_disp' printf pp cod = let printf_esc = (fun i -> JPrintUtil.replace_forb_xml_ch ~repl_amp:true (printf i)) in printf_esc (cod.code).(pp) let get_source_line_number pp code = Bir.bir_get_source_line_number pp code.bir let inst_disp = inst_disp' (print_instr ~show_type:true) let to_plugin_warning jm pp_warn_map = to_plugin_warning' (fun c -> c.bir.Bir.bir_code) (fun c -> c.bir.Bir.bir_exc_tbl) jm pp_warn_map Bir.MakeBirLikeFunctions.find_ast_node find_ast_node_of_expr end module PluginPrinter = JPrintPlugin.NewCodePrinter.Make(MakeBirLikeFunctions)
bec026a0f67a0127998ca241f47ac96ecd27be12b54be13657060383ced73cc5
thizanne/snake
snake.ml
open Lwt.Infix let flip f x y = f y x let pi = 4.0 *. atan 1.0 let window = Dom_html.window let str = Js.string let alert s = window##alert (str s) let ( %% ) n k = (* Fixes modulo for negative n *) if n < 0 then k + n mod k else n mod k let () = Random.self_init () let ( @> ) id coercion = try Dom_html.getElementById id |> coercion |> flip Js.Opt.get (fun () -> alert "Coercion impossible"; assert false) with Not_found -> Printf.ksprintf alert {|Élément "%s" introuvable|} id; raise Not_found (*************************) (* Behaviour of the game *) (*************************) type direction = | North | South | East | West let opposite = function | North -> South | South -> North | West -> East | East -> West type tile = (* | Wall | Mouse *) | Empty | SnakeHead of { from : direction } | SnakeBody of { from : direction; toward : direction } | SnakeTail of { toward : direction } | Apple type state = { grid : tile array array; mutable direction : direction; mutable just_ate : bool; mutable head_pos : int * int; mutable tail_pos : int * int; } type move_result = | AteApple | AteItself | Nothing let head_comes_from state = (* Return the direction from which the head comes *) let head_i, head_j = state.head_pos in match state.grid.(head_i).(head_j) with | SnakeHead { from } -> from | _ -> assert false let body_goes_toward state (i, j) = (* Return the direction toward which or a body segment goes *) match state.grid.(i).(j) with | SnakeBody { toward; _ } -> toward | _ -> assert false let tail_goes_toward state = (* Return the direction toward which the tail goes *) let (i, j) = state.tail_pos in match state.grid.(i).(j) with | SnakeTail { toward } -> toward | _ -> assert false let next_position state (i, j) direction = let (i, j) = match direction with | North -> i - 1, j | South -> i + 1, j | East -> i, j - 1 | West -> i, j + 1 in i %% Array.length state.grid, j %% Array.length state.grid.(0) let move_head state = Moves the head one step forward . Returns the result of this move : either the snake ate an apple , or it ate itself , or nothing particular happened . This is supposed to be run after the tail moves , so eating it is losing . either the snake ate an apple, or it ate itself, or nothing particular happened. This is supposed to be run after the tail moves, so eating it is losing. *) let i, j = state.head_pos in let from = head_comes_from state in (* Replace the head by a body segment *) state.grid.(i).(j) <- SnakeBody { from; toward = state.direction }; (* Get the new position of the head *) let i', j' = next_position state (i, j) state.direction in (* Get the result and set just_ate *) let result = match state.grid.(i').(j') with | Empty -> state.just_ate <- false; Nothing | SnakeTail _ | SnakeBody _ -> AteItself | Apple -> state.just_ate <- true; AteApple | SnakeHead _ -> assert false in (* Move the head *) state.grid.(i').(j') <- SnakeHead { from = opposite state.direction }; state.head_pos <- (i', j'); (* Return the result of the move *) result let move_tail state = let (i, j) = state.tail_pos in (* Remove the tail *) let tail_dir = tail_goes_toward state in state.grid.(i).(j) <- Empty; (* Create the new tail *) let (i', j') = next_position state (i, j) tail_dir in let toward = body_goes_toward state (i', j') in state.grid.(i').(j') <- SnakeTail { toward }; state.tail_pos <- (i', j') let rec spawn_apple state = (* Puts an apple on a board on a free position *) let i = Random.int (Array.length state.grid) in let j = Random.int (Array.length state.grid.(0)) in if state.grid.(i).(j) = Empty then state.grid.(i).(j) <- Apple else spawn_apple state let update state = Updates one state : moves the head , possibly moves the tail and spawns an apple . Returns the result of the move . spawns an apple. Returns the result of the move. *) if not state.just_ate then move_tail state; let result = move_head state in if result = AteApple then spawn_apple state; result let make_state ~rows ~cols = let grid = Array.make_matrix rows cols Empty in let i, j = rows / 2, cols / 2 in grid.(i).(j - 1) <- SnakeTail { toward = West }; grid.(i).(j) <- SnakeBody { from = East; toward = West }; grid.(i).(j + 1) <- SnakeHead { from = East }; let state = { grid; direction = West; just_ate = false; head_pos = (i, j + 1); tail_pos = (i, j - 1); } in spawn_apple state; state let register_direction direction state = (* Tries to register a new direction for the snake. If the head comes from this direction, does nothing. *) let head_direction = head_comes_from state in if direction <> head_direction then state.direction <- direction (******************) (* Graphical part *) (******************) let canvas_coords (i, j) = float (j * 10), float (i * 10) let draw_head context _from x y = context##.fillStyle := str "#0000FF"; context##fillRect x y 10. 10. let draw_body context _from _toward x y = context##.fillStyle := str "#00FF00"; context##fillRect x y 10. 10. let draw_tail context _toward x y = context##.fillStyle := str "#000000"; context##fillRect x y 10. 10. let draw_apple context x y = context##.fillStyle := str "#FF0000"; context##fillRect x y 10. 10. let draw_tile context i j tile = let x, y = canvas_coords (i, j) in match tile with | SnakeHead { from } -> draw_head context from x y | SnakeBody { from; toward } -> draw_body context from toward x y | SnakeTail { toward } -> draw_tail context toward x y | Apple -> draw_apple context x y | Empty -> () let draw_state context state = let rows = Array.length state.grid in let cols = Array.length state.grid.(0) in let x, y = canvas_coords (rows, cols) in context##clearRect 0. 0. x y; for i = 0 to rows - 1 do for j = 0 to cols - 1 do draw_tile context i j state.grid.(i).(j) done done; context##fill let rec main_loop context state = Lwt_js.sleep 0.05 >>= fun () -> let result = update state in draw_state context state; if result <> AteItself then main_loop context state else (alert "Perdu"; Lwt.return ()) let change_direction state = function | "ArrowRight" -> register_direction West state | "ArrowLeft" -> register_direction East state | "ArrowUp" -> register_direction North state | "ArrowDown" -> register_direction South state | _ -> () let control_loop state = Lwt_js_events.keypresses window (fun ev _thread -> let key_pressed = Js.Optdef.get ev##.key (fun () -> alert "oups"; assert false) in change_direction state (Js.to_string key_pressed); Lwt.return ()) let display_keyboard () = let key_elt = Dom_html.getElementById "key" in Lwt_js_events.keypresses window (fun ev _thread -> let key_pressed = Js.Optdef.get ev##.key (fun () -> key_elt##.innerHTML := (str "oups"); assert false) in key_elt##.innerHTML := key_pressed; Lwt.return ()) let _ : unit Lwt.t = let%lwt () = Lwt_js_events.domContentLoaded () in let canvas = "canvas" @> Dom_html.CoerceTo.canvas in let context = canvas##getContext Dom_html._2d_ in let state = make_state ~rows:50 ~cols:100 in Lwt.join [ main_loop context state; control_loop state; display_keyboard (); ] Local Variables : compile - command : " ocamlfind ocamlc -package js_of_ocaml.ppx \ -package lwt.ppx \ -linkpkg -o snake.bytes snake.ml ; js_of_ocaml snake.bytes " End : Local Variables: compile-command: "ocamlfind ocamlc -package js_of_ocaml-lwt -package js_of_ocaml.ppx \ -package lwt.ppx \ -linkpkg -o snake.bytes snake.ml; js_of_ocaml snake.bytes" End: *)
null
https://raw.githubusercontent.com/thizanne/snake/0671810a2c43f2e58bea8384b00ad08050e63184/snake.ml
ocaml
Fixes modulo for negative n *********************** Behaviour of the game *********************** | Wall | Mouse Return the direction from which the head comes Return the direction toward which or a body segment goes Return the direction toward which the tail goes Replace the head by a body segment Get the new position of the head Get the result and set just_ate Move the head Return the result of the move Remove the tail Create the new tail Puts an apple on a board on a free position Tries to register a new direction for the snake. If the head comes from this direction, does nothing. **************** Graphical part ****************
open Lwt.Infix let flip f x y = f y x let pi = 4.0 *. atan 1.0 let window = Dom_html.window let str = Js.string let alert s = window##alert (str s) let ( %% ) n k = if n < 0 then k + n mod k else n mod k let () = Random.self_init () let ( @> ) id coercion = try Dom_html.getElementById id |> coercion |> flip Js.Opt.get (fun () -> alert "Coercion impossible"; assert false) with Not_found -> Printf.ksprintf alert {|Élément "%s" introuvable|} id; raise Not_found type direction = | North | South | East | West let opposite = function | North -> South | South -> North | West -> East | East -> West type tile = | Empty | SnakeHead of { from : direction } | SnakeBody of { from : direction; toward : direction } | SnakeTail of { toward : direction } | Apple type state = { grid : tile array array; mutable direction : direction; mutable just_ate : bool; mutable head_pos : int * int; mutable tail_pos : int * int; } type move_result = | AteApple | AteItself | Nothing let head_comes_from state = let head_i, head_j = state.head_pos in match state.grid.(head_i).(head_j) with | SnakeHead { from } -> from | _ -> assert false let body_goes_toward state (i, j) = match state.grid.(i).(j) with | SnakeBody { toward; _ } -> toward | _ -> assert false let tail_goes_toward state = let (i, j) = state.tail_pos in match state.grid.(i).(j) with | SnakeTail { toward } -> toward | _ -> assert false let next_position state (i, j) direction = let (i, j) = match direction with | North -> i - 1, j | South -> i + 1, j | East -> i, j - 1 | West -> i, j + 1 in i %% Array.length state.grid, j %% Array.length state.grid.(0) let move_head state = Moves the head one step forward . Returns the result of this move : either the snake ate an apple , or it ate itself , or nothing particular happened . This is supposed to be run after the tail moves , so eating it is losing . either the snake ate an apple, or it ate itself, or nothing particular happened. This is supposed to be run after the tail moves, so eating it is losing. *) let i, j = state.head_pos in let from = head_comes_from state in state.grid.(i).(j) <- SnakeBody { from; toward = state.direction }; let i', j' = next_position state (i, j) state.direction in let result = match state.grid.(i').(j') with | Empty -> state.just_ate <- false; Nothing | SnakeTail _ | SnakeBody _ -> AteItself | Apple -> state.just_ate <- true; AteApple | SnakeHead _ -> assert false in state.grid.(i').(j') <- SnakeHead { from = opposite state.direction }; state.head_pos <- (i', j'); result let move_tail state = let (i, j) = state.tail_pos in let tail_dir = tail_goes_toward state in state.grid.(i).(j) <- Empty; let (i', j') = next_position state (i, j) tail_dir in let toward = body_goes_toward state (i', j') in state.grid.(i').(j') <- SnakeTail { toward }; state.tail_pos <- (i', j') let rec spawn_apple state = let i = Random.int (Array.length state.grid) in let j = Random.int (Array.length state.grid.(0)) in if state.grid.(i).(j) = Empty then state.grid.(i).(j) <- Apple else spawn_apple state let update state = Updates one state : moves the head , possibly moves the tail and spawns an apple . Returns the result of the move . spawns an apple. Returns the result of the move. *) if not state.just_ate then move_tail state; let result = move_head state in if result = AteApple then spawn_apple state; result let make_state ~rows ~cols = let grid = Array.make_matrix rows cols Empty in let i, j = rows / 2, cols / 2 in grid.(i).(j - 1) <- SnakeTail { toward = West }; grid.(i).(j) <- SnakeBody { from = East; toward = West }; grid.(i).(j + 1) <- SnakeHead { from = East }; let state = { grid; direction = West; just_ate = false; head_pos = (i, j + 1); tail_pos = (i, j - 1); } in spawn_apple state; state let register_direction direction state = let head_direction = head_comes_from state in if direction <> head_direction then state.direction <- direction let canvas_coords (i, j) = float (j * 10), float (i * 10) let draw_head context _from x y = context##.fillStyle := str "#0000FF"; context##fillRect x y 10. 10. let draw_body context _from _toward x y = context##.fillStyle := str "#00FF00"; context##fillRect x y 10. 10. let draw_tail context _toward x y = context##.fillStyle := str "#000000"; context##fillRect x y 10. 10. let draw_apple context x y = context##.fillStyle := str "#FF0000"; context##fillRect x y 10. 10. let draw_tile context i j tile = let x, y = canvas_coords (i, j) in match tile with | SnakeHead { from } -> draw_head context from x y | SnakeBody { from; toward } -> draw_body context from toward x y | SnakeTail { toward } -> draw_tail context toward x y | Apple -> draw_apple context x y | Empty -> () let draw_state context state = let rows = Array.length state.grid in let cols = Array.length state.grid.(0) in let x, y = canvas_coords (rows, cols) in context##clearRect 0. 0. x y; for i = 0 to rows - 1 do for j = 0 to cols - 1 do draw_tile context i j state.grid.(i).(j) done done; context##fill let rec main_loop context state = Lwt_js.sleep 0.05 >>= fun () -> let result = update state in draw_state context state; if result <> AteItself then main_loop context state else (alert "Perdu"; Lwt.return ()) let change_direction state = function | "ArrowRight" -> register_direction West state | "ArrowLeft" -> register_direction East state | "ArrowUp" -> register_direction North state | "ArrowDown" -> register_direction South state | _ -> () let control_loop state = Lwt_js_events.keypresses window (fun ev _thread -> let key_pressed = Js.Optdef.get ev##.key (fun () -> alert "oups"; assert false) in change_direction state (Js.to_string key_pressed); Lwt.return ()) let display_keyboard () = let key_elt = Dom_html.getElementById "key" in Lwt_js_events.keypresses window (fun ev _thread -> let key_pressed = Js.Optdef.get ev##.key (fun () -> key_elt##.innerHTML := (str "oups"); assert false) in key_elt##.innerHTML := key_pressed; Lwt.return ()) let _ : unit Lwt.t = let%lwt () = Lwt_js_events.domContentLoaded () in let canvas = "canvas" @> Dom_html.CoerceTo.canvas in let context = canvas##getContext Dom_html._2d_ in let state = make_state ~rows:50 ~cols:100 in Lwt.join [ main_loop context state; control_loop state; display_keyboard (); ] Local Variables : compile - command : " ocamlfind ocamlc -package js_of_ocaml.ppx \ -package lwt.ppx \ -linkpkg -o snake.bytes snake.ml ; js_of_ocaml snake.bytes " End : Local Variables: compile-command: "ocamlfind ocamlc -package js_of_ocaml-lwt -package js_of_ocaml.ppx \ -package lwt.ppx \ -linkpkg -o snake.bytes snake.ml; js_of_ocaml snake.bytes" End: *)
3256ba11d33df587951285c0071bb37d3c64a8bc9d74d7b1ac989eee8bd77d0f
ucsd-progsys/dsolve
pervasives.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ I d : pervasives.mli , v 1.108 2007/02/21 14:15:19 xleroy Exp $ (** The initially opened module. This module provides the basic operations over the built-in types (numbers, booleans, strings, exceptions, references, lists, arrays, input-output channels, ...) This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by [Pervasives]. *) * { 6 Exceptions } external raise : exn -> 'a = "%raise" (** Raise the given exception value *) val invalid_arg : string -> 'a (** Raise exception [Invalid_argument] with the given string. *) val failwith : string -> 'a (** Raise exception [Failure] with the given string. *) exception Exit (** The [Exit] exception is not raised by any library function. It is provided for use in your programs.*) * { 6 Comparisons } external ( = ) : 'a -> 'a -> bool = "%equal" * [ e1 = e2 ] tests for structural equality of [ e1 ] and [ e2 ] . Mutable structures ( e.g. references and arrays ) are equal if and only if their current contents are structurally equal , even if the two mutable objects are not the same physical object . Equality between functional values raises [ Invalid_argument ] . Equality between cyclic data structures does not terminate . Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises [Invalid_argument]. Equality between cyclic data structures does not terminate. *) external ( <> ) : 'a -> 'a -> bool = "%notequal" (** Negation of {!Pervasives.(=)}. *) external ( < ) : 'a -> 'a -> bool = "%lessthan" (** See {!Pervasives.(>=)}. *) external ( > ) : 'a -> 'a -> bool = "%greaterthan" (** See {!Pervasives.(>=)}. *) external ( <= ) : 'a -> 'a -> bool = "%lessequal" (** See {!Pervasives.(>=)}. *) external ( >= ) : 'a -> 'a -> bool = "%greaterequal" (** Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with [(=)]. As in the case of [(=)], mutable structures are compared by contents. Comparison between functional values raises [Invalid_argument]. Comparison between cyclic structures does not terminate. *) external compare : 'a -> 'a -> int = "%compare" * [ compare x y ] returns [ 0 ] if [ x ] is equal to [ y ] , a negative integer if [ x ] is less than [ y ] , and a positive integer if [ x ] is greater than [ y ] . The ordering implemented by [ compare ] is compatible with the comparison predicates [ =] , [ < ] and [ > ] defined above , with one difference on the treatment of the float value { ! } . Namely , the comparison predicates treat [ nan ] as different from any other float value , including itself ; while [ compare ] treats [ nan ] as equal to itself and less than any other float value . This treatment of ensures that [ compare ] defines a total ordering relation . [ compare ] applied to functional values may raise [ Invalid_argument ] . [ compare ] applied to cyclic structures may not terminate . The [ compare ] function can be used as the comparison function required by the { ! Set . Make } and { ! Map . Make } functors , as well as the { ! List.sort } and { ! Array.sort } functions . a negative integer if [x] is less than [y], and a positive integer if [x] is greater than [y]. The ordering implemented by [compare] is compatible with the comparison predicates [=], [<] and [>] defined above, with one difference on the treatment of the float value {!Pervasives.nan}. Namely, the comparison predicates treat [nan] as different from any other float value, including itself; while [compare] treats [nan] as equal to itself and less than any other float value. This treatment of [nan] ensures that [compare] defines a total ordering relation. [compare] applied to functional values may raise [Invalid_argument]. [compare] applied to cyclic structures may not terminate. The [compare] function can be used as the comparison function required by the {!Set.Make} and {!Map.Make} functors, as well as the {!List.sort} and {!Array.sort} functions. *) val min : 'a -> 'a -> 'a * Return the smaller of the two arguments . val max : 'a -> 'a -> 'a * Return the greater of the two arguments . external ( == ) : 'a -> 'a -> bool = "%eq" (** [e1 == e2] tests for physical equality of [e1] and [e2]. On integers and characters, physical equality is identical to structural equality. On mutable structures, [e1 == e2] is true if and only if physical modification of [e1] also affects [e2]. On non-mutable structures, the behavior of [(==)] is implementation-dependent; however, it is guaranteed that [e1 == e2] implies [compare e1 e2 = 0]. *) external ( != ) : 'a -> 'a -> bool = "%noteq" (** Negation of {!Pervasives.(==)}. *) * { 6 Boolean operations } external not : bool -> bool = "%boolnot" (** The boolean negation. *) external ( && ) : bool -> bool -> bool = "%sequand" * The boolean ` ` and '' . Evaluation is sequential , left - to - right : in [ e1 & & e2 ] , [ e1 ] is evaluated first , and if it returns [ false ] , [ e2 ] is not evaluated at all . in [e1 && e2], [e1] is evaluated first, and if it returns [false], [e2] is not evaluated at all. *) external ( & ) : bool -> bool -> bool = "%sequand" (** @deprecated {!Pervasives.(&&)} should be used instead. *) external ( || ) : bool -> bool -> bool = "%sequor" * The boolean ` ` or '' . Evaluation is sequential , left - to - right : in [ e1 || e2 ] , [ e1 ] is evaluated first , and if it returns [ true ] , [ e2 ] is not evaluated at all . in [e1 || e2], [e1] is evaluated first, and if it returns [true], [e2] is not evaluated at all. *) external ( or ) : bool -> bool -> bool = "%sequor" * @deprecated { ! ) } should be used instead . * { 6 Integer arithmetic } * Integers are 31 bits wide ( or 63 bits on 64 - bit processors ) . All operations are taken modulo 2{^31 } ( or 2{^63 } ) . They do not fail on overflow . All operations are taken modulo 2{^31} (or 2{^63}). They do not fail on overflow. *) external ( ~- ) : int -> int = "%negint" (** Unary negation. You can also write [-e] instead of [~-e]. *) external succ : int -> int = "%succint" (** [succ x] is [x+1]. *) external pred : int -> int = "%predint" (** [pred x] is [x-1]. *) external ( + ) : int -> int -> int = "%addint" (** Integer addition. *) external ( - ) : int -> int -> int = "%subint" (** Integer subtraction. *) external ( * ) : int -> int -> int = "%mulint" (** Integer multiplication. *) external ( / ) : int -> int -> int = "%divint" * Integer division . Raise [ Division_by_zero ] if the second argument is 0 . Integer division rounds the real quotient of its arguments towards zero . More precisely , if [ x > = 0 ] and [ y > 0 ] , [ x / y ] is the greatest integer less than or equal to the real quotient of [ x ] by [ y ] . Moreover , [ ( -x ) / y = x / ( -y ) = -(x / y ) ] . Raise [Division_by_zero] if the second argument is 0. Integer division rounds the real quotient of its arguments towards zero. More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer less than or equal to the real quotient of [x] by [y]. Moreover, [(-x) / y = x / (-y) = -(x / y)]. *) external ( mod ) : int -> int -> int = "%modint" * Integer remainder . If [ y ] is not zero , the result of [ x mod y ] satisfies the following properties : [ x = ( x / y ) * y + x mod y ] and [ ) < = abs(y)-1 ] . If [ y = 0 ] , [ x mod y ] raises [ Division_by_zero ] . Notice that [ x mod y ] is nonpositive if and only if [ x < 0 ] . Raise [ Division_by_zero ] if [ y ] is zero . of [x mod y] satisfies the following properties: [x = (x / y) * y + x mod y] and [abs(x mod y) <= abs(y)-1]. If [y = 0], [x mod y] raises [Division_by_zero]. Notice that [x mod y] is nonpositive if and only if [x < 0]. Raise [Division_by_zero] if [y] is zero. *) val abs : int -> int (** Return the absolute value of the argument. Note that this may be negative if the argument is [min_int]. *) val max_int : int (** The greatest representable integer. *) val min_int : int (** The smallest representable integer. *) * { 7 Bitwise operations } external ( land ) : int -> int -> int = "%andint" (** Bitwise logical and. *) external ( lor ) : int -> int -> int = "%orint" (** Bitwise logical or. *) external ( lxor ) : int -> int -> int = "%xorint" (** Bitwise logical exclusive or. *) val lnot : int -> int (** Bitwise logical negation. *) external ( lsl ) : int -> int -> int = "%lslint" * [ n lsl m ] shifts [ n ] to the left by [ m ] bits . The result is unspecified if [ m < 0 ] or [ m > = bitsize ] , where [ bitsize ] is [ 32 ] on a 32 - bit platform and [ 64 ] on a 64 - bit platform . The result is unspecified if [m < 0] or [m >= bitsize], where [bitsize] is [32] on a 32-bit platform and [64] on a 64-bit platform. *) external ( lsr ) : int -> int -> int = "%lsrint" * [ n lsr m ] shifts [ n ] to the right by [ m ] bits . This is a logical shift : zeroes are inserted regardless of the sign of [ n ] . The result is unspecified if [ m < 0 ] or [ m > = bitsize ] . This is a logical shift: zeroes are inserted regardless of the sign of [n]. The result is unspecified if [m < 0] or [m >= bitsize]. *) external ( asr ) : int -> int -> int = "%asrint" (** [n asr m] shifts [n] to the right by [m] bits. This is an arithmetic shift: the sign bit of [n] is replicated. The result is unspecified if [m < 0] or [m >= bitsize]. *) * { 6 Floating - point arithmetic } 's floating - point numbers follow the IEEE 754 standard , using double precision ( 64 bits ) numbers . Floating - point operations never raise an exception on overflow , underflow , division by zero , etc . Instead , special IEEE numbers are returned as appropriate , such as [ infinity ] for [ 1.0 /. 0.0 ] , [ neg_infinity ] for [ -1.0 /. 0.0 ] , and [ ] ( ` ` not a number '' ) for [ 0.0 /. 0.0 ] . These special numbers then propagate through floating - point computations as expected : for instance , [ 1.0 /. infinity ] is [ 0.0 ] , and any operation with [ ] as argument returns [ nan ] as result . Caml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as [infinity] for [1.0 /. 0.0], [neg_infinity] for [-1.0 /. 0.0], and [nan] (``not a number'') for [0.0 /. 0.0]. These special numbers then propagate through floating-point computations as expected: for instance, [1.0 /. infinity] is [0.0], and any operation with [nan] as argument returns [nan] as result. *) external ( ~-. ) : float -> float = "%negfloat" (** Unary negation. You can also write [-.e] instead of [~-.e]. *) external ( +. ) : float -> float -> float = "%addfloat" (** Floating-point addition *) external ( -. ) : float -> float -> float = "%subfloat" (** Floating-point subtraction *) external ( *. ) : float -> float -> float = "%mulfloat" (** Floating-point multiplication *) external ( /. ) : float -> float -> float = "%divfloat" (** Floating-point division. *) external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float" (** Exponentiation *) external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float" (** Square root *) external exp : float -> float = "caml_exp_float" "exp" "float" (** Exponential. *) external log : float -> float = "caml_log_float" "log" "float" (** Natural logarithm. *) external log10 : float -> float = "caml_log10_float" "log10" "float" (** Base 10 logarithm. *) external cos : float -> float = "caml_cos_float" "cos" "float" (** See {!Pervasives.atan2}. *) external sin : float -> float = "caml_sin_float" "sin" "float" (** See {!Pervasives.atan2}. *) external tan : float -> float = "caml_tan_float" "tan" "float" (** See {!Pervasives.atan2}. *) external acos : float -> float = "caml_acos_float" "acos" "float" (** See {!Pervasives.atan2}. *) external asin : float -> float = "caml_asin_float" "asin" "float" (** See {!Pervasives.atan2}. *) external atan : float -> float = "caml_atan_float" "atan" "float" (** See {!Pervasives.atan2}. *) external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float" (** The usual trigonometric functions. *) external cosh : float -> float = "caml_cosh_float" "cosh" "float" (** See {!Pervasives.tanh}. *) external sinh : float -> float = "caml_sinh_float" "sinh" "float" (** See {!Pervasives.tanh}. *) external tanh : float -> float = "caml_tanh_float" "tanh" "float" (** The usual hyperbolic trigonometric functions. *) external ceil : float -> float = "caml_ceil_float" "ceil" "float" * See { ! Pervasives.floor } . external floor : float -> float = "caml_floor_float" "floor" "float" (** Round the given float to an integer value. [floor f] returns the greatest integer value less than or equal to [f]. [ceil f] returns the least integer value greater than or equal to [f]. *) external abs_float : float -> float = "%absfloat" (** Return the absolute value of the argument. *) external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float" * [ mod_float a b ] returns the remainder of [ a ] with respect to [ b ] . The returned value is [ a - . n * . b ] , where [ n ] is the quotient [ a /. b ] rounded towards zero to an integer . [b]. The returned value is [a -. n *. b], where [n] is the quotient [a /. b] rounded towards zero to an integer. *) external frexp : float -> float * int = "caml_frexp_float" * [ frexp f ] returns the pair of the significant and the exponent of [ f ] . When [ f ] is zero , the significant [ x ] and the exponent [ n ] of [ f ] are equal to zero . When [ f ] is non - zero , they are defined by [ f = x * . 2 * * n ] and [ 0.5 < = x < 1.0 ] . and the exponent of [f]. When [f] is zero, the significant [x] and the exponent [n] of [f] are equal to zero. When [f] is non-zero, they are defined by [f = x *. 2 ** n] and [0.5 <= x < 1.0]. *) external ldexp : float -> int -> float = "caml_ldexp_float" * [ ldexp x n ] returns [ x * . 2 * * n ] . external modf : float -> float * float = "caml_modf_float" (** [modf f] returns the pair of the fractional and integral part of [f]. *) external float : int -> float = "%floatofint" (** Same as {!Pervasives.float_of_int}. *) external float_of_int : int -> float = "%floatofint" (** Convert an integer to floating-point. *) external truncate : float -> int = "%intoffloat" (** Same as {!Pervasives.int_of_float}. *) external int_of_float : float -> int = "%intoffloat" * the given floating - point number to an integer . The result is unspecified if the argument is [ nan ] or falls outside the range of representable integers . The result is unspecified if the argument is [nan] or falls outside the range of representable integers. *) val infinity : float (** Positive infinity. *) val neg_infinity : float (** Negative infinity. *) val nan : float * A special floating - point value denoting the result of an undefined operation such as [ 0.0 /. 0.0 ] . Stands for ` ` not a number '' . Any floating - point operation with [ ] as argument returns [ nan ] as result . As for floating - point comparisons , [ =] , [ < ] , [ < =] , [ > ] and [ > =] return [ false ] and [ < > ] returns [ true ] if one or both of their arguments is [ nan ] . undefined operation such as [0.0 /. 0.0]. Stands for ``not a number''. Any floating-point operation with [nan] as argument returns [nan] as result. As for floating-point comparisons, [=], [<], [<=], [>] and [>=] return [false] and [<>] returns [true] if one or both of their arguments is [nan]. *) val max_float : float (** The largest positive finite value of type [float]. *) val min_float : float * The smallest positive , non - zero , non - denormalized value of type [ float ] . val epsilon_float : float * The smallest positive float [ x ] such that [ 1.0 + . x < > 1.0 ] . type fpclass = FP_normal (** Normal number, none of the below *) * Number very close to 0.0 , has reduced precision * Number is 0.0 or -0.0 | FP_infinite (** Number is positive or negative infinity *) | FP_nan (** Not a number: result of an undefined operation *) * The five classes of floating - point numbers , as determined by the { ! } function . the {!Pervasives.classify_float} function. *) external classify_float : float -> fpclass = "caml_classify_float" * Return the class of the given floating - point number : normal , subnormal , zero , infinite , or not a number . normal, subnormal, zero, infinite, or not a number. *) * { 6 String operations } More string operations are provided in module { ! String } . More string operations are provided in module {!String}. *) val ( ^ ) : string -> string -> string (** String concatenation. *) * { 6 Character operations } More character operations are provided in module { ! } . More character operations are provided in module {!Char}. *) external int_of_char : char -> int = "%identity" (** Return the ASCII code of the argument. *) val char_of_int : int -> char (** Return the character with the given ASCII code. Raise [Invalid_argument "char_of_int"] if the argument is outside the range 0--255. *) * { 6 Unit operations } external ignore : 'a -> unit = "%ignore" (** Discard the value of its argument and return [()]. For instance, [ignore(f x)] discards the result of the side-effecting function [f]. It is equivalent to [f x; ()], except that the latter may generate a compiler warning; writing [ignore(f x)] instead avoids the warning. *) * { 6 String conversion functions } val string_of_bool : bool -> string (** Return the string representation of a boolean. *) val bool_of_string : string -> bool (** Convert the given string to a boolean. Raise [Invalid_argument "bool_of_string"] if the string is not ["true"] or ["false"]. *) val string_of_int : int -> string (** Return the string representation of an integer, in decimal. *) external int_of_string : string -> int = "caml_int_of_string" * Convert the given string to an integer . The string is read in decimal ( by default ) or in hexadecimal ( if it begins with [ 0x ] or [ 0X ] ) , octal ( if it begins with [ 0o ] or [ 0O ] ) , or binary ( if it begins with [ 0b ] or [ ] ) . Raise [ Failure " int_of_string " ] if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ int ] . The string is read in decimal (by default) or in hexadecimal (if it begins with [0x] or [0X]), octal (if it begins with [0o] or [0O]), or binary (if it begins with [0b] or [0B]). Raise [Failure "int_of_string"] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int]. *) val string_of_float : float -> string (** Return the string representation of a floating-point number. *) external float_of_string : string -> float = "caml_float_of_string" (** Convert the given string to a float. Raise [Failure "float_of_string"] if the given string is not a valid representation of a float. *) * { 6 Pair operations } external fst : 'a * 'b -> 'a = "%field0" * Return the first component of a pair . external snd : 'a * 'b -> 'b = "%field1" * Return the second component of a pair . * { 6 List operations } More list operations are provided in module { ! List } . More list operations are provided in module {!List}. *) val ( @ ) : 'a list -> 'a list -> 'a list (** List concatenation. *) * { 6 Input / output } type in_channel (** The type of input channel. *) type out_channel (** The type of output channel. *) val stdin : in_channel (** The standard input for the process. *) val stdout : out_channel (** The standard output for the process. *) val stderr : out_channel (** The standard error ouput for the process. *) * { 7 Output functions on standard output } val print_char : char -> unit (** Print a character on standard output. *) val print_string : string -> unit (** Print a string on standard output. *) val print_int : int -> unit (** Print an integer, in decimal, on standard output. *) val print_float : float -> unit (** Print a floating-point number, in decimal, on standard output. *) val print_endline : string -> unit (** Print a string, followed by a newline character, on standard output and flush standard output. *) val print_newline : unit -> unit (** Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. *) * { 7 Output functions on standard error } val prerr_char : char -> unit (** Print a character on standard error. *) val prerr_string : string -> unit (** Print a string on standard error. *) val prerr_int : int -> unit (** Print an integer, in decimal, on standard error. *) val prerr_float : float -> unit (** Print a floating-point number, in decimal, on standard error. *) val prerr_endline : string -> unit (** Print a string, followed by a newline character on standard error and flush standard error. *) val prerr_newline : unit -> unit (** Print a newline character on standard error, and flush standard error. *) * { 7 Input functions on standard input } val read_line : unit -> string (** Flush standard output, then read characters from standard input until a newline character is encountered. Return the string of all characters read, without the newline character at the end. *) val read_int : unit -> int * Flush standard output , then read one line from standard input and convert it to an integer . Raise [ Failure " int_of_string " ] if the line read is not a valid representation of an integer . and convert it to an integer. Raise [Failure "int_of_string"] if the line read is not a valid representation of an integer. *) val read_float : unit -> float * Flush standard output , then read one line from standard input and convert it to a floating - point number . The result is unspecified if the line read is not a valid representation of a floating - point number . and convert it to a floating-point number. The result is unspecified if the line read is not a valid representation of a floating-point number. *) * { 7 General output functions } type open_flag = Open_rdonly (** open for reading. *) | Open_wronly (** open for writing. *) | Open_append (** open for appending: always write at end of file. *) | Open_creat (** create the file if it does not exist. *) | Open_trunc (** empty the file if it already exists. *) | Open_excl (** fail if Open_creat and the file already exists. *) | Open_binary (** open in binary mode (no conversion). *) | Open_text (** open in text mode (may perform conversions). *) | Open_nonblock (** open in non-blocking mode. *) * Opening modes for { ! } and { ! } . {!Pervasives.open_in_gen}. *) val open_out : string -> out_channel * Open the named file for writing , and return a new output channel on that file , positionned at the beginning of the file . The file is truncated to zero length if it already exists . It is created if it does not already exists . Raise [ Sys_error ] if the file could not be opened . on that file, positionned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. Raise [Sys_error] if the file could not be opened. *) val open_out_bin : string -> out_channel * Same as { ! Pervasives.open_out } , but the file is opened in binary mode , so that no translation takes place during writes . On operating systems that do not distinguish between text mode and binary mode , this function behaves like { ! Pervasives.open_out } . so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like {!Pervasives.open_out}. *) val open_out_gen : open_flag list -> int -> string -> out_channel * [ open_out_gen mode perm filename ] opens the named file for writing , as described above . The extra argument [ mode ] specify the opening mode . The extra argument [ perm ] specifies the file permissions , in case the file must be created . { ! Pervasives.open_out } and { ! Pervasives.open_out_bin } are special cases of this function . as described above. The extra argument [mode] specify the opening mode. The extra argument [perm] specifies the file permissions, in case the file must be created. {!Pervasives.open_out} and {!Pervasives.open_out_bin} are special cases of this function. *) val flush : out_channel -> unit (** Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. *) val flush_all : unit -> unit (** Flush all open output channels; ignore errors. *) val output_char : out_channel -> char -> unit (** Write the character on the given output channel. *) val output_string : out_channel -> string -> unit (** Write the string on the given output channel. *) val output : out_channel -> string -> int -> int -> unit * [ output oc buf pos len ] writes [ len ] characters from string [ buf ] , starting at offset [ pos ] , to the given output channel [ oc ] . Raise [ Invalid_argument " output " ] if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . starting at offset [pos], to the given output channel [oc]. Raise [Invalid_argument "output"] if [pos] and [len] do not designate a valid substring of [buf]. *) val output_byte : out_channel -> int -> unit * Write one 8 - bit integer ( as the single character with that code ) on the given output channel . The given integer is taken modulo 256 . on the given output channel. The given integer is taken modulo 256. *) val output_binary_int : out_channel -> int -> unit * Write one integer in binary format ( 4 bytes , big - endian ) on the given output channel . The given integer is taken modulo 2{^32 } . The only reliable way to read it back is through the { ! Pervasives.input_binary_int } function . The format is compatible across all machines for a given version of . on the given output channel. The given integer is taken modulo 2{^32}. The only reliable way to read it back is through the {!Pervasives.input_binary_int} function. The format is compatible across all machines for a given version of Objective Caml. *) val output_value : out_channel -> 'a -> unit (** Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function {!Pervasives.input_value}. See the description of module {!Marshal} for more information. {!Pervasives.output_value} is equivalent to {!Marshal.to_channel} with an empty list of flags. *) val seek_out : out_channel -> int -> unit * [ seek_out ] sets the current writing position to [ pos ] for channel [ chan ] . This works only for regular files . On files of other kinds ( such as terminals , pipes and sockets ) , the behavior is unspecified . for channel [chan]. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. *) val pos_out : out_channel -> int (** Return the current writing position for the given channel. Does not work on channels opened with the [Open_append] flag (returns unspecified results). *) val out_channel_length : out_channel -> int (** Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. *) val close_out : out_channel -> unit * Close the given channel , flushing all buffered write operations . Output functions raise a [ Sys_error ] exception when they are applied to a closed output channel , except [ close_out ] and [ flush ] , which do nothing when applied to an already closed channel . Note that [ close_out ] may raise [ ] if the operating system signals an error when flushing or closing . Output functions raise a [Sys_error] exception when they are applied to a closed output channel, except [close_out] and [flush], which do nothing when applied to an already closed channel. Note that [close_out] may raise [Sys_error] if the operating system signals an error when flushing or closing. *) val close_out_noerr : out_channel -> unit (** Same as [close_out], but ignore all errors. *) val set_binary_mode_out : out_channel -> bool -> unit * [ set_binary_mode_out oc true ] sets the channel [ oc ] to binary mode : no translations take place during output . [ set_binary_mode_out oc false ] sets the channel [ oc ] to text mode : depending on the operating system , some translations may take place during output . For instance , under Windows , end - of - lines will be translated from [ \n ] to [ \r\n ] . This function has no effect under operating systems that do not distinguish between text mode and binary mode . mode: no translations take place during output. [set_binary_mode_out oc false] sets the channel [oc] to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from [\n] to [\r\n]. This function has no effect under operating systems that do not distinguish between text mode and binary mode. *) * { 7 General input functions } val open_in : string -> in_channel (** Open the named file for reading, and return a new input channel on that file, positionned at the beginning of the file. Raise [Sys_error] if the file could not be opened. *) val open_in_bin : string -> in_channel (** Same as {!Pervasives.open_in}, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like {!Pervasives.open_in}. *) val open_in_gen : open_flag list -> int -> string -> in_channel * [ open_in mode perm filename ] opens the named file for reading , as described above . The extra arguments [ mode ] and [ perm ] specify the opening mode and file permissions . { ! Pervasives.open_in } and { ! Pervasives.open_in_bin } are special cases of this function . as described above. The extra arguments [mode] and [perm] specify the opening mode and file permissions. {!Pervasives.open_in} and {!Pervasives.open_in_bin} are special cases of this function. *) val input_char : in_channel -> char * Read one character from the given input channel . Raise [ End_of_file ] if there are no more characters to read . Raise [End_of_file] if there are no more characters to read. *) val input_line : in_channel -> string (** Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. Raise [End_of_file] if the end of the file is reached at the beginning of line. *) val input : in_channel -> string -> int -> int -> int * [ input ic buf pos len ] reads up to [ len ] characters from the given channel [ ic ] , storing them in string [ buf ] , starting at character number [ pos ] . It returns the actual number of characters read , between 0 and [ len ] ( inclusive ) . A return value of 0 means that the end of file was reached . A return value between 0 and [ len ] exclusive means that not all requested [ len ] characters were read , either because no more characters were available at that time , or because the implementation found it convenient to do a partial read ; [ input ] must be called again to read the remaining characters , if desired . ( See also { ! Pervasives.really_input } for reading exactly [ len ] characters . ) Exception [ Invalid_argument " input " ] is raised if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . the given channel [ic], storing them in string [buf], starting at character number [pos]. It returns the actual number of characters read, between 0 and [len] (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and [len] exclusive means that not all requested [len] characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; [input] must be called again to read the remaining characters, if desired. (See also {!Pervasives.really_input} for reading exactly [len] characters.) Exception [Invalid_argument "input"] is raised if [pos] and [len] do not designate a valid substring of [buf]. *) val really_input : in_channel -> string -> int -> int -> unit * [ really_input ic buf pos len ] reads [ len ] characters from channel [ ic ] , storing them in string [ buf ] , starting at character number [ pos ] . Raise [ End_of_file ] if the end of file is reached before [ len ] characters have been read . Raise [ Invalid_argument " really_input " ] if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . storing them in string [buf], starting at character number [pos]. Raise [End_of_file] if the end of file is reached before [len] characters have been read. Raise [Invalid_argument "really_input"] if [pos] and [len] do not designate a valid substring of [buf]. *) val input_byte : in_channel -> int * Same as { ! Pervasives.input_char } , but return the 8 - bit integer representing the character . Raise [ End_of_file ] if an end of file was reached . the character. Raise [End_of_file] if an end of file was reached. *) val input_binary_int : in_channel -> int * Read an integer encoded in binary format ( 4 bytes , big - endian ) from the given input channel . See { ! Pervasives.output_binary_int } . Raise [ End_of_file ] if an end of file was reached while reading the integer . from the given input channel. See {!Pervasives.output_binary_int}. Raise [End_of_file] if an end of file was reached while reading the integer. *) val input_value : in_channel -> 'a (** Read the representation of a structured value, as produced by {!Pervasives.output_value}, and return the corresponding value. This function is identical to {!Marshal.from_channel}; see the description of module {!Marshal} for more information, in particular concerning the lack of type safety. *) val seek_in : in_channel -> int -> unit (** [seek_in chan pos] sets the current reading position to [pos] for channel [chan]. This works only for regular files. On files of other kinds, the behavior is unspecified. *) val pos_in : in_channel -> int (** Return the current reading position for the given channel. *) val in_channel_length : in_channel -> int (** Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. *) val close_in : in_channel -> unit * Close the given channel . Input functions raise a [ Sys_error ] exception when they are applied to a closed input channel , except [ close_in ] , which does nothing when applied to an already closed channel . Note that [ close_in ] may raise [ ] if the operating system signals an error . exception when they are applied to a closed input channel, except [close_in], which does nothing when applied to an already closed channel. Note that [close_in] may raise [Sys_error] if the operating system signals an error. *) val close_in_noerr : in_channel -> unit (** Same as [close_in], but ignore all errors. *) val set_binary_mode_in : in_channel -> bool -> unit * [ set_binary_mode_in ic true ] sets the channel [ ic ] to binary mode : no translations take place during input . [ set_binary_mode_out ic false ] sets the channel [ ic ] to text mode : depending on the operating system , some translations may take place during input . For instance , under Windows , end - of - lines will be translated from [ \r\n ] to [ \n ] . This function has no effect under operating systems that do not distinguish between text mode and binary mode . mode: no translations take place during input. [set_binary_mode_out ic false] sets the channel [ic] to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from [\r\n] to [\n]. This function has no effect under operating systems that do not distinguish between text mode and binary mode. *) * { 7 Operations on large files } module LargeFile : sig val seek_out : out_channel -> int64 -> unit val pos_out : out_channel -> int64 val out_channel_length : out_channel -> int64 val seek_in : in_channel -> int64 -> unit val pos_in : in_channel -> int64 val in_channel_length : in_channel -> int64 end * Operations on large files . This sub - module provides 64 - bit variants of the channel functions that manipulate file positions and file sizes . By representing positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of regular integers ( type [ int ] ) , these alternate functions allow operating on files whose sizes are greater than [ max_int ] . This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type [int64]) instead of regular integers (type [int]), these alternate functions allow operating on files whose sizes are greater than [max_int]. *) (** {6 References} *) type 'a ref = { mutable contents : 'a } (** The type of references (mutable indirection cells) containing a value of type ['a]. *) external ref : 'a -> 'a ref = "%makemutable" (** Return a fresh reference containing the given value. *) external ( ! ) : 'a ref -> 'a = "%field0" (** [!r] returns the current contents of reference [r]. Equivalent to [fun r -> r.contents]. *) external ( := ) : 'a ref -> 'a -> unit = "%setfield0" (** [r := a] stores the value of [a] in reference [r]. Equivalent to [fun r v -> r.contents <- v]. *) external incr : int ref -> unit = "%incr" (** Increment the integer contained in the given reference. Equivalent to [fun r -> r := succ !r]. *) external decr : int ref -> unit = "%decr" (** Decrement the integer contained in the given reference. Equivalent to [fun r -> r := pred !r]. *) * { 6 Operations on format strings } (** See modules {!Printf} and {!Scanf} for more operations on format strings. *) type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 * Simplified type for format strings , included for backward compatibility with earlier releases of [ ' a ] is the type of the parameters of the format , [ ' c ] is the result type for the " printf"-style function , and [ ' b ] is the type of the first argument given to [ % a ] and [ % t ] printing functions . with earlier releases of Objective Caml. ['a] is the type of the parameters of the format, ['c] is the result type for the "printf"-style function, and ['b] is the type of the first argument given to [%a] and [%t] printing functions. *) val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string (** Converts a format string into a string. *) external format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity" (** [format_of_string s] returns a format string read from the string literal [s]. *) val ( ^^ ) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('f, 'b, 'c, 'e, 'g, 'h) format6 -> ('a, 'b, 'c, 'd, 'g, 'h) format6 (** [f1 ^^ f2] catenates formats [f1] and [f2]. The result is a format that accepts arguments from [f1], then arguments from [f2]. *) * { 6 Program termination } val exit : int -> 'a * Terminate the process , returning the given status code to the operating system : usually 0 to indicate no errors , and a small positive integer to indicate failure . All open output channels are flushed with flush_all . An implicit [ exit 0 ] is performed each time a program terminates normally . An implicit [ exit 2 ] is performed if the program terminates early because of an uncaught exception . to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with flush_all. An implicit [exit 0] is performed each time a program terminates normally. An implicit [exit 2] is performed if the program terminates early because of an uncaught exception. *) val at_exit : (unit -> unit) -> unit * Register the given function to be called at program termination time . The functions registered with [ at_exit ] will be called when the program executes { ! Pervasives.exit } , or terminates , either normally or because of an uncaught exception . The functions are called in ` ` last in , first out '' order : the function most recently added with [ at_exit ] is called first . termination time. The functions registered with [at_exit] will be called when the program executes {!Pervasives.exit}, or terminates, either normally or because of an uncaught exception. The functions are called in ``last in, first out'' order: the function most recently added with [at_exit] is called first. *) (**/**) * { 6 For system use only , not for the casual user } val valid_float_lexem : string -> string val unsafe_really_input : in_channel -> string -> int -> int -> unit val do_at_exit : unit -> unit
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/stdlib/pervasives.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* * The initially opened module. This module provides the basic operations over the built-in types (numbers, booleans, strings, exceptions, references, lists, arrays, input-output channels, ...) This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by [Pervasives]. * Raise the given exception value * Raise exception [Invalid_argument] with the given string. * Raise exception [Failure] with the given string. * The [Exit] exception is not raised by any library function. It is provided for use in your programs. * Negation of {!Pervasives.(=)}. * See {!Pervasives.(>=)}. * See {!Pervasives.(>=)}. * See {!Pervasives.(>=)}. * Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with [(=)]. As in the case of [(=)], mutable structures are compared by contents. Comparison between functional values raises [Invalid_argument]. Comparison between cyclic structures does not terminate. * [e1 == e2] tests for physical equality of [e1] and [e2]. On integers and characters, physical equality is identical to structural equality. On mutable structures, [e1 == e2] is true if and only if physical modification of [e1] also affects [e2]. On non-mutable structures, the behavior of [(==)] is implementation-dependent; however, it is guaranteed that [e1 == e2] implies [compare e1 e2 = 0]. * Negation of {!Pervasives.(==)}. * The boolean negation. * @deprecated {!Pervasives.(&&)} should be used instead. * Unary negation. You can also write [-e] instead of [~-e]. * [succ x] is [x+1]. * [pred x] is [x-1]. * Integer addition. * Integer subtraction. * Integer multiplication. * Return the absolute value of the argument. Note that this may be negative if the argument is [min_int]. * The greatest representable integer. * The smallest representable integer. * Bitwise logical and. * Bitwise logical or. * Bitwise logical exclusive or. * Bitwise logical negation. * [n asr m] shifts [n] to the right by [m] bits. This is an arithmetic shift: the sign bit of [n] is replicated. The result is unspecified if [m < 0] or [m >= bitsize]. * Unary negation. You can also write [-.e] instead of [~-.e]. * Floating-point addition * Floating-point subtraction * Floating-point multiplication * Floating-point division. * Exponentiation * Square root * Exponential. * Natural logarithm. * Base 10 logarithm. * See {!Pervasives.atan2}. * See {!Pervasives.atan2}. * See {!Pervasives.atan2}. * See {!Pervasives.atan2}. * See {!Pervasives.atan2}. * See {!Pervasives.atan2}. * The usual trigonometric functions. * See {!Pervasives.tanh}. * See {!Pervasives.tanh}. * The usual hyperbolic trigonometric functions. * Round the given float to an integer value. [floor f] returns the greatest integer value less than or equal to [f]. [ceil f] returns the least integer value greater than or equal to [f]. * Return the absolute value of the argument. * [modf f] returns the pair of the fractional and integral part of [f]. * Same as {!Pervasives.float_of_int}. * Convert an integer to floating-point. * Same as {!Pervasives.int_of_float}. * Positive infinity. * Negative infinity. * The largest positive finite value of type [float]. * Normal number, none of the below * Number is positive or negative infinity * Not a number: result of an undefined operation * String concatenation. * Return the ASCII code of the argument. * Return the character with the given ASCII code. Raise [Invalid_argument "char_of_int"] if the argument is outside the range 0--255. * Discard the value of its argument and return [()]. For instance, [ignore(f x)] discards the result of the side-effecting function [f]. It is equivalent to [f x; ()], except that the latter may generate a compiler warning; writing [ignore(f x)] instead avoids the warning. * Return the string representation of a boolean. * Convert the given string to a boolean. Raise [Invalid_argument "bool_of_string"] if the string is not ["true"] or ["false"]. * Return the string representation of an integer, in decimal. * Return the string representation of a floating-point number. * Convert the given string to a float. Raise [Failure "float_of_string"] if the given string is not a valid representation of a float. * List concatenation. * The type of input channel. * The type of output channel. * The standard input for the process. * The standard output for the process. * The standard error ouput for the process. * Print a character on standard output. * Print a string on standard output. * Print an integer, in decimal, on standard output. * Print a floating-point number, in decimal, on standard output. * Print a string, followed by a newline character, on standard output and flush standard output. * Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. * Print a character on standard error. * Print a string on standard error. * Print an integer, in decimal, on standard error. * Print a floating-point number, in decimal, on standard error. * Print a string, followed by a newline character on standard error and flush standard error. * Print a newline character on standard error, and flush standard error. * Flush standard output, then read characters from standard input until a newline character is encountered. Return the string of all characters read, without the newline character at the end. * open for reading. * open for writing. * open for appending: always write at end of file. * create the file if it does not exist. * empty the file if it already exists. * fail if Open_creat and the file already exists. * open in binary mode (no conversion). * open in text mode (may perform conversions). * open in non-blocking mode. * Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. * Flush all open output channels; ignore errors. * Write the character on the given output channel. * Write the string on the given output channel. * Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function {!Pervasives.input_value}. See the description of module {!Marshal} for more information. {!Pervasives.output_value} is equivalent to {!Marshal.to_channel} with an empty list of flags. * Return the current writing position for the given channel. Does not work on channels opened with the [Open_append] flag (returns unspecified results). * Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. * Same as [close_out], but ignore all errors. * Open the named file for reading, and return a new input channel on that file, positionned at the beginning of the file. Raise [Sys_error] if the file could not be opened. * Same as {!Pervasives.open_in}, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like {!Pervasives.open_in}. * Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. Raise [End_of_file] if the end of the file is reached at the beginning of line. * Read the representation of a structured value, as produced by {!Pervasives.output_value}, and return the corresponding value. This function is identical to {!Marshal.from_channel}; see the description of module {!Marshal} for more information, in particular concerning the lack of type safety. * [seek_in chan pos] sets the current reading position to [pos] for channel [chan]. This works only for regular files. On files of other kinds, the behavior is unspecified. * Return the current reading position for the given channel. * Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. * Same as [close_in], but ignore all errors. * {6 References} * The type of references (mutable indirection cells) containing a value of type ['a]. * Return a fresh reference containing the given value. * [!r] returns the current contents of reference [r]. Equivalent to [fun r -> r.contents]. * [r := a] stores the value of [a] in reference [r]. Equivalent to [fun r v -> r.contents <- v]. * Increment the integer contained in the given reference. Equivalent to [fun r -> r := succ !r]. * Decrement the integer contained in the given reference. Equivalent to [fun r -> r := pred !r]. * See modules {!Printf} and {!Scanf} for more operations on format strings. * Converts a format string into a string. * [format_of_string s] returns a format string read from the string literal [s]. * [f1 ^^ f2] catenates formats [f1] and [f2]. The result is a format that accepts arguments from [f1], then arguments from [f2]. */*
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ I d : pervasives.mli , v 1.108 2007/02/21 14:15:19 xleroy Exp $ * { 6 Exceptions } external raise : exn -> 'a = "%raise" val invalid_arg : string -> 'a val failwith : string -> 'a exception Exit * { 6 Comparisons } external ( = ) : 'a -> 'a -> bool = "%equal" * [ e1 = e2 ] tests for structural equality of [ e1 ] and [ e2 ] . Mutable structures ( e.g. references and arrays ) are equal if and only if their current contents are structurally equal , even if the two mutable objects are not the same physical object . Equality between functional values raises [ Invalid_argument ] . Equality between cyclic data structures does not terminate . Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises [Invalid_argument]. Equality between cyclic data structures does not terminate. *) external ( <> ) : 'a -> 'a -> bool = "%notequal" external ( < ) : 'a -> 'a -> bool = "%lessthan" external ( > ) : 'a -> 'a -> bool = "%greaterthan" external ( <= ) : 'a -> 'a -> bool = "%lessequal" external ( >= ) : 'a -> 'a -> bool = "%greaterequal" external compare : 'a -> 'a -> int = "%compare" * [ compare x y ] returns [ 0 ] if [ x ] is equal to [ y ] , a negative integer if [ x ] is less than [ y ] , and a positive integer if [ x ] is greater than [ y ] . The ordering implemented by [ compare ] is compatible with the comparison predicates [ =] , [ < ] and [ > ] defined above , with one difference on the treatment of the float value { ! } . Namely , the comparison predicates treat [ nan ] as different from any other float value , including itself ; while [ compare ] treats [ nan ] as equal to itself and less than any other float value . This treatment of ensures that [ compare ] defines a total ordering relation . [ compare ] applied to functional values may raise [ Invalid_argument ] . [ compare ] applied to cyclic structures may not terminate . The [ compare ] function can be used as the comparison function required by the { ! Set . Make } and { ! Map . Make } functors , as well as the { ! List.sort } and { ! Array.sort } functions . a negative integer if [x] is less than [y], and a positive integer if [x] is greater than [y]. The ordering implemented by [compare] is compatible with the comparison predicates [=], [<] and [>] defined above, with one difference on the treatment of the float value {!Pervasives.nan}. Namely, the comparison predicates treat [nan] as different from any other float value, including itself; while [compare] treats [nan] as equal to itself and less than any other float value. This treatment of [nan] ensures that [compare] defines a total ordering relation. [compare] applied to functional values may raise [Invalid_argument]. [compare] applied to cyclic structures may not terminate. The [compare] function can be used as the comparison function required by the {!Set.Make} and {!Map.Make} functors, as well as the {!List.sort} and {!Array.sort} functions. *) val min : 'a -> 'a -> 'a * Return the smaller of the two arguments . val max : 'a -> 'a -> 'a * Return the greater of the two arguments . external ( == ) : 'a -> 'a -> bool = "%eq" external ( != ) : 'a -> 'a -> bool = "%noteq" * { 6 Boolean operations } external not : bool -> bool = "%boolnot" external ( && ) : bool -> bool -> bool = "%sequand" * The boolean ` ` and '' . Evaluation is sequential , left - to - right : in [ e1 & & e2 ] , [ e1 ] is evaluated first , and if it returns [ false ] , [ e2 ] is not evaluated at all . in [e1 && e2], [e1] is evaluated first, and if it returns [false], [e2] is not evaluated at all. *) external ( & ) : bool -> bool -> bool = "%sequand" external ( || ) : bool -> bool -> bool = "%sequor" * The boolean ` ` or '' . Evaluation is sequential , left - to - right : in [ e1 || e2 ] , [ e1 ] is evaluated first , and if it returns [ true ] , [ e2 ] is not evaluated at all . in [e1 || e2], [e1] is evaluated first, and if it returns [true], [e2] is not evaluated at all. *) external ( or ) : bool -> bool -> bool = "%sequor" * @deprecated { ! ) } should be used instead . * { 6 Integer arithmetic } * Integers are 31 bits wide ( or 63 bits on 64 - bit processors ) . All operations are taken modulo 2{^31 } ( or 2{^63 } ) . They do not fail on overflow . All operations are taken modulo 2{^31} (or 2{^63}). They do not fail on overflow. *) external ( ~- ) : int -> int = "%negint" external succ : int -> int = "%succint" external pred : int -> int = "%predint" external ( + ) : int -> int -> int = "%addint" external ( - ) : int -> int -> int = "%subint" external ( * ) : int -> int -> int = "%mulint" external ( / ) : int -> int -> int = "%divint" * Integer division . Raise [ Division_by_zero ] if the second argument is 0 . Integer division rounds the real quotient of its arguments towards zero . More precisely , if [ x > = 0 ] and [ y > 0 ] , [ x / y ] is the greatest integer less than or equal to the real quotient of [ x ] by [ y ] . Moreover , [ ( -x ) / y = x / ( -y ) = -(x / y ) ] . Raise [Division_by_zero] if the second argument is 0. Integer division rounds the real quotient of its arguments towards zero. More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer less than or equal to the real quotient of [x] by [y]. Moreover, [(-x) / y = x / (-y) = -(x / y)]. *) external ( mod ) : int -> int -> int = "%modint" * Integer remainder . If [ y ] is not zero , the result of [ x mod y ] satisfies the following properties : [ x = ( x / y ) * y + x mod y ] and [ ) < = abs(y)-1 ] . If [ y = 0 ] , [ x mod y ] raises [ Division_by_zero ] . Notice that [ x mod y ] is nonpositive if and only if [ x < 0 ] . Raise [ Division_by_zero ] if [ y ] is zero . of [x mod y] satisfies the following properties: [x = (x / y) * y + x mod y] and [abs(x mod y) <= abs(y)-1]. If [y = 0], [x mod y] raises [Division_by_zero]. Notice that [x mod y] is nonpositive if and only if [x < 0]. Raise [Division_by_zero] if [y] is zero. *) val abs : int -> int val max_int : int val min_int : int * { 7 Bitwise operations } external ( land ) : int -> int -> int = "%andint" external ( lor ) : int -> int -> int = "%orint" external ( lxor ) : int -> int -> int = "%xorint" val lnot : int -> int external ( lsl ) : int -> int -> int = "%lslint" * [ n lsl m ] shifts [ n ] to the left by [ m ] bits . The result is unspecified if [ m < 0 ] or [ m > = bitsize ] , where [ bitsize ] is [ 32 ] on a 32 - bit platform and [ 64 ] on a 64 - bit platform . The result is unspecified if [m < 0] or [m >= bitsize], where [bitsize] is [32] on a 32-bit platform and [64] on a 64-bit platform. *) external ( lsr ) : int -> int -> int = "%lsrint" * [ n lsr m ] shifts [ n ] to the right by [ m ] bits . This is a logical shift : zeroes are inserted regardless of the sign of [ n ] . The result is unspecified if [ m < 0 ] or [ m > = bitsize ] . This is a logical shift: zeroes are inserted regardless of the sign of [n]. The result is unspecified if [m < 0] or [m >= bitsize]. *) external ( asr ) : int -> int -> int = "%asrint" * { 6 Floating - point arithmetic } 's floating - point numbers follow the IEEE 754 standard , using double precision ( 64 bits ) numbers . Floating - point operations never raise an exception on overflow , underflow , division by zero , etc . Instead , special IEEE numbers are returned as appropriate , such as [ infinity ] for [ 1.0 /. 0.0 ] , [ neg_infinity ] for [ -1.0 /. 0.0 ] , and [ ] ( ` ` not a number '' ) for [ 0.0 /. 0.0 ] . These special numbers then propagate through floating - point computations as expected : for instance , [ 1.0 /. infinity ] is [ 0.0 ] , and any operation with [ ] as argument returns [ nan ] as result . Caml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as [infinity] for [1.0 /. 0.0], [neg_infinity] for [-1.0 /. 0.0], and [nan] (``not a number'') for [0.0 /. 0.0]. These special numbers then propagate through floating-point computations as expected: for instance, [1.0 /. infinity] is [0.0], and any operation with [nan] as argument returns [nan] as result. *) external ( ~-. ) : float -> float = "%negfloat" external ( +. ) : float -> float -> float = "%addfloat" external ( -. ) : float -> float -> float = "%subfloat" external ( *. ) : float -> float -> float = "%mulfloat" external ( /. ) : float -> float -> float = "%divfloat" external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float" external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float" external exp : float -> float = "caml_exp_float" "exp" "float" external log : float -> float = "caml_log_float" "log" "float" external log10 : float -> float = "caml_log10_float" "log10" "float" external cos : float -> float = "caml_cos_float" "cos" "float" external sin : float -> float = "caml_sin_float" "sin" "float" external tan : float -> float = "caml_tan_float" "tan" "float" external acos : float -> float = "caml_acos_float" "acos" "float" external asin : float -> float = "caml_asin_float" "asin" "float" external atan : float -> float = "caml_atan_float" "atan" "float" external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float" external cosh : float -> float = "caml_cosh_float" "cosh" "float" external sinh : float -> float = "caml_sinh_float" "sinh" "float" external tanh : float -> float = "caml_tanh_float" "tanh" "float" external ceil : float -> float = "caml_ceil_float" "ceil" "float" * See { ! Pervasives.floor } . external floor : float -> float = "caml_floor_float" "floor" "float" external abs_float : float -> float = "%absfloat" external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float" * [ mod_float a b ] returns the remainder of [ a ] with respect to [ b ] . The returned value is [ a - . n * . b ] , where [ n ] is the quotient [ a /. b ] rounded towards zero to an integer . [b]. The returned value is [a -. n *. b], where [n] is the quotient [a /. b] rounded towards zero to an integer. *) external frexp : float -> float * int = "caml_frexp_float" * [ frexp f ] returns the pair of the significant and the exponent of [ f ] . When [ f ] is zero , the significant [ x ] and the exponent [ n ] of [ f ] are equal to zero . When [ f ] is non - zero , they are defined by [ f = x * . 2 * * n ] and [ 0.5 < = x < 1.0 ] . and the exponent of [f]. When [f] is zero, the significant [x] and the exponent [n] of [f] are equal to zero. When [f] is non-zero, they are defined by [f = x *. 2 ** n] and [0.5 <= x < 1.0]. *) external ldexp : float -> int -> float = "caml_ldexp_float" * [ ldexp x n ] returns [ x * . 2 * * n ] . external modf : float -> float * float = "caml_modf_float" external float : int -> float = "%floatofint" external float_of_int : int -> float = "%floatofint" external truncate : float -> int = "%intoffloat" external int_of_float : float -> int = "%intoffloat" * the given floating - point number to an integer . The result is unspecified if the argument is [ nan ] or falls outside the range of representable integers . The result is unspecified if the argument is [nan] or falls outside the range of representable integers. *) val infinity : float val neg_infinity : float val nan : float * A special floating - point value denoting the result of an undefined operation such as [ 0.0 /. 0.0 ] . Stands for ` ` not a number '' . Any floating - point operation with [ ] as argument returns [ nan ] as result . As for floating - point comparisons , [ =] , [ < ] , [ < =] , [ > ] and [ > =] return [ false ] and [ < > ] returns [ true ] if one or both of their arguments is [ nan ] . undefined operation such as [0.0 /. 0.0]. Stands for ``not a number''. Any floating-point operation with [nan] as argument returns [nan] as result. As for floating-point comparisons, [=], [<], [<=], [>] and [>=] return [false] and [<>] returns [true] if one or both of their arguments is [nan]. *) val max_float : float val min_float : float * The smallest positive , non - zero , non - denormalized value of type [ float ] . val epsilon_float : float * The smallest positive float [ x ] such that [ 1.0 + . x < > 1.0 ] . type fpclass = * Number very close to 0.0 , has reduced precision * Number is 0.0 or -0.0 * The five classes of floating - point numbers , as determined by the { ! } function . the {!Pervasives.classify_float} function. *) external classify_float : float -> fpclass = "caml_classify_float" * Return the class of the given floating - point number : normal , subnormal , zero , infinite , or not a number . normal, subnormal, zero, infinite, or not a number. *) * { 6 String operations } More string operations are provided in module { ! String } . More string operations are provided in module {!String}. *) val ( ^ ) : string -> string -> string * { 6 Character operations } More character operations are provided in module { ! } . More character operations are provided in module {!Char}. *) external int_of_char : char -> int = "%identity" val char_of_int : int -> char * { 6 Unit operations } external ignore : 'a -> unit = "%ignore" * { 6 String conversion functions } val string_of_bool : bool -> string val bool_of_string : string -> bool val string_of_int : int -> string external int_of_string : string -> int = "caml_int_of_string" * Convert the given string to an integer . The string is read in decimal ( by default ) or in hexadecimal ( if it begins with [ 0x ] or [ 0X ] ) , octal ( if it begins with [ 0o ] or [ 0O ] ) , or binary ( if it begins with [ 0b ] or [ ] ) . Raise [ Failure " int_of_string " ] if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ int ] . The string is read in decimal (by default) or in hexadecimal (if it begins with [0x] or [0X]), octal (if it begins with [0o] or [0O]), or binary (if it begins with [0b] or [0B]). Raise [Failure "int_of_string"] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int]. *) val string_of_float : float -> string external float_of_string : string -> float = "caml_float_of_string" * { 6 Pair operations } external fst : 'a * 'b -> 'a = "%field0" * Return the first component of a pair . external snd : 'a * 'b -> 'b = "%field1" * Return the second component of a pair . * { 6 List operations } More list operations are provided in module { ! List } . More list operations are provided in module {!List}. *) val ( @ ) : 'a list -> 'a list -> 'a list * { 6 Input / output } type in_channel type out_channel val stdin : in_channel val stdout : out_channel val stderr : out_channel * { 7 Output functions on standard output } val print_char : char -> unit val print_string : string -> unit val print_int : int -> unit val print_float : float -> unit val print_endline : string -> unit val print_newline : unit -> unit * { 7 Output functions on standard error } val prerr_char : char -> unit val prerr_string : string -> unit val prerr_int : int -> unit val prerr_float : float -> unit val prerr_endline : string -> unit val prerr_newline : unit -> unit * { 7 Input functions on standard input } val read_line : unit -> string val read_int : unit -> int * Flush standard output , then read one line from standard input and convert it to an integer . Raise [ Failure " int_of_string " ] if the line read is not a valid representation of an integer . and convert it to an integer. Raise [Failure "int_of_string"] if the line read is not a valid representation of an integer. *) val read_float : unit -> float * Flush standard output , then read one line from standard input and convert it to a floating - point number . The result is unspecified if the line read is not a valid representation of a floating - point number . and convert it to a floating-point number. The result is unspecified if the line read is not a valid representation of a floating-point number. *) * { 7 General output functions } type open_flag = * Opening modes for { ! } and { ! } . {!Pervasives.open_in_gen}. *) val open_out : string -> out_channel * Open the named file for writing , and return a new output channel on that file , positionned at the beginning of the file . The file is truncated to zero length if it already exists . It is created if it does not already exists . Raise [ Sys_error ] if the file could not be opened . on that file, positionned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. Raise [Sys_error] if the file could not be opened. *) val open_out_bin : string -> out_channel * Same as { ! Pervasives.open_out } , but the file is opened in binary mode , so that no translation takes place during writes . On operating systems that do not distinguish between text mode and binary mode , this function behaves like { ! Pervasives.open_out } . so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like {!Pervasives.open_out}. *) val open_out_gen : open_flag list -> int -> string -> out_channel * [ open_out_gen mode perm filename ] opens the named file for writing , as described above . The extra argument [ mode ] specify the opening mode . The extra argument [ perm ] specifies the file permissions , in case the file must be created . { ! Pervasives.open_out } and { ! Pervasives.open_out_bin } are special cases of this function . as described above. The extra argument [mode] specify the opening mode. The extra argument [perm] specifies the file permissions, in case the file must be created. {!Pervasives.open_out} and {!Pervasives.open_out_bin} are special cases of this function. *) val flush : out_channel -> unit val flush_all : unit -> unit val output_char : out_channel -> char -> unit val output_string : out_channel -> string -> unit val output : out_channel -> string -> int -> int -> unit * [ output oc buf pos len ] writes [ len ] characters from string [ buf ] , starting at offset [ pos ] , to the given output channel [ oc ] . Raise [ Invalid_argument " output " ] if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . starting at offset [pos], to the given output channel [oc]. Raise [Invalid_argument "output"] if [pos] and [len] do not designate a valid substring of [buf]. *) val output_byte : out_channel -> int -> unit * Write one 8 - bit integer ( as the single character with that code ) on the given output channel . The given integer is taken modulo 256 . on the given output channel. The given integer is taken modulo 256. *) val output_binary_int : out_channel -> int -> unit * Write one integer in binary format ( 4 bytes , big - endian ) on the given output channel . The given integer is taken modulo 2{^32 } . The only reliable way to read it back is through the { ! Pervasives.input_binary_int } function . The format is compatible across all machines for a given version of . on the given output channel. The given integer is taken modulo 2{^32}. The only reliable way to read it back is through the {!Pervasives.input_binary_int} function. The format is compatible across all machines for a given version of Objective Caml. *) val output_value : out_channel -> 'a -> unit val seek_out : out_channel -> int -> unit * [ seek_out ] sets the current writing position to [ pos ] for channel [ chan ] . This works only for regular files . On files of other kinds ( such as terminals , pipes and sockets ) , the behavior is unspecified . for channel [chan]. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. *) val pos_out : out_channel -> int val out_channel_length : out_channel -> int val close_out : out_channel -> unit * Close the given channel , flushing all buffered write operations . Output functions raise a [ Sys_error ] exception when they are applied to a closed output channel , except [ close_out ] and [ flush ] , which do nothing when applied to an already closed channel . Note that [ close_out ] may raise [ ] if the operating system signals an error when flushing or closing . Output functions raise a [Sys_error] exception when they are applied to a closed output channel, except [close_out] and [flush], which do nothing when applied to an already closed channel. Note that [close_out] may raise [Sys_error] if the operating system signals an error when flushing or closing. *) val close_out_noerr : out_channel -> unit val set_binary_mode_out : out_channel -> bool -> unit * [ set_binary_mode_out oc true ] sets the channel [ oc ] to binary mode : no translations take place during output . [ set_binary_mode_out oc false ] sets the channel [ oc ] to text mode : depending on the operating system , some translations may take place during output . For instance , under Windows , end - of - lines will be translated from [ \n ] to [ \r\n ] . This function has no effect under operating systems that do not distinguish between text mode and binary mode . mode: no translations take place during output. [set_binary_mode_out oc false] sets the channel [oc] to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from [\n] to [\r\n]. This function has no effect under operating systems that do not distinguish between text mode and binary mode. *) * { 7 General input functions } val open_in : string -> in_channel val open_in_bin : string -> in_channel val open_in_gen : open_flag list -> int -> string -> in_channel * [ open_in mode perm filename ] opens the named file for reading , as described above . The extra arguments [ mode ] and [ perm ] specify the opening mode and file permissions . { ! Pervasives.open_in } and { ! Pervasives.open_in_bin } are special cases of this function . as described above. The extra arguments [mode] and [perm] specify the opening mode and file permissions. {!Pervasives.open_in} and {!Pervasives.open_in_bin} are special cases of this function. *) val input_char : in_channel -> char * Read one character from the given input channel . Raise [ End_of_file ] if there are no more characters to read . Raise [End_of_file] if there are no more characters to read. *) val input_line : in_channel -> string val input : in_channel -> string -> int -> int -> int * [ input ic buf pos len ] reads up to [ len ] characters from the given channel [ ic ] , storing them in string [ buf ] , starting at character number [ pos ] . It returns the actual number of characters read , between 0 and [ len ] ( inclusive ) . A return value of 0 means that the end of file was reached . A return value between 0 and [ len ] exclusive means that not all requested [ len ] characters were read , either because no more characters were available at that time , or because the implementation found it convenient to do a partial read ; [ input ] must be called again to read the remaining characters , if desired . ( See also { ! Pervasives.really_input } for reading exactly [ len ] characters . ) Exception [ Invalid_argument " input " ] is raised if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . the given channel [ic], storing them in string [buf], starting at character number [pos]. It returns the actual number of characters read, between 0 and [len] (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and [len] exclusive means that not all requested [len] characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; [input] must be called again to read the remaining characters, if desired. (See also {!Pervasives.really_input} for reading exactly [len] characters.) Exception [Invalid_argument "input"] is raised if [pos] and [len] do not designate a valid substring of [buf]. *) val really_input : in_channel -> string -> int -> int -> unit * [ really_input ic buf pos len ] reads [ len ] characters from channel [ ic ] , storing them in string [ buf ] , starting at character number [ pos ] . Raise [ End_of_file ] if the end of file is reached before [ len ] characters have been read . Raise [ Invalid_argument " really_input " ] if [ pos ] and [ len ] do not designate a valid substring of [ buf ] . storing them in string [buf], starting at character number [pos]. Raise [End_of_file] if the end of file is reached before [len] characters have been read. Raise [Invalid_argument "really_input"] if [pos] and [len] do not designate a valid substring of [buf]. *) val input_byte : in_channel -> int * Same as { ! Pervasives.input_char } , but return the 8 - bit integer representing the character . Raise [ End_of_file ] if an end of file was reached . the character. Raise [End_of_file] if an end of file was reached. *) val input_binary_int : in_channel -> int * Read an integer encoded in binary format ( 4 bytes , big - endian ) from the given input channel . See { ! Pervasives.output_binary_int } . Raise [ End_of_file ] if an end of file was reached while reading the integer . from the given input channel. See {!Pervasives.output_binary_int}. Raise [End_of_file] if an end of file was reached while reading the integer. *) val input_value : in_channel -> 'a val seek_in : in_channel -> int -> unit val pos_in : in_channel -> int val in_channel_length : in_channel -> int val close_in : in_channel -> unit * Close the given channel . Input functions raise a [ Sys_error ] exception when they are applied to a closed input channel , except [ close_in ] , which does nothing when applied to an already closed channel . Note that [ close_in ] may raise [ ] if the operating system signals an error . exception when they are applied to a closed input channel, except [close_in], which does nothing when applied to an already closed channel. Note that [close_in] may raise [Sys_error] if the operating system signals an error. *) val close_in_noerr : in_channel -> unit val set_binary_mode_in : in_channel -> bool -> unit * [ set_binary_mode_in ic true ] sets the channel [ ic ] to binary mode : no translations take place during input . [ set_binary_mode_out ic false ] sets the channel [ ic ] to text mode : depending on the operating system , some translations may take place during input . For instance , under Windows , end - of - lines will be translated from [ \r\n ] to [ \n ] . This function has no effect under operating systems that do not distinguish between text mode and binary mode . mode: no translations take place during input. [set_binary_mode_out ic false] sets the channel [ic] to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from [\r\n] to [\n]. This function has no effect under operating systems that do not distinguish between text mode and binary mode. *) * { 7 Operations on large files } module LargeFile : sig val seek_out : out_channel -> int64 -> unit val pos_out : out_channel -> int64 val out_channel_length : out_channel -> int64 val seek_in : in_channel -> int64 -> unit val pos_in : in_channel -> int64 val in_channel_length : in_channel -> int64 end * Operations on large files . This sub - module provides 64 - bit variants of the channel functions that manipulate file positions and file sizes . By representing positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of regular integers ( type [ int ] ) , these alternate functions allow operating on files whose sizes are greater than [ max_int ] . This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type [int64]) instead of regular integers (type [int]), these alternate functions allow operating on files whose sizes are greater than [max_int]. *) type 'a ref = { mutable contents : 'a } external ref : 'a -> 'a ref = "%makemutable" external ( ! ) : 'a ref -> 'a = "%field0" external ( := ) : 'a ref -> 'a -> unit = "%setfield0" external incr : int ref -> unit = "%incr" external decr : int ref -> unit = "%decr" * { 6 Operations on format strings } type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 * Simplified type for format strings , included for backward compatibility with earlier releases of [ ' a ] is the type of the parameters of the format , [ ' c ] is the result type for the " printf"-style function , and [ ' b ] is the type of the first argument given to [ % a ] and [ % t ] printing functions . with earlier releases of Objective Caml. ['a] is the type of the parameters of the format, ['c] is the result type for the "printf"-style function, and ['b] is the type of the first argument given to [%a] and [%t] printing functions. *) val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string external format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity" val ( ^^ ) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('f, 'b, 'c, 'e, 'g, 'h) format6 -> ('a, 'b, 'c, 'd, 'g, 'h) format6 * { 6 Program termination } val exit : int -> 'a * Terminate the process , returning the given status code to the operating system : usually 0 to indicate no errors , and a small positive integer to indicate failure . All open output channels are flushed with flush_all . An implicit [ exit 0 ] is performed each time a program terminates normally . An implicit [ exit 2 ] is performed if the program terminates early because of an uncaught exception . to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with flush_all. An implicit [exit 0] is performed each time a program terminates normally. An implicit [exit 2] is performed if the program terminates early because of an uncaught exception. *) val at_exit : (unit -> unit) -> unit * Register the given function to be called at program termination time . The functions registered with [ at_exit ] will be called when the program executes { ! Pervasives.exit } , or terminates , either normally or because of an uncaught exception . The functions are called in ` ` last in , first out '' order : the function most recently added with [ at_exit ] is called first . termination time. The functions registered with [at_exit] will be called when the program executes {!Pervasives.exit}, or terminates, either normally or because of an uncaught exception. The functions are called in ``last in, first out'' order: the function most recently added with [at_exit] is called first. *) * { 6 For system use only , not for the casual user } val valid_float_lexem : string -> string val unsafe_really_input : in_channel -> string -> int -> int -> unit val do_at_exit : unit -> unit
7dd2150506c74e5e4688eaa93b615c5a67a5ae62a38f2ca638b5ee82dee407bc
janestreet/jsonaf
jsonaf_kernel.ml
module Conv = Conv module Expert = Expert module Jsonafable = Jsonafable_intf type t = [ `Null | `False | `True | `String of string | `Number of string | `Object of (string * t) list | `Array of t list ] constraint t = Type.t module Parser = struct let parse_number = Result.ok let t_without_trailing_whitespace = Expert.Parser.create_without_trailing_whitespace parse_number ;; let t = Expert.Parser.create parse_number let run_angstrom parser_ = Angstrom.parse_string ~consume:All parser_ let run = run_angstrom t let run_many = run_angstrom (Angstrom.many t) end module Serializer = struct let serialize_number f n = Faraday.write_string f n let serialize = Expert.Serializer.create serialize_number let serialize_hum ~spaces = Expert.Serializer.create_hum ~spaces serialize_number let run t = let faraday = Faraday.create 0x1000 in serialize t faraday; Faraday.serialize_to_string faraday ;; let run_hum ~spaces t = let faraday = Faraday.create 0x1000 in serialize_hum ~spaces t faraday; Faraday.serialize_to_string faraday ;; end
null
https://raw.githubusercontent.com/janestreet/jsonaf/45c4ebabd03dc099e6de76714d86c53e0879558c/kernel/src/jsonaf_kernel.ml
ocaml
module Conv = Conv module Expert = Expert module Jsonafable = Jsonafable_intf type t = [ `Null | `False | `True | `String of string | `Number of string | `Object of (string * t) list | `Array of t list ] constraint t = Type.t module Parser = struct let parse_number = Result.ok let t_without_trailing_whitespace = Expert.Parser.create_without_trailing_whitespace parse_number ;; let t = Expert.Parser.create parse_number let run_angstrom parser_ = Angstrom.parse_string ~consume:All parser_ let run = run_angstrom t let run_many = run_angstrom (Angstrom.many t) end module Serializer = struct let serialize_number f n = Faraday.write_string f n let serialize = Expert.Serializer.create serialize_number let serialize_hum ~spaces = Expert.Serializer.create_hum ~spaces serialize_number let run t = let faraday = Faraday.create 0x1000 in serialize t faraday; Faraday.serialize_to_string faraday ;; let run_hum ~spaces t = let faraday = Faraday.create 0x1000 in serialize_hum ~spaces t faraday; Faraday.serialize_to_string faraday ;; end
c347b1e6a44902450b7b6114d60199895192f0d3786eaab2e8c14106a1fa14d8
Eventuria/demonstration-gsd
Dependencies.hs
# LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # module Eventuria.GSD.Write.CommandSourcer.Server.Dependencies where import Eventuria.Commons.Logger.Core import Eventuria.Commons.Network.Core import qualified Eventuria.Libraries.PersistedStreamEngine.Instances.EventStore.Client.Dependencies as EventStoreClient import Eventuria.GSD.Write.CommandSourcer.Server.Settings import Eventuria.Commons.Dependencies.Core data Dependencies = Dependencies { logger :: Logger , port :: URLPort, eventStoreClientDependencies :: EventStoreClient.Dependencies} getDependencies :: GetDependencies Settings Dependencies c getDependencies Settings {serviceLoggerId, eventStoreClientSettings,port} executionUnderDependenciesAcquired = do logger <- getLogger serviceLoggerId EventStoreClient.getDependencies eventStoreClientSettings (\eventStoreClientDependencies -> executionUnderDependenciesAcquired Dependencies {..}) healthCheck :: HealthCheck Dependencies healthCheck dependencies @ Dependencies {eventStoreClientDependencies} = do result <- EventStoreClient.healthCheck eventStoreClientDependencies return $ fmap (\_ -> ()) result
null
https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/GSD/Write/CommandSourcer/Server/Dependencies.hs
haskell
# LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # module Eventuria.GSD.Write.CommandSourcer.Server.Dependencies where import Eventuria.Commons.Logger.Core import Eventuria.Commons.Network.Core import qualified Eventuria.Libraries.PersistedStreamEngine.Instances.EventStore.Client.Dependencies as EventStoreClient import Eventuria.GSD.Write.CommandSourcer.Server.Settings import Eventuria.Commons.Dependencies.Core data Dependencies = Dependencies { logger :: Logger , port :: URLPort, eventStoreClientDependencies :: EventStoreClient.Dependencies} getDependencies :: GetDependencies Settings Dependencies c getDependencies Settings {serviceLoggerId, eventStoreClientSettings,port} executionUnderDependenciesAcquired = do logger <- getLogger serviceLoggerId EventStoreClient.getDependencies eventStoreClientSettings (\eventStoreClientDependencies -> executionUnderDependenciesAcquired Dependencies {..}) healthCheck :: HealthCheck Dependencies healthCheck dependencies @ Dependencies {eventStoreClientDependencies} = do result <- EventStoreClient.healthCheck eventStoreClientDependencies return $ fmap (\_ -> ()) result
33ca28639f13c7741325427dc002d2745a2932a2a5d9c8b3b6557d2baf7b6953
skruger/ClusterSupervisor
cluster_supervisor_callback.erl
-module(cluster_supervisor_callback). %% %% Include files %% -include("cluster_supervisor.hrl"). %% %% Exported Functions %% -export([behaviour_info/1,add/3,remove/3]). -export([vip_state/2]). %% %% API Functions %% behaviour_info(callbacks) -> [{vip_state,3}]; behaviour_info(_) -> undefined. vip_state(State , ) vip_state(State,VipAddr) -> CallBacks = case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} -> lists:filter(fun(X) -> case X of #cluster_supervisor_callback{type=vip_state} -> true; _ -> false end end,CBList); _ -> [] end, error_logger:warning_msg("Running ~p callbacks.~n~p~n",[length(CallBacks),CallBacks]), lists:foreach(fun(#cluster_supervisor_callback{module=Mod,extraargs=ExtraArgs}=CB) -> try erlang:apply(Mod,vip_state,[State,VipAddr,ExtraArgs]) catch _:Err -> error_logger:warning_msg("Error calling vip_state callback: ~p~n~p~n",[CB,Err]), ok end end,CallBacks). %% Adding the same module twice results in replacing the previously added version. add(Type,Module,ExtraArgs) -> CallBacks = case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} when is_list(CBList) -> lists:filter(fun(X) -> case X of #cluster_supervisor_callback{module=Module,type=Type} -> false; _ -> true end end,CBList); None -> error_logger:error_msg("Replacing empty callback value: ~p~n",[None]), [] end, %% error_logger:error_msg("Callbacks: ~p~n",[CallBacks]), CB = #cluster_supervisor_callback{type=Type,module=Module,extraargs=ExtraArgs}, application:set_env(cluster_supervisor,callbacks,[CB|CallBacks]). remove(Type,Module,ExtraArgs) -> CB = #cluster_supervisor_callback{type=Type,module=Module,extraargs=ExtraArgs}, case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} when is_list(CBList) -> NewCBList = lists:filter(fun(This) -> case This of CB -> false; _ -> true end end, CBList), application:set_env(cluster_supervisor,callbacks,NewCBList); _ -> ok end. %% %% Local Functions %%
null
https://raw.githubusercontent.com/skruger/ClusterSupervisor/92db35944c3da1efdaa8b0b84cc701ad23ee1281/src/cluster_supervisor_callback.erl
erlang
Include files Exported Functions API Functions Adding the same module twice results in replacing the previously added version. error_logger:error_msg("Callbacks: ~p~n",[CallBacks]), Local Functions
-module(cluster_supervisor_callback). -include("cluster_supervisor.hrl"). -export([behaviour_info/1,add/3,remove/3]). -export([vip_state/2]). behaviour_info(callbacks) -> [{vip_state,3}]; behaviour_info(_) -> undefined. vip_state(State , ) vip_state(State,VipAddr) -> CallBacks = case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} -> lists:filter(fun(X) -> case X of #cluster_supervisor_callback{type=vip_state} -> true; _ -> false end end,CBList); _ -> [] end, error_logger:warning_msg("Running ~p callbacks.~n~p~n",[length(CallBacks),CallBacks]), lists:foreach(fun(#cluster_supervisor_callback{module=Mod,extraargs=ExtraArgs}=CB) -> try erlang:apply(Mod,vip_state,[State,VipAddr,ExtraArgs]) catch _:Err -> error_logger:warning_msg("Error calling vip_state callback: ~p~n~p~n",[CB,Err]), ok end end,CallBacks). add(Type,Module,ExtraArgs) -> CallBacks = case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} when is_list(CBList) -> lists:filter(fun(X) -> case X of #cluster_supervisor_callback{module=Module,type=Type} -> false; _ -> true end end,CBList); None -> error_logger:error_msg("Replacing empty callback value: ~p~n",[None]), [] end, CB = #cluster_supervisor_callback{type=Type,module=Module,extraargs=ExtraArgs}, application:set_env(cluster_supervisor,callbacks,[CB|CallBacks]). remove(Type,Module,ExtraArgs) -> CB = #cluster_supervisor_callback{type=Type,module=Module,extraargs=ExtraArgs}, case application:get_env(cluster_supervisor,callbacks) of {ok,CBList} when is_list(CBList) -> NewCBList = lists:filter(fun(This) -> case This of CB -> false; _ -> true end end, CBList), application:set_env(cluster_supervisor,callbacks,NewCBList); _ -> ok end.
abc4b2aafa4e6bd5fbd35014d6351512fff563bdaa979c33529ff61792483e68
idubrov/siperl
sip_idgen.erl
%%%---------------------------------------------------------------- @author < > @doc Utilities to generate different identifiers ( branch , tags ) %%% %%% @end 2011 - 2012 . See LICENSE file . %%%---------------------------------------------------------------- -module(sip_idgen). %% Exports %% API -export([generate_tag/0, generate_branch/0, generate_call_id/0, generate_cseq/0]). -export([generate_id/1]). %% Include files -include("../sip_common.hrl"). -include("sip.hrl"). %%----------------------------------------------------------------- %% API functions %%----------------------------------------------------------------- %% @doc Generate new random alphanumeric tag binary %% When a tag is generated by a UA for insertion into a request or %% response, it MUST be globally unique and cryptographically random with at least 32 bits of randomness . %% @end -spec generate_tag() -> binary(). generate_tag() -> rand_binary(16, <<>>). %% @doc Generate new random alphanumeric branch binary %% %% The branch parameter value MUST be unique across space and time for all requests sent by the UA . %% @end -spec generate_branch() -> binary(). generate_branch() -> rand_binary(8, <<?MAGIC_COOKIE>>). %% @doc Generate new random alphanumeric Call-ID %% In a new request created by a UAC outside of any dialog , the Call - ID header field MUST be selected by the UAC as a globally unique %% identifier over space and time unless overridden by method-specific %% behavior. %% @end -spec generate_call_id() -> binary(). generate_call_id() -> rand_binary(8, <<>>). %% @doc Generate new random CSeq %% The sequence number value MUST be expressible as a 32 - bit unsigned %% integer and MUST be less than 2**31. As long as it follows the above %% guidelines, a client may use any mechanism it would like to select %% CSeq header field values. %% @end -spec generate_cseq() -> integer(). generate_cseq() -> crypto:rand_uniform(1, 2147483648). %% @doc Generate arbitrary random alphanumeric identifier %% %% Generate new string binary identifier for general usage (like, identifying the request in the UA core ) . %% @end -spec generate_id(integer()) -> binary(). generate_id(Len) -> rand_binary(Len, <<>>). %%----------------------------------------------------------------- Internal functions %%----------------------------------------------------------------- rand_binary(0, Bin) -> Bin; rand_binary(N, Bin) -> Char = case crypto:rand_uniform(0, 52) of C when C < 26 -> C + $a; C -> C - 26 + $A end, rand_binary(N - 1, <<Bin/binary, Char>>). %%----------------------------------------------------------------- %% Tests %%----------------------------------------------------------------- -ifdef(TEST). -spec gen_test_() -> term(). gen_test_() -> % Mostly useless tests [?_assertEqual(16, size(generate_tag())), ?_assertEqual(15, size(generate_branch())), ?_assertEqual(8, size(generate_call_id())), ?_assertEqual(23, size(generate_id(23))), ?_assertEqual(true, begin Value = generate_cseq(), 1 =< Value andalso Value =< 2147483648 end) ]. -endif.
null
https://raw.githubusercontent.com/idubrov/siperl/251daf3a0d7c7442f56f42cfd6c92764a4f475a7/apps/sip/src/syntax/sip_idgen.erl
erlang
---------------------------------------------------------------- @end ---------------------------------------------------------------- Exports API Include files ----------------------------------------------------------------- API functions ----------------------------------------------------------------- @doc Generate new random alphanumeric tag binary response, it MUST be globally unique and cryptographically random @end @doc Generate new random alphanumeric branch binary The branch parameter value MUST be unique across space and time for @end @doc Generate new random alphanumeric Call-ID identifier over space and time unless overridden by method-specific behavior. @end @doc Generate new random CSeq integer and MUST be less than 2**31. As long as it follows the above guidelines, a client may use any mechanism it would like to select CSeq header field values. @end @doc Generate arbitrary random alphanumeric identifier Generate new string binary identifier for general usage (like, identifying @end ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Tests ----------------------------------------------------------------- Mostly useless tests
@author < > @doc Utilities to generate different identifiers ( branch , tags ) 2011 - 2012 . See LICENSE file . -module(sip_idgen). -export([generate_tag/0, generate_branch/0, generate_call_id/0, generate_cseq/0]). -export([generate_id/1]). -include("../sip_common.hrl"). -include("sip.hrl"). When a tag is generated by a UA for insertion into a request or with at least 32 bits of randomness . -spec generate_tag() -> binary(). generate_tag() -> rand_binary(16, <<>>). all requests sent by the UA . -spec generate_branch() -> binary(). generate_branch() -> rand_binary(8, <<?MAGIC_COOKIE>>). In a new request created by a UAC outside of any dialog , the Call - ID header field MUST be selected by the UAC as a globally unique -spec generate_call_id() -> binary(). generate_call_id() -> rand_binary(8, <<>>). The sequence number value MUST be expressible as a 32 - bit unsigned -spec generate_cseq() -> integer(). generate_cseq() -> crypto:rand_uniform(1, 2147483648). the request in the UA core ) . -spec generate_id(integer()) -> binary(). generate_id(Len) -> rand_binary(Len, <<>>). Internal functions rand_binary(0, Bin) -> Bin; rand_binary(N, Bin) -> Char = case crypto:rand_uniform(0, 52) of C when C < 26 -> C + $a; C -> C - 26 + $A end, rand_binary(N - 1, <<Bin/binary, Char>>). -ifdef(TEST). -spec gen_test_() -> term(). gen_test_() -> [?_assertEqual(16, size(generate_tag())), ?_assertEqual(15, size(generate_branch())), ?_assertEqual(8, size(generate_call_id())), ?_assertEqual(23, size(generate_id(23))), ?_assertEqual(true, begin Value = generate_cseq(), 1 =< Value andalso Value =< 2147483648 end) ]. -endif.
5082ec7fdfa34b8de3eadd21de5c309f41edb9ba049467f0b4563a12eb1d90ed
Vortecsmaster/EmurgoAcademyPlutusExamples
NFTBounty.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} module NFTBounty where PlutusTx import PlutusTx (Data (..)) import qualified PlutusTx import qualified PlutusTx.Builtins as Builtins import PlutusTx.Prelude hiding (Semigroup(..), unless) --Contract Monad import Plutus.Contract --Ledger import Ledger hiding (singleton) import qualified Ledger.Address as V1Address Same library name , different functions for V1 and V2 in some cases import qualified Ledger . Typed . Scripts as Scripts New library name for Typed and some new fuctions import qualified Plutus.V1.Ledger.Api as PlutusV1 -- import Ledger.Ada as Ada Trace Emulator import Plutus.Trace import qualified Plutus.Trace.Emulator as Emulator import qualified Wallet.Emulator.Wallet as Wallet ( broken ) import Playground . Contract ( printJson , printSchemas , ensureKnownCurrencies , stage ) import Playground . TH ( mkKnownCurrencies , mkSchemaDefinitions ) import Playground . Types ( ( .. ) ) --"Normal " Haskell import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) --"Normal" Haskell -} import Control.Monad hiding (fmap) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import Prelude (IO, Semigroup (..), String, show) import Text.Printf (printf) import Control.Monad.Freer.Extras as Extras import Language . . TH ( RuleBndr(TypedRuleVar ) ) import Language.Haskell.TH (RuleBndr(TypedRuleVar)) -} # OPTIONS_GHC -fno - warn - unused - imports # --THE ON-CHAIN CODE newtype MyWonderfullRedeemer = MWR Integer At compile time write an instance of this data type ( MyWonderFullRedeemer ) on the IsData typeclass # INLINABLE typedRedeemer # typedRedeemer :: () -> MyWonderfullRedeemer -> PlutusV1.ScriptContext -> Bool typedRedeemer _ (MWR redeemer) _ = traceIfFalse "Wrong redeemer!" (redeemer == 42) New type that encode the information about the Datum and the Redeemer instance Scripts.ValidatorTypes Typed where type instance RedeemerType Typed = MyWonderfullRedeemer type instance DatumType Typed = () typedValidator :: Scripts.TypedValidator Typed typedValidator = Scripts.mkTypedValidator @Typed $$(PlutusTx.compile [|| typedRedeemer ||]) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.mkUntypedValidator @() @MyWonderfullRedeemer --New wrapper function for typed validators validator :: Validator validator = Scripts.validatorScript typedValidator -- Get the untyped validator script of the wrapped typeValidator PlutusCore valHash :: Ledger.ValidatorHash valHash = Scripts.validatorHash typedValidator scrAddress :: Ledger.Address New functino to derive the address , included in the Utils library --scrAddress = scriptAddress validator --THE OFFCHAIN CODE type GiftSchema = Endpoint "give" Integer -- .\/ Endpoint "grab" Integer give :: AsContractError e => Integer -> Contract w s e () give amount = do Typed version for one script , This Tx needs an output , that s its going to be the Script Address , Datum MUST be specified , so unit ( ) . This line submit the Tx void $ awaitTxConfirmed $ getCardanoTxId ledgerTx --This line waits for confirmation Plutus.Contract.logInfo @String $ printf "made a gift of %d lovelace" amount --This line log info,usable on the PP(Plutus Playground) --grab :: forall w s e. AsContractError e => Contract w s e () grab :: forall w s e. AsContractError e => Integer -> Contract w s e () grab n = do utxos <- utxosAt scrAddress -- This will find all UTXOs that sit at the script address let orefs = fst <$> Map.toList utxos -- This get all the references of the UTXOs lookups = Constraints.unspentOutputs utxos <> -- Tell where to find all the UTXOS and inform about the actual validator ( the spending tx needs to provide the actual validator ) tx :: TxConstraints Void Void Define the TX giving constrains , one for each UTXO sitting on this addrs , -- must provide a redeemer (ignored in this case) Allow the wallet to construct the tx with the necesary information void $ awaitTxConfirmed $ getCardanoTxId ledgerTx -- Wait for confirmation Plutus.Contract.logInfo @String $ "collected gifts" -- Log information endpoints :: Contract () GiftSchema Text () endpoints = awaitPromise (give' `select` grab') >> endpoints -- Asynchronously wait for the endpoints interactions from the wallet where -- and recursively wait for the endpoints all over again give' = endpoint @"give" give -- block until give grab' = endpoint @"grab" grab -- block until grab Playground broken at the moment - September 2022 mkSchemaDefinitions '' GiftSchema -- Generate the Schema for the playground -- mkKnownCurrencies [] --SIMULATION test :: IO () test = runEmulatorTraceIO $ do h1 <- activateContractWallet (Wallet.knownWallet 1) endpoints h2 <- activateContractWallet (Wallet.knownWallet 2) endpoints callEndpoint @"give" h1 $ 51000000 void $ Emulator.waitNSlots 11 callEndpoint @"grab" h2 42 s <- Emulator.waitNSlots 11 Extras.logInfo $ "End of Simulation at slot " ++ show s
null
https://raw.githubusercontent.com/Vortecsmaster/EmurgoAcademyPlutusExamples/184a00c1d53c24acfbe9ecf8c37ad4e09285c31b/V1/MathBounty/src/NFTBounty.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE TypeOperators # # LANGUAGE OverloadedStrings # Contract Monad Ledger "Normal " Haskell "Normal" Haskell -} THE ON-CHAIN CODE New wrapper function for typed validators Get the untyped validator script of the wrapped typeValidator PlutusCore scrAddress = scriptAddress validator THE OFFCHAIN CODE This line waits for confirmation This line log info,usable on the PP(Plutus Playground) grab :: forall w s e. AsContractError e => Contract w s e () This will find all UTXOs that sit at the script address This get all the references of the UTXOs Tell where to find all the UTXOS must provide a redeemer (ignored in this case) Wait for confirmation Log information Asynchronously wait for the endpoints interactions from the wallet and recursively wait for the endpoints all over again block until give block until grab Generate the Schema for the playground mkKnownCurrencies [] SIMULATION
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module NFTBounty where PlutusTx import PlutusTx (Data (..)) import qualified PlutusTx import qualified PlutusTx.Builtins as Builtins import PlutusTx.Prelude hiding (Semigroup(..), unless) import Plutus.Contract import Ledger hiding (singleton) import qualified Ledger.Address as V1Address Same library name , different functions for V1 and V2 in some cases import qualified Ledger . Typed . Scripts as Scripts New library name for Typed and some new fuctions import Ledger.Ada as Ada Trace Emulator import Plutus.Trace import qualified Plutus.Trace.Emulator as Emulator import qualified Wallet.Emulator.Wallet as Wallet ( broken ) import Playground . Contract ( printJson , printSchemas , ensureKnownCurrencies , stage ) import Playground . TH ( mkKnownCurrencies , mkSchemaDefinitions ) import Playground . Types ( ( .. ) ) import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage) import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions) import Playground.Types (KnownCurrency (..)) import Control.Monad hiding (fmap) import Data.Map as Map import Data.Text (Text) import Data.Void (Void) import Prelude (IO, Semigroup (..), String, show) import Text.Printf (printf) import Control.Monad.Freer.Extras as Extras import Language . . TH ( RuleBndr(TypedRuleVar ) ) import Language.Haskell.TH (RuleBndr(TypedRuleVar)) -} # OPTIONS_GHC -fno - warn - unused - imports # newtype MyWonderfullRedeemer = MWR Integer At compile time write an instance of this data type ( MyWonderFullRedeemer ) on the IsData typeclass # INLINABLE typedRedeemer # typedRedeemer :: () -> MyWonderfullRedeemer -> PlutusV1.ScriptContext -> Bool typedRedeemer _ (MWR redeemer) _ = traceIfFalse "Wrong redeemer!" (redeemer == 42) New type that encode the information about the Datum and the Redeemer instance Scripts.ValidatorTypes Typed where type instance RedeemerType Typed = MyWonderfullRedeemer type instance DatumType Typed = () typedValidator :: Scripts.TypedValidator Typed typedValidator = Scripts.mkTypedValidator @Typed $$(PlutusTx.compile [|| typedRedeemer ||]) $$(PlutusTx.compile [|| wrap ||]) where validator :: Validator valHash :: Ledger.ValidatorHash valHash = Scripts.validatorHash typedValidator scrAddress :: Ledger.Address New functino to derive the address , included in the Utils library type GiftSchema = .\/ Endpoint "grab" Integer give :: AsContractError e => Integer -> Contract w s e () give amount = do Typed version for one script , This Tx needs an output , that s its going to be the Script Address , Datum MUST be specified , so unit ( ) . This line submit the Tx grab :: forall w s e. AsContractError e => Integer -> Contract w s e () grab n = do and inform about the actual validator ( the spending tx needs to provide the actual validator ) tx :: TxConstraints Void Void Define the TX giving constrains , one for each UTXO sitting on this addrs , Allow the wallet to construct the tx with the necesary information endpoints :: Contract () GiftSchema Text () Playground broken at the moment - September 2022 test :: IO () test = runEmulatorTraceIO $ do h1 <- activateContractWallet (Wallet.knownWallet 1) endpoints h2 <- activateContractWallet (Wallet.knownWallet 2) endpoints callEndpoint @"give" h1 $ 51000000 void $ Emulator.waitNSlots 11 callEndpoint @"grab" h2 42 s <- Emulator.waitNSlots 11 Extras.logInfo $ "End of Simulation at slot " ++ show s
f904fb7758105e96f741b1757d78fd322c736e95562ac610c60b0451b401fde2
paines/cl-puyopuyo
package.lisp
package.lisp (defpackage #:cl-puyopuyo (:use #:cl))
null
https://raw.githubusercontent.com/paines/cl-puyopuyo/8a7786d38be041027669658e6be46366d45eece2/package.lisp
lisp
package.lisp (defpackage #:cl-puyopuyo (:use #:cl))
825edfe3ba0e2696e77b355c8bb512f7f8a954543008ddf041d6ae45d63000b9
openbadgefactory/salava
registration_test.clj
(ns salava.user.registration-test (:require [midje.sweet :refer :all] [salava.core.migrator :as migrator] [salava.test-utils :refer [test-api-request]])) (def registration-data {:first_name "Testing" :last_name "Registration" :email "" :country "US"}) (facts "about user account registration" (fact "email address must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :email))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address@either"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email (str (apply str (repeat 252 "a")) "@a.a")))) => 400) (fact "first name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :first_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name (apply str (repeat 256 "a"))))) => 400) (fact "last name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :last_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name (apply str (repeat 256 "a"))))) => 400) (fact "country must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :country))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country "XX"))) => 400) (fact "user can create an account" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "success")) (fact "user can not create account, if email address is already taken" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "error"))) (migrator/reset-seeds (migrator/test-config))
null
https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/user/registration_test.clj
clojure
(ns salava.user.registration-test (:require [midje.sweet :refer :all] [salava.core.migrator :as migrator] [salava.test-utils :refer [test-api-request]])) (def registration-data {:first_name "Testing" :last_name "Registration" :email "" :country "US"}) (facts "about user account registration" (fact "email address must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :email))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address@either"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email (str (apply str (repeat 252 "a")) "@a.a")))) => 400) (fact "first name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :first_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name (apply str (repeat 256 "a"))))) => 400) (fact "last name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :last_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name (apply str (repeat 256 "a"))))) => 400) (fact "country must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :country))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country "XX"))) => 400) (fact "user can create an account" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "success")) (fact "user can not create account, if email address is already taken" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "error"))) (migrator/reset-seeds (migrator/test-config))
fcb962dc1936d73291e564e2ee41c4cefb173669ff26384da6343c15a0b69157
BinaryAnalysisPlatform/bap-plugins
trim.mli
* A trim is a subgraph composed of unique source / sink pairs . One or more trims may be produced from a cut group : one trim for each unique source / sink pair . more trims may be produced from a cut group: one trim for each unique source/sink pair. *) open Bap.Std open Cut open Options type trim = { trim_sub : Sub.t; cut_group : cut_group; src_tid : tid; sink_tid : tid } (* 'a is debug. 'b is highlight. *) (* A given cut_group returns a sequence of trims (trim group) *) val trims : sub term -> cut_group -> 'b -> bool -> trim seq
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap-plugins/2e9aa5c7c24ef494d0e7db1b43c5ceedcb4196a8/minos/trim.mli
ocaml
'a is debug. 'b is highlight. A given cut_group returns a sequence of trims (trim group)
* A trim is a subgraph composed of unique source / sink pairs . One or more trims may be produced from a cut group : one trim for each unique source / sink pair . more trims may be produced from a cut group: one trim for each unique source/sink pair. *) open Bap.Std open Cut open Options type trim = { trim_sub : Sub.t; cut_group : cut_group; src_tid : tid; sink_tid : tid } val trims : sub term -> cut_group -> 'b -> bool -> trim seq
e8b245cc6e7421063b1d66cccb6eb3c8b0495c851cd165b66eded9a93e2d0305
facebook/duckling
Rules.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.TimeGrain.EN.Rules ( rules ) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Types import qualified Duckling.TimeGrain.Types as TG grains :: [(Text, String, TG.Grain)] grains = [ ("second (grain) ", "sec(ond)?s?", TG.Second) , ("minute (grain)" , "m(in(ute)?s?)?", TG.Minute) , ("hour (grain)" , "h(((ou)?rs?)|r)?", TG.Hour) , ("day (grain)" , "days?", TG.Day) , ("week (grain)" , "weeks?", TG.Week) , ("month (grain)" , "months?", TG.Month) , ("quarter (grain)", "(quarter|qtr)s?", TG.Quarter) , ("year (grain)" , "y(ea)?rs?", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/TimeGrain/EN/Rules.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.TimeGrain.EN.Rules ( rules ) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Types import qualified Duckling.TimeGrain.Types as TG grains :: [(Text, String, TG.Grain)] grains = [ ("second (grain) ", "sec(ond)?s?", TG.Second) , ("minute (grain)" , "m(in(ute)?s?)?", TG.Minute) , ("hour (grain)" , "h(((ou)?rs?)|r)?", TG.Hour) , ("day (grain)" , "days?", TG.Day) , ("week (grain)" , "weeks?", TG.Week) , ("month (grain)" , "months?", TG.Month) , ("quarter (grain)", "(quarter|qtr)s?", TG.Quarter) , ("year (grain)" , "y(ea)?rs?", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
252d628ba6854809c630cd5c0508bef32bb265c2d2393314a4795c51a5dad8bb
caiorss/Functional-Programming
actions.hs
file : ch07 / actions.hs str2action :: String -> IO () str2action input = putStrLn ("Data: " ++ input) list2actions :: [String] -> [IO ()] list2actions = map str2action numbers :: [Int] numbers = [1..10] strings :: [String] strings = map show numbers actions :: [IO ()] actions = list2actions strings printitall :: IO () printitall = runall actions -- Take a list of actions, and execute each of them in turn. runall :: [IO ()] -> IO () runall [] = return () runall (firstelem:remainingelems) = do firstelem runall remainingelems main = do str2action "Start of the program" printitall str2action "Done!"
null
https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/haskell/rwh/ch07/actions.hs
haskell
Take a list of actions, and execute each of them in turn.
file : ch07 / actions.hs str2action :: String -> IO () str2action input = putStrLn ("Data: " ++ input) list2actions :: [String] -> [IO ()] list2actions = map str2action numbers :: [Int] numbers = [1..10] strings :: [String] strings = map show numbers actions :: [IO ()] actions = list2actions strings printitall :: IO () printitall = runall actions runall :: [IO ()] -> IO () runall [] = return () runall (firstelem:remainingelems) = do firstelem runall remainingelems main = do str2action "Start of the program" printitall str2action "Done!"
10544084572b407fe20c8124f94e32e5795e2508e1059338259ac1c7694a15e3
ghollisjr/cl-ana
package.lisp
cl - ana is a Common Lisp data analysis library . Copyright 2013 , 2014 ;;;; This file is part of cl - ana . ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see </>. ;;;; You may contact ( me ! ) via email at ;;;; (defpackage #:cl-ana.clos-utils (:use :cl :cl-ana.tensor :cl-ana.list-utils :cl-ana.symbol-utils) (:export :slot-names :slot-keyword-names :slot-values :clist-type :clist-field-symbols :clist-field-values :object->clist :object->plist :clist->object :type-constructor))
null
https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/clos-utils/package.lisp
lisp
cl-ana is free software: you can redistribute it and/or modify it (at your option) any later version. cl-ana is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with cl-ana. If not, see </>.
cl - ana is a Common Lisp data analysis library . Copyright 2013 , 2014 This file is part of cl - ana . under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License You may contact ( me ! ) via email at (defpackage #:cl-ana.clos-utils (:use :cl :cl-ana.tensor :cl-ana.list-utils :cl-ana.symbol-utils) (:export :slot-names :slot-keyword-names :slot-values :clist-type :clist-field-symbols :clist-field-values :object->clist :object->plist :clist->object :type-constructor))