_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
bf02642931ae171899e36a37459c8e82a7bdeb2cd355a912342b4ba5cc94c5ab
master/ejabberd
idna.erl
%%%---------------------------------------------------------------------- %%% File : idna.erl Author : < > %%% Purpose : Support for IDNA (RFC3490) Created : 10 Apr 2004 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA %%% %%%---------------------------------------------------------------------- -module(idna). -author(''). %%-compile(export_all). -export([domain_utf8_to_ascii/1, domain_ucs2_to_ascii/1]). domain_utf8_to_ascii(Domain) -> domain_ucs2_to_ascii(utf8_to_ucs2(Domain)). utf8_to_ucs2(S) -> utf8_to_ucs2(S, ""). utf8_to_ucs2([], R) -> lists:reverse(R); utf8_to_ucs2([C | S], R) when C < 16#80 -> utf8_to_ucs2(S, [C | R]); utf8_to_ucs2([C1, C2 | S], R) when C1 < 16#E0 -> utf8_to_ucs2(S, [((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) | R]); utf8_to_ucs2([C1, C2, C3 | S], R) when C1 < 16#F0 -> utf8_to_ucs2(S, [((C1 band 16#0F) bsl 12) bor ((C2 band 16#3F) bsl 6) bor (C3 band 16#3F) | R]). domain_ucs2_to_ascii(Domain) -> case catch domain_ucs2_to_ascii1(Domain) of {'EXIT', _Reason} -> false; Res -> Res end. domain_ucs2_to_ascii1(Domain) -> Parts = string:tokens(Domain, [16#002E, 16#3002, 16#FF0E, 16#FF61]), ASCIIParts = lists:map(fun(P) -> to_ascii(P) end, Parts), string:strip(lists:flatmap(fun(P) -> [$. | P] end, ASCIIParts), left, $.). Domain names are already in ejabberd , so we skiping this step to_ascii(Name) -> false = lists:any( fun(C) when ( 0 =< C) and (C =< 16#2C) or (16#2E =< C) and (C =< 16#2F) or (16#3A =< C) and (C =< 16#40) or (16#5B =< C) and (C =< 16#60) or (16#7B =< C) and (C =< 16#7F) -> true; (_) -> false end, Name), case Name of [H | _] when H /= $- -> true = lists:last(Name) /= $- end, ASCIIName = case lists:any(fun(C) -> C > 16#7F end, Name) of true -> true = case Name of "xn--" ++ _ -> false; _ -> true end, "xn--" ++ punycode_encode(Name); false -> Name end, L = length(ASCIIName), true = (1 =< L) and (L =< 63), ASCIIName. PUNYCODE ( RFC3492 ) -define(BASE, 36). -define(TMIN, 1). -define(TMAX, 26). -define(SKEW, 38). -define(DAMP, 700). -define(INITIAL_BIAS, 72). -define(INITIAL_N, 128). punycode_encode(Input) -> N = ?INITIAL_N, Delta = 0, Bias = ?INITIAL_BIAS, Basic = lists:filter(fun(C) -> C =< 16#7f end, Input), NonBasic = lists:filter(fun(C) -> C > 16#7f end, Input), L = length(Input), B = length(Basic), SNonBasic = lists:usort(NonBasic), Output1 = if B > 0 -> Basic ++ "-"; true -> "" end, Output2 = punycode_encode1(Input, SNonBasic, B, B, L, N, Delta, Bias, ""), Output1 ++ Output2. punycode_encode1(Input, [M | SNonBasic], B, H, L, N, Delta, Bias, Out) when H < L -> Delta1 = Delta + (M - N) * (H + 1), % let n = m {NewDelta, NewBias, NewH, NewOut} = lists:foldl( fun(C, {ADelta, ABias, AH, AOut}) -> if C < M -> {ADelta + 1, ABias, AH, AOut}; C == M -> NewOut = punycode_encode_delta(ADelta, ABias, AOut), NewBias = adapt(ADelta, H + 1, H == B), {0, NewBias, AH + 1, NewOut}; true -> {ADelta, ABias, AH, AOut} end end, {Delta1, Bias, H, Out}, Input), punycode_encode1( Input, SNonBasic, B, NewH, L, M + 1, NewDelta + 1, NewBias, NewOut); punycode_encode1(_Input, _SNonBasic, _B, _H, _L, _N, _Delta, _Bias, Out) -> lists:reverse(Out). punycode_encode_delta(Delta, Bias, Out) -> punycode_encode_delta(Delta, Bias, Out, ?BASE). punycode_encode_delta(Delta, Bias, Out, K) -> T = if K =< Bias -> ?TMIN; K >= Bias + ?TMAX -> ?TMAX; true -> K - Bias end, if Delta < T -> [codepoint(Delta) | Out]; true -> C = T + ((Delta - T) rem (?BASE - T)), punycode_encode_delta((Delta - T) div (?BASE - T), Bias, [codepoint(C) | Out], K + ?BASE) end. adapt(Delta, NumPoints, FirstTime) -> Delta1 = if FirstTime -> Delta div ?DAMP; true -> Delta div 2 end, Delta2 = Delta1 + (Delta1 div NumPoints), adapt1(Delta2, 0). adapt1(Delta, K) -> if Delta > ((?BASE - ?TMIN) * ?TMAX) div 2 -> adapt1(Delta div (?BASE - ?TMIN), K + ?BASE); true -> K + (((?BASE - ?TMIN + 1) * Delta) div (Delta + ?SKEW)) end. codepoint(C) -> if (0 =< C) and (C =< 25) -> C + 97; (26 =< C) and (C =< 35) -> C + 22 end.
null
https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/idna.erl
erlang
---------------------------------------------------------------------- File : idna.erl Purpose : Support for IDNA (RFC3490) This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ---------------------------------------------------------------------- -compile(export_all). let n = m
Author : < > Created : 10 Apr 2004 by < > ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA -module(idna). -author(''). -export([domain_utf8_to_ascii/1, domain_ucs2_to_ascii/1]). domain_utf8_to_ascii(Domain) -> domain_ucs2_to_ascii(utf8_to_ucs2(Domain)). utf8_to_ucs2(S) -> utf8_to_ucs2(S, ""). utf8_to_ucs2([], R) -> lists:reverse(R); utf8_to_ucs2([C | S], R) when C < 16#80 -> utf8_to_ucs2(S, [C | R]); utf8_to_ucs2([C1, C2 | S], R) when C1 < 16#E0 -> utf8_to_ucs2(S, [((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) | R]); utf8_to_ucs2([C1, C2, C3 | S], R) when C1 < 16#F0 -> utf8_to_ucs2(S, [((C1 band 16#0F) bsl 12) bor ((C2 band 16#3F) bsl 6) bor (C3 band 16#3F) | R]). domain_ucs2_to_ascii(Domain) -> case catch domain_ucs2_to_ascii1(Domain) of {'EXIT', _Reason} -> false; Res -> Res end. domain_ucs2_to_ascii1(Domain) -> Parts = string:tokens(Domain, [16#002E, 16#3002, 16#FF0E, 16#FF61]), ASCIIParts = lists:map(fun(P) -> to_ascii(P) end, Parts), string:strip(lists:flatmap(fun(P) -> [$. | P] end, ASCIIParts), left, $.). Domain names are already in ejabberd , so we skiping this step to_ascii(Name) -> false = lists:any( fun(C) when ( 0 =< C) and (C =< 16#2C) or (16#2E =< C) and (C =< 16#2F) or (16#3A =< C) and (C =< 16#40) or (16#5B =< C) and (C =< 16#60) or (16#7B =< C) and (C =< 16#7F) -> true; (_) -> false end, Name), case Name of [H | _] when H /= $- -> true = lists:last(Name) /= $- end, ASCIIName = case lists:any(fun(C) -> C > 16#7F end, Name) of true -> true = case Name of "xn--" ++ _ -> false; _ -> true end, "xn--" ++ punycode_encode(Name); false -> Name end, L = length(ASCIIName), true = (1 =< L) and (L =< 63), ASCIIName. PUNYCODE ( RFC3492 ) -define(BASE, 36). -define(TMIN, 1). -define(TMAX, 26). -define(SKEW, 38). -define(DAMP, 700). -define(INITIAL_BIAS, 72). -define(INITIAL_N, 128). punycode_encode(Input) -> N = ?INITIAL_N, Delta = 0, Bias = ?INITIAL_BIAS, Basic = lists:filter(fun(C) -> C =< 16#7f end, Input), NonBasic = lists:filter(fun(C) -> C > 16#7f end, Input), L = length(Input), B = length(Basic), SNonBasic = lists:usort(NonBasic), Output1 = if B > 0 -> Basic ++ "-"; true -> "" end, Output2 = punycode_encode1(Input, SNonBasic, B, B, L, N, Delta, Bias, ""), Output1 ++ Output2. punycode_encode1(Input, [M | SNonBasic], B, H, L, N, Delta, Bias, Out) when H < L -> Delta1 = Delta + (M - N) * (H + 1), {NewDelta, NewBias, NewH, NewOut} = lists:foldl( fun(C, {ADelta, ABias, AH, AOut}) -> if C < M -> {ADelta + 1, ABias, AH, AOut}; C == M -> NewOut = punycode_encode_delta(ADelta, ABias, AOut), NewBias = adapt(ADelta, H + 1, H == B), {0, NewBias, AH + 1, NewOut}; true -> {ADelta, ABias, AH, AOut} end end, {Delta1, Bias, H, Out}, Input), punycode_encode1( Input, SNonBasic, B, NewH, L, M + 1, NewDelta + 1, NewBias, NewOut); punycode_encode1(_Input, _SNonBasic, _B, _H, _L, _N, _Delta, _Bias, Out) -> lists:reverse(Out). punycode_encode_delta(Delta, Bias, Out) -> punycode_encode_delta(Delta, Bias, Out, ?BASE). punycode_encode_delta(Delta, Bias, Out, K) -> T = if K =< Bias -> ?TMIN; K >= Bias + ?TMAX -> ?TMAX; true -> K - Bias end, if Delta < T -> [codepoint(Delta) | Out]; true -> C = T + ((Delta - T) rem (?BASE - T)), punycode_encode_delta((Delta - T) div (?BASE - T), Bias, [codepoint(C) | Out], K + ?BASE) end. adapt(Delta, NumPoints, FirstTime) -> Delta1 = if FirstTime -> Delta div ?DAMP; true -> Delta div 2 end, Delta2 = Delta1 + (Delta1 div NumPoints), adapt1(Delta2, 0). adapt1(Delta, K) -> if Delta > ((?BASE - ?TMIN) * ?TMAX) div 2 -> adapt1(Delta div (?BASE - ?TMIN), K + ?BASE); true -> K + (((?BASE - ?TMIN + 1) * Delta) div (Delta + ?SKEW)) end. codepoint(C) -> if (0 =< C) and (C =< 25) -> C + 97; (26 =< C) and (C =< 35) -> C + 22 end.
a4a02ce3fabe9fc86337b6cefe967cb0cf240def8f0f3d0a797ece47e39afb0b
bluelisp/hemlock
lispeval.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; ;;; ;;; ********************************************************************** ;;; ;;; This file contains code for sending requests to eval servers and the ;;; commands based on that code. ;;; Written by and . ;;; (in-package :hemlock) ;;; The note structure holds everything we need to know about an ;;; operation. Not all operations use all the available fields. ;;; (defstruct (note (:print-function %print-note)) (state :unsent) ; :unsent, :pending, :running, :aborted or :dead. Server - Info for the server this op is on . context ; Short string describing what this op is doing. kind ; Either :eval, :compile, or :compile-file buffer ; Buffer source came from. region ; Region of request package ; Package or NIL if none text ; string containing request input-file ; File to compile or where stuff was found net-input-file ; Net version of above. output-file ; Temporary output file for compiler fasl code. net-output-file ; Net version of above output-date ; Temp-file is created before calling compiler, ; and this is its write date. lap-file ; The lap file for compiles error-file ; The file to dump errors into load ; Load compiled file or not? (errors 0) ; Count of compiler errors. (warnings 0) ; Count of compiler warnings. (notes 0)) ; Count of compiler notes. ;;; (defun %print-note (note stream d) (declare (ignore d)) (format stream "#<Eval-Server-Note for ~A [~A]>" (note-context note) (note-state note))) ;;;; Note support routines. ;;; QUEUE-NOTE -- Internal. ;;; ;;; This queues note for server. SERVER-INFO-NOTES keeps notes in stack order, ;;; not queue order. We also link the note to the server and try to send it ;;; to the server. If we didn't send this note, we tell the user the server ;;; is busy and that we're queuing his note to be sent later. ;;; (defun queue-note (note server) (push note (server-info-notes server)) (setf (note-server note) server) (maybe-send-next-note server) (when (eq (note-state note) :unsent) (message "Server ~A busy, ~A queued." (server-info-name server) (note-context note)))) ;;; MAYBE-SEND-NEXT-NOTE -- Internal. ;;; ;;; Loop over all notes in server. If we see any :pending or :running, then ;;; punt since we can't send one. Otherwise, by the end of the list, we may ;;; have found an :unsent one, and if we did, next will be the last :unsent ;;; note. Remember, SERVER-INFO-NOTES is kept in stack order not queue order. ;;; (defun maybe-send-next-note (server) (let ((busy nil) (next nil)) (dolist (note (server-info-notes server)) (ecase (note-state note) ((:pending :running) (setf busy t) (return)) (:unsent (setf next note)) (:aborted :dead))) (when (and (not busy) next) (send-note next)))) (defun send-note (note) (let* ((remote (hemlock.wire:make-remote-object note)) (server (note-server note)) (ts (server-info-slave-info server)) (bg (server-info-background-info server)) (wire (server-info-wire server))) (setf (note-state note) :pending) (message "Sending ~A." (note-context note)) (case (note-kind note) (:eval (hemlock.wire:remote wire (server-eval-text remote (note-package note) (note-text note) (and ts (ts-data-stream ts))))) (:compile (hemlock.wire:remote wire (server-compile-text remote (note-package note) (note-text note) (note-input-file note) (and ts (ts-data-stream ts)) (and bg (ts-data-stream bg))))) (:compile-file (macrolet ((frob (x) `(if (pathnamep ,x) (namestring ,x) ,x))) (hemlock.wire:remote wire (server-compile-file remote (note-package note) (frob (or (note-net-input-file note) (note-input-file note))) (frob (or (note-net-output-file note) (note-output-file note))) (frob (note-error-file note)) (frob (note-lap-file note)) (note-load note) (and ts (ts-data-stream ts)) (and bg (ts-data-stream bg)))))) (t (error "Unknown note kind ~S" (note-kind note)))) (hemlock.wire:wire-force-output wire))) Server Callbacks . (defun operation-started (note) (let ((note (hemlock.wire:remote-object-value note))) (setf (note-state note) :running) (message "The ~A started." (note-context note))) (values)) (defun eval-form-error (message) (editor-error message)) (defun lisp-error (note start end msg) (declare (ignore start end)) (let ((note (hemlock.wire:remote-object-value note))) (loud-message "During ~A: ~A" (note-context note) msg)) (values)) (defun compiler-error (note start end function severity) (let* ((note (hemlock.wire:remote-object-value note)) (server (note-server note)) (line (mark-line (buffer-end-mark (server-info-background-buffer server)))) (message (format nil "~:(~A~) ~@[in ~A ~]during ~A." severity function (note-context note))) (error (make-error-info :buffer (note-buffer note) :message message :line line))) (message "~A" message) (case severity (:error (incf (note-errors note))) (:warning (incf (note-warnings note))) (:note (incf (note-notes note)))) (let ((region (case (note-kind note) (:compile (note-region note)) (:compile-file (let ((buff (note-buffer note))) (and buff (buffer-region buff)))) (t (error "Compiler error in ~S?" note))))) (when region (let* ((region-end (region-end region)) (m1 (copy-mark (region-start region) :left-inserting)) (m2 (copy-mark m1 :left-inserting))) (when start (character-offset m1 start) (when (mark> m1 region-end) (move-mark m1 region-end))) (unless (and end (character-offset m2 end)) (move-mark m2 region-end)) (setf (error-info-region error) (region m1 m2))))) (vector-push-extend error (server-info-errors server))) (values)) (defun eval-text-result (note start end values) (declare (ignore note start end)) (message "=> ~{~#[~;~A~:;~A, ~]~}" values) (values)) (defun operation-completed (note abortp) (let* ((note (hemlock.wire:remote-object-value note)) (server (note-server note)) (file (note-output-file note))) (hemlock.wire:forget-remote-translation note) (setf (note-state note) :dead) (setf (server-info-notes server) (delete note (server-info-notes server) :test #'eq)) (setf (note-server note) nil) (if abortp (loud-message "The ~A aborted." (note-context note)) (let ((errors (note-errors note)) (warnings (note-warnings note)) (notes (note-notes note))) (message "The ~A complete.~ ~@[ ~D error~:P~]~@[ ~D warning~:P~]~@[ ~D note~:P~]" (note-context note) (and (plusp errors) errors) (and (plusp warnings) warnings) (and (plusp notes) notes)))) (let ((region (note-region note))) (when (regionp region) (delete-mark (region-start region)) (delete-mark (region-end region)) (setf (note-region note) nil))) (when (and (eq (note-kind note) :compile-file) (not (eq file t)) file) (if (> (file-write-date file) (note-output-date note)) (let ((new-name (make-pathname :type "fasl" :defaults (note-input-file note)))) (rename-file file new-name) #+NILGB (unix:unix-chmod (namestring new-name) #o644)) (delete-file file))) (maybe-send-next-note server)) (values)) ;;;; Stuff to send noise to the server. fixme : these two should be the same (defun eval-safely-in-slave (form) (handler-case (eval form) (error (c) (warn "ignoring error in slave request: ~A" c)))) (defun eval-safely-in-master (form) (let (ok) (block nil (unwind-protect (multiple-value-prog1 (eval form) (setf ok t)) (unless ok (return "fell through)")))))) (defvar *synchronous-evaluation-of-slave-requests-in-the-master* nil) (defun eval-in-master (form) (if *synchronous-evaluation-of-slave-requests-in-the-master* (eval form) (hemlock.wire:remote hemlock.wire::*current-wire* (eval-safely-in-master form)))) (defun eval-in-slave (form) (if *synchronous-evaluation-of-slave-requests-in-the-master* (eval form) (hemlock.wire:remote (server-info-wire (get-current-eval-server)) (eval-safely-in-slave form)))) ;;; EVAL-FORM-IN-SERVER -- Public. ;;; (defun eval-form-in-server (server-info form &optional (package (package-at-point))) "This evals form, a simple-string, in the server for server-info. Package is the name of the package in which the server reads form, and it defaults to the value of \"Current Package\". If package is nil, then the slave uses the value of *package*. If server is busy with other requests, this signals an editor-error to prevent commands using this from hanging. If the server dies while evaluating form, then this signals an editor-error. This returns a list of strings which are the printed representation of all the values returned by form in the server." (declare (simple-string form)) (when (server-info-notes server-info) (editor-error "Server ~S is currently busy. See \"List Operations\"." (server-info-name server-info))) (multiple-value-bind (values error) (hemlock.wire:remote-value (server-info-wire server-info) (server-eval-form package form)) (when error (editor-error "The server died before finishing")) values)) ;;; EVAL-FORM-IN-SERVER-1 -- Public. ;;; We use VALUES to squelch the second value of READ - FROM - STRING . ;;; (defun eval-form-in-server-1 (server-info form &optional (package (package-at-point))) "This calls EVAL-FORM-IN-SERVER and returns the result of READ'ing from the first string EVAL-FORM-IN-SERVER returns." (values (read-from-string (car (eval-form-in-server server-info form package))))) (defun string-eval (string &key (server (get-current-eval-server)) (package (package-at-point)) (context (format nil "evaluation of ~S" string))) "Queues the evaluation of string on an eval server. String is a simple string. If package is not supplied, the string is eval'ed in the slave's current package." (declare (simple-string string)) (queue-note (make-note :kind :eval :context context :package package :text string) server) (values)) (defun region-eval (region &key (server (get-current-eval-server)) (package (package-at-point)) (context (region-context region "evaluation"))) "Queues the evaluation of a region of text on an eval server. If package is not supplied, the string is eval'ed in the slave's current package." (let ((region (region (copy-mark (region-start region) :left-inserting) (copy-mark (region-end region) :left-inserting)))) (queue-note (make-note :kind :eval :context context :region region :package package :text (region-to-string region)) server)) (values)) (defun region-compile (region &key (server (get-current-eval-server)) (package (package-at-point))) "Queues a compilation on an eval server. If package is not supplied, the string is eval'ed in the slave's current package." (let* ((region (region (copy-mark (region-start region) :left-inserting) (copy-mark (region-end region) :left-inserting))) (buf (line-buffer (mark-line (region-start region)))) (pn (and buf (buffer-pathname buf))) (defined-from (if pn (namestring pn) "unknown"))) (queue-note (make-note :kind :compile :context (region-context region "compilation") :buffer (and region (region-start region) (mark-line (region-start region)) (line-buffer (mark-line (region-start region)))) :region region :package package :text (region-to-string region) :input-file defined-from) server)) (values)) ;;;; File compiling noise. (defhvar "Remote Compile File" "When set (the default), this causes slave file compilations to assume the compilation is occurring on a remote machine. This means the source file must be world readable. Unsetting this, causes no file accesses to go through the super root." :value nil) ;;; FILE-COMPILE compiles files in a client Lisp. Because of Unix file ;;; protection, one cannot write files over the net unless they are publicly ;;; writeable. To get around this, we create a temporary file that is ;;; publicly writeable for compiler output. This file is renamed to an ;;; ordinary output name if the compiler wrote anything to it, or deleted ;;; otherwise. No temporary file is created when output-file is not t. ;;; (defun file-compile (file &key buffer (output-file t) error-file lap-file load (server (get-current-compile-server)) (package (package-at-point))) "Compiles file in a client Lisp. When output-file is t, a temporary output file is used that is publicly writeable in case the client is on another machine. This file is renamed or deleted after compilation. Setting \"Remote Compile File\" to nil, inhibits this. If package is not supplied, the string is eval'ed in the slave's current package." (let* ((file (truename file)) ; in case of search-list in pathname. (namestring (namestring file)) (note (make-note :kind :compile-file :context (format nil "compilation of ~A" namestring) :buffer buffer :region nil :package package :input-file file :output-file output-file :error-file error-file :lap-file lap-file :load load))) (when (and (value remote-compile-file) (eq output-file t)) (multiple-value-bind (net-infile ofile net-ofile date) (file-compile-temp-file file) (setf (note-net-input-file note) net-infile) (setf (note-output-file note) ofile) (setf (note-net-output-file note) net-ofile) (setf (note-output-date note) date))) (clear-server-errors server #'(lambda (error) (eq (error-info-buffer error) buffer))) (queue-note note server))) ;;; FILE-COMPILE-TEMP-FILE creates a a temporary file that is publicly writable in the directory file is in and with a .fasl type . Four values ;;; are returned -- a pathname suitable for referencing file remotely, the ;;; pathname of the temporary file created, a pathname suitable for referencing ;;; the temporary file remotely, and the write date of the temporary file. ;;; #+NILGB (defun file-compile-temp-file (file) (let ((ofile (loop (let* ((sym (gensym)) (f (merge-pathnames (format nil "compile-file-~A.fasl" sym) file))) (unless (probe-file f) (return f)))))) (multiple-value-bind (fd err) (unix:unix-open (namestring ofile) unix:o_creat #o666) (unless fd (editor-error "Couldn't create compiler temporary output file:~%~ ~A" (unix:get-unix-error-msg err))) (unix:unix-fchmod fd #o666) (unix:unix-close fd)) (let ((net-ofile (pathname-for-remote-access ofile))) (values (make-pathname :directory (pathname-directory net-ofile) :defaults file) ofile net-ofile (file-write-date ofile))))) (defun pathname-for-remote-access (file) (let* ((machine (machine-instance)) (usable-name (nstring-downcase (the simple-string (subseq machine 0 (position #\. machine)))))) (declare (simple-string machine usable-name)) (make-pathname :directory (concatenate 'simple-string "/../" usable-name (directory-namestring file)) :defaults file))) ;;; REGION-CONTEXT -- internal ;;; ;;; Return a string which describes the code in a region. Thing is the ;;; thing being done to the region. "compilation" or "evaluation"... (defun region-context (region thing) (declare (simple-string thing)) (pre-command-parse-check (region-start region)) (let ((start (region-start region))) (with-mark ((m1 start)) (unless (start-defun-p m1) (top-level-offset m1 1)) (with-mark ((m2 m1)) (mark-after m2) (form-offset m2 2) (format nil "~A of ~S" thing (if (eq (mark-line m1) (mark-line m2)) (region-to-string (region m1 m2)) (concatenate 'simple-string (line-string (mark-line m1)) "..."))))))) ;;;; Commands (Gosh, wow gee!) (defcommand "Editor Server Name" (p) "Echos the editor server's name which can be supplied with the -slave switch to connect to a designated editor." "Echos the editor server's name which can be supplied with the -slave switch to connect to a designated editor." (declare (ignore p)) (if *editor-name* (message "This editor is named ~S." *editor-name*) (message "This editor is not currently named."))) (defun invoke-with-save-excursion (fn) (let* ((point (current-point)) (point-pos (mark-charpos point))) (unwind-protect (funcall fn) (move-to-position point point-pos)))) (defmacro save-excursion (&body body) `(invoke-with-save-excursion (lambda () ,@body))) (defclass slave-symbol (hemlock.wire::serializable-object) ((package-name :initarg :package-name :accessor slave-symbol-package-name) (name :initarg :name :accessor slave-symbol-name))) (defmethod hemlock.wire::serialize ((x slave-symbol)) (values 'slave-symbol (list (coerce (slave-symbol-package-name x) 'simple-string) (coerce (slave-symbol-name x) 'simple-string)))) (defmethod hemlock.wire::deserialize-with-type ((type (eql 'slave-symbol)) data) (destructuring-bind (package-name symbol-name) data (make-slave-symbol symbol-name package-name))) (defmethod print-object ((object slave-symbol) stream) (flet ((% () (format stream "~A:~A" (slave-symbol-package-name object) (slave-symbol-name object)))) (if *print-escape* (print-unreadable-object (object stream :type t :identity nil) (%)) (%)))) (defmethod slave-symbol-name ((x symbol)) (symbol-name x)) (defmethod slave-symbol-package-name ((x symbol)) (package-name (symbol-package x))) (defun resolve-slave-symbol (slave-symbol &optional (if-does-not-exist :intern) (if-does-not-exist-value nil)) (with-slots (name package-name) slave-symbol (let ((package (find-package package-name))) (cond ((null package) if-does-not-exist-value) ((and (eq package (find-package :cl)) (equal name (symbol-name nil))) nil) ((find-symbol name package)) (t (ecase if-does-not-exist (:intern (intern name package)) (:error (error "symbol does not exist in this lisp: ~A:~A" package-name name)) ((nil) if-does-not-exist-value))))))) (defun make-slave-symbol (name &optional package) (multiple-value-bind (name package) (if (symbolp name) (values (symbol-name name) (symbol-package name)) (values name package)) (make-instance 'slave-symbol :package-name (etypecase package (package (package-name package)) (string package) (null (or (package-at-point) (symbol-name :common-lisp)))) :name name))) (defun casify-char (char) "Convert CHAR accoring to readtable-case." #-scl (char-upcase char) #+scl (if (eq ext:*case-mode* :upper) (char-upcase char) (char-downcase char)) ;; fixme: need to do this on the slave side #+nil (ecase (readtable-case *readtable*) (:preserve char) (:upcase (char-upcase char)) (:downcase (char-downcase char)) (:invert (if (upper-case-p char) (char-downcase char) (char-upcase char))))) (defun tokenize-symbol-thoroughly (string) "This version of TOKENIZE-SYMBOL handles escape characters." (let ((package nil) (token (make-array (length string) :element-type 'character :fill-pointer 0)) (backslash nil) (vertical nil) (internp nil)) (loop for char across string do (cond (backslash (vector-push-extend char token) (setq backslash nil)) ((char= char #\\) ; Quotes next character, even within |...| (setq backslash t)) ((char= char #\|) (setq vertical t)) (vertical (vector-push-extend char token)) ((char= char #\:) (if package (setq internp t) (setq package token token (make-array (length string) :element-type 'character :fill-pointer 0)))) (t (vector-push-extend (casify-char char) token)))) (values token package (or (not package) internp)))) ;; adapted from swank (defun parse-slave-symbol (string &optional package) (multiple-value-bind (sname pname) (tokenize-symbol-thoroughly string) (when (plusp (length sname)) (make-slave-symbol sname (cond ((equal pname "") (symbol-name :keyword)) (pname (canonicalize-slave-package-name pname)) (t package)))))) (defun slave-symbol-at-point () (parse-slave-symbol (symbol-string-at-point))) (defun symbol-string-at-point () (with-mark ((mark1 (current-point)) (mark2 (current-point))) (mark-symbol mark1 mark2) (region-to-string (region mark1 mark2)))) (defun canonicalize-slave-package-name (str) (cl-ppcre:regex-replace "^SB!" (canonical-case str) "SB-")) (defun package-at-point () (hi::tag-package (hi::line-tag (mark-line (current-point))))) (defcommand "Set Buffer Package" (p) "Set the package to be used by Lisp evaluation and compilation commands while in this buffer. When in a slave's interactive buffers, do NOT set the editor's package variable, but changed the slave's *package*." "Prompt for a package to make into a buffer-local variable current-package." (declare (ignore p)) (let* ((name (string (prompt-for-expression :prompt "Package name: " :help "Name of package to associate with this buffer."))) (buffer (current-buffer)) (info (value current-eval-server))) (cond ((and info (or (eq (server-info-slave-buffer info) buffer) (eq (server-info-background-buffer info) buffer))) (hemlock.wire:remote (server-info-wire info) (server-set-package name)) (hemlock.wire:wire-force-output (server-info-wire info))) #+nil ((eq buffer *selected-eval-buffer*) (setf *package* (maybe-make-package name))) (t (defhvar "Current Package" "The package used for evaluation of Lisp in this buffer." :buffer buffer :value name))) (when (buffer-modeline-field-p buffer :package) (dolist (w (buffer-windows buffer)) (update-modeline-field buffer w :package))))) (defcommand "Current Compile Server" (p) "Echos the current compile server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." "Echos the current compile server's name. With prefix argument, shows global one." (let ((info (if p (variable-value 'current-compile-server :global) (value current-compile-server)))) (if info (message "~A" (server-info-name info)) (message "No ~:[current~;global~] compile server." p)))) (defcommand "Set Compile Server" (p) "Specifies the name of the server used globally for file compilation requests." "Call select-current-compile-server." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (setf (variable-value 'current-compile-server :global) (maybe-create-server)))) (defcommand "Set Buffer Compile Server" (p) "Specifies the name of the server used for file compilation requests in the current buffer." "Call select-current-compile-server after making a buffer local variable." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (defhvar "Current Compile Server" "The Server-Info object for the server currently used for compilation requests." :buffer (current-buffer) :value (maybe-create-server)))) (defcommand "Current Eval Server" (p) "Echos the current eval server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." "Echos the current eval server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." (let ((info (if p (variable-value 'current-eval-server :global) (value current-eval-server)))) (if info (message "~A" (server-info-name info)) (message "No ~:[current~;global~] eval server." p)))) (defcommand "Set Eval Server" (p) "Specifies the name of the server used globally for evaluation and compilation requests." "Call select-current-server." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (setf (variable-value 'current-eval-server :global) (maybe-create-server)))) (defcommand "Set Buffer Eval Server" (p) "Specifies the name of the server used for evaluation and compilation requests in the current buffer." "Call select-current-server after making a buffer local variable." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (defhvar "Current Eval Server" "The Server-Info for the eval server used in this buffer." :buffer (current-buffer) :value (maybe-create-server)))) (defcommand "Evaluate Defun" (p) "Evaluates the current or next top-level form. If the current region is active, then evaluate it." "Evaluates the current or next top-level form." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluate Defun in the editor Lisp ...") (editor-evaluate-defun-command nil)) ((region-active-p) (evaluate-region-command nil)) (t (region-eval (defun-region (current-point))))))) (defcommand "Re-evaluate Defvar" (p) "Evaluate the current or next top-level form if it is a DEFVAR. Treat the form as if the variable is not bound." "Evaluate the current or next top-level form if it is a DEFVAR. Treat the form as if the variable is not bound." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Re-evaluate Defvar in the editor Lisp ...") (editor-re-evaluate-defvar-command nil)) (t (let* ((form (defun-region (current-point))) (start (region-start form))) (with-mark ((var-start start) (var-end start)) (mark-after var-start) (form-offset var-start 1) (form-offset (move-mark var-end var-start) 1) (let ((exp (concatenate 'simple-string "(makunbound '" (region-to-string (region var-start var-end)) ")"))) (eval-form-in-server (get-current-eval-server) exp))) (region-eval form)))))) ;;; We use Prin1-To-String in the client so that the expansion gets pretty ;;; printed. Since the expansion can contain unreadable stuff, we can't expect ;;; to be able to read that string back in the editor. We shove the region at the client as a string , so it can read from the string with the ;;; right package environment. ;;; (defcommand "Macroexpand Expression" (p) "Show the macroexpansion of the current expression in the null environment. With an argument, use MACROEXPAND instead of MACROEXPAND-1." "Show the macroexpansion of the current expression in the null environment. With an argument, use MACROEXPAND instead of MACROEXPAND-1." (let ((info (value current-eval-server))) (cond ((not info) (message "Macroexpand Expression in the editor Lisp ...") (editor-macroexpand-expression-command nil)) (t (let ((point (current-point))) (with-mark ((start point)) (pre-command-parse-check start) (with-mark ((end start)) (unless (form-offset end 1) (editor-error)) (let ((package (package-at-point))) (with-pop-up-display (s) (write-string (eval-form-in-server-1 (get-current-eval-server) (format nil "(prin1-to-string (~S (read-from-string ~S)))" (if p 'macroexpand 'macroexpand-1) (region-to-string (region start end))) package) s)))))))))) (defcommand "Evaluate Expression" (p) "Prompt for an expression to evaluate." "Prompt for an expression to evaluate." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluate Expression in the editor Lisp ...") (editor-evaluate-expression-command nil)) (t (let ((exp (prompt-for-string :prompt "Eval: " :help "Expression to evaluate."))) (message "=> ~{~#[~;~A~:;~A, ~]~}" (eval-form-in-server (get-current-eval-server) exp))))))) (defcommand "Compile Defun" (p) "Compiles the current or next top-level form. First the form is evaluated, then the result of this evaluation is passed to compile. If the current region is active, compile the region." "Evaluates the current or next top-level form." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compiling in the editor Lisp ...") (editor-compile-defun-command nil)) ((region-active-p) (compile-region-command nil)) (t (region-compile (defun-region (current-point))))))) (defcommand "Compile Region" (p) "Compiles lisp forms between the point and the mark." "Compiles lisp forms between the point and the mark." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compiling in the editor Lisp ...") (editor-compile-region-command nil)) (t (region-compile (current-region)))))) (defcommand "Evaluate Region" (p) "Evaluates lisp forms between the point and the mark." "Evaluates lisp forms between the point and the mark." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluating region in the editor Lisp ...") (editor-evaluate-region-command nil)) (t (region-eval (current-region)))))) (defcommand "Evaluate Buffer" (p) "Evaluates the text in the current buffer." "Evaluates the text in the current buffer redirecting *Standard-Output* to the echo area. The prefix argument is ignored." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluating buffer in the editor Lisp ...") (editor-evaluate-buffer-command nil)) (t (let ((b (current-buffer))) (region-eval (buffer-region b) :context (format nil "evaluation of buffer ``~A''" (buffer-name b)))))))) (defcommand "Load File" (p) "Prompt for a file to load into the current eval server." "Prompt for a file to load into the current eval server." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Load File in the editor Lisp ...") (editor-load-file-command nil)) (t (let ((name (truename (prompt-for-file :default (or (value load-pathname-defaults) (buffer-default-pathname (current-buffer))) :prompt "File to load: " :help "The name of the file to load")))) (setv load-pathname-defaults name) (string-eval (format nil "(load ~S)" (namestring (if (value remote-compile-file) (pathname-for-remote-access name) name))))))))) (defcommand "Compile File" (p) "Prompts for file to compile. Does not compare source and binary write dates. Does not check any buffer for that file for whether the buffer needs to be saved." "Prompts for file to compile." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compile File in the editor Lisp ...") (editor-compile-file-command nil)) (t (let ((pn (prompt-for-file :default (buffer-default-pathname (current-buffer)) :prompt "File to compile: "))) (file-compile pn)))))) (defhvar "Compile Buffer File Confirm" "When set, \"Compile Buffer File\" prompts before doing anything." :value nil) (defcommand "Compile Buffer File" (p) "Compile the file in the current buffer if its associated binary file (of type .fasl) is older than the source or doesn't exist. When the binary file is up to date, the user is asked if the source should be compiled anyway. When the prefix argument is supplied, compile the file without checking the binary file. When \"Compile Buffer File Confirm\" is set, this command will ask for confirmation when it otherwise would not." "Compile the file in the current buffer if the fasl file isn't up to date. When p, always do it." (let ((info (value current-eval-server))) (cond ((not info) (message "Compile Buffer File in the editor Lisp ...") (editor-compile-buffer-file-command nil)) (t (let* ((buf (current-buffer)) (pn (buffer-pathname buf))) (unless pn (editor-error "Buffer has no associated pathname.")) (cond ((buffer-modified buf) (when (or (not (value compile-buffer-file-confirm)) (prompt-for-y-or-n :default t :default-string "Y" :prompt (list "Save and compile file ~A? " (namestring pn)))) (write-buffer-file buf pn) (file-compile pn :buffer buf))) ((older-or-non-existent-fasl-p pn p) (when (or (not (value compile-buffer-file-confirm)) (prompt-for-y-or-n :default t :default-string "Y" :prompt (list "Compile file ~A? " (namestring pn)))) (file-compile pn :buffer buf))) ((or p (prompt-for-y-or-n :default t :default-string "Y" :prompt "Fasl file up to date, compile source anyway? ")) (file-compile pn :buffer buf)))))))) (defcommand "Compile Group" (p) "Compile each file in the current group which needs it. If a file has type LISP and there is a curresponding file with type FASL which has been written less recently (or it doesn't exit), then the file is compiled, with error output directed to the \"Compiler Warnings\" buffer. If a prefix argument is provided, then all the files are compiled. All modified files are saved beforehand." "Do a Compile-File in each file in the current group that seems to need it." (let ((info (value current-eval-server))) (cond ((not info) (message "Compile Group in the editor Lisp ...") (editor-compile-group-command nil)) (t (save-all-files-command ()) (unless *active-file-group* (editor-error "No active file group.")) (dolist (file *active-file-group*) (when (string-equal (pathname-type file) "lisp") (let ((tn (probe-file file))) (cond ((not tn) (message "File ~A not found." (namestring file))) ((older-or-non-existent-fasl-p tn p) (file-compile tn)))))))))) ;;;; Error hacking stuff. (defcommand "Flush Compiler Error Information" (p) "Flushes all infomation about errors encountered while compiling using the current server" "Flushes all infomation about errors encountered while compiling using the current server" (declare (ignore p)) (clear-server-errors (get-current-compile-server t))) (defcommand "Next Compiler Error" (p) "Move to the next compiler error for the current server. If an argument is given, advance that many errors." "Move to the next compiler error for the current server. If an argument is given, advance that many errors." (let* ((server (get-current-compile-server t)) (errors (server-info-errors server)) (fp (fill-pointer errors))) (when (zerop fp) (editor-error "There are no compiler errors.")) (let* ((old-index (server-info-error-index server)) (new-index (+ (or old-index -1) (or p 1)))) (when (< new-index 0) (if old-index (editor-error "Can't back up ~R, only at the ~:R compiler error." (- p) (1+ old-index)) (editor-error "Not even at the first compiler error."))) (when (>= new-index fp) (if (= (1+ (or old-index -1)) fp) (editor-error "No more compiler errors.") (editor-error "Only ~R remaining compiler error~:P." (- fp old-index 1)))) (setf (server-info-error-index server) new-index) ;; Display the silly error. (let ((error (aref errors new-index))) (let ((region (error-info-region error))) (if region (let* ((start (region-start region)) (buffer (line-buffer (mark-line start)))) (change-to-buffer buffer) (move-mark (buffer-point buffer) start)) (message "Hmm, no region for this error."))) (let* ((line (error-info-line error)) (buffer (line-buffer line))) (if (and line (bufferp buffer)) (let ((mark (mark line 0))) (unless (buffer-windows buffer) (let ((window (find-if-not #'(lambda (window) (or (eq window (current-window)) (eq window *echo-area-window*))) *window-list*))) (if window (setf (window-buffer window) buffer) (make-window mark)))) (move-mark (buffer-point buffer) mark) (dolist (window (buffer-windows buffer)) (move-mark (window-display-start window) mark) (move-mark (window-point window) mark)) (delete-mark mark)) (message "Hmm, no line for this error."))))))) (defcommand "Previous Compiler Error" (p) "Move to the previous compiler error. If an argument is given, move back that many errors." "Move to the previous compiler error. If an argument is given, move back that many errors." (next-compiler-error-command (- (or p 1)))) ;;;; Operation management commands: (defcommand "Abort Operations" (p) "Abort all operations on current eval server connection." "Abort all operations on current eval server connection." (declare (ignore p)) (let* ((server (get-current-eval-server)) (wire (server-info-wire server))) ;; Tell the slave to abort the current operation and to ignore any further ;; operations. (dolist (note (server-info-notes server)) (setf (note-state note) :aborted)) #+NILGB (ext:send-character-out-of-band (hemlock.wire:wire-fd wire) #\N) (hemlock.wire:remote-value wire (server-accept-operations)) ;; Synch'ing with server here, causes any operations queued at the socket or ;; in the server to be ignored, and the last thing evaluated is an ;; instruction to go on accepting operations. (hemlock.wire:wire-force-output wire) (dolist (note (server-info-notes server)) (when (eq (note-state note) :pending) The HEMLOCK.WIRE : REMOTE - VALUE call should have allowed a handshake to ;; tell the editor anything :pending was aborted. (error "Operation ~S is still around after we aborted it?" note))) ;; Forget anything queued in the editor. (setf (server-info-notes server) nil))) (defcommand "List Operations" (p) "List all eval server operations which have not yet completed." "List all eval server operations which have not yet completed." (declare (ignore p)) (let ((notes nil)) ;; Collect all notes, reversing them since they act like a queue but ;; are not in queue order. (do-strings (str val *server-names*) (declare (ignore str)) (setq notes (nconc notes (reverse (server-info-notes val))))) (if notes (with-pop-up-display (s) (dolist (note notes) (format s "~@(~8A~) ~A on ~A.~%" (note-state note) (note-context note) (server-info-name (note-server note))))) (message "No uncompleted operations."))) (values)) ;;;; Describing in the client lisp. " Describe Function Call " gets the function name from the current form ;;; as a string. This string is used as the argument to a call to ;;; DESCRIBE-FUNCTION-CALL-AUX which is eval'ed in the client lisp. The ;;; auxiliary function's name is qualified since it is read in the client ;;; Lisp with *package* bound to the buffer's package. The result comes back as a list of strings , so we read the first string to get out the string value returned by DESCRIBE - FUNCTION - CALL - AUX in the client . ;;; (defcommand "Describe Function Call" (p) "Describe the current function call." "Describe the current function call." (let ((info (value current-eval-server))) (cond ((not info) (message "Describing from the editor Lisp ...") (editor-describe-function-call-command p)) (t (with-mark ((mark1 (current-point)) (mark2 (current-point))) (pre-command-parse-check mark1) (unless (backward-up-list mark1) (editor-error)) (form-offset (move-mark mark2 (mark-after mark1)) 1) (let* ((package (package-at-point)) (package-exists (eval-form-in-server-1 info (format nil "(if (find-package ~S) t (package-name *package*))" package) nil))) (unless (eq package-exists t) (message "Using package ~S in ~A since ~ ~:[there is no current package~;~:*~S does not exist~]." package-exists (server-info-name info) package)) (with-pop-up-display (s) (write-string (eval-form-in-server-1 info (format nil "(hemlock::describe-function-call-aux ~S)" (region-to-string (region mark1 mark2))) (if (eq package-exists t) package nil)) s)))))))) ;;; DESCRIBE-FUNCTION-CALL-AUX is always evaluated in a client Lisp to some ;;; editor, relying on the fact that the cores have the same functions. String ;;; is the name of a function that is read (in the client Lisp). The result is ;;; a string of all the output from EDITOR-DESCRIBE-FUNCTION. ;;; (defun describe-function-call-aux (string) (let* ((sym (read-from-string string)) (fun (function-to-describe sym error))) (with-output-to-string (*standard-output*) (editor-describe-function fun sym)))) " Describe Symbol " gets the symbol name and quotes it as the argument to a ;;; call to DESCRIBE-SYMBOL-AUX which is eval'ed in the client lisp. The ;;; auxiliary function's name is qualified since it is read in the client Lisp ;;; with *package* bound to the buffer's package. The result comes back as a list of strings , so we read the first string to get out the string value returned by DESCRIBE - SYMBOL - AUX in the client . ;;; (defcommand "Describe Symbol" (p) "Describe the previous s-expression if it is a symbol." "Describe the previous s-expression if it is a symbol." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Describing from the editor Lisp ...") (editor-describe-symbol-command nil)) (t (with-mark ((mark1 (current-point)) (mark2 (current-point))) (mark-symbol mark1 mark2) (let ((package (package-at-point))) (with-pop-up-display (s) (write-string (eval-form-in-server-1 info (format nil "(hemlock::describe-symbol-aux '~A)" (region-to-string (region mark1 mark2))) package) s)))))))) (defun describe-symbol-aux (thing) (with-output-to-string (*standard-output*) (describe (if (and (consp thing) (or (eq (car thing) 'quote) (eq (car thing) 'function)) (symbolp (cadr thing))) (cadr thing) thing))))
null
https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/src/lispeval.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- ********************************************************************** ********************************************************************** This file contains code for sending requests to eval servers and the commands based on that code. The note structure holds everything we need to know about an operation. Not all operations use all the available fields. :unsent, :pending, :running, :aborted or :dead. Short string describing what this op is doing. Either :eval, :compile, or :compile-file Buffer source came from. Region of request Package or NIL if none string containing request File to compile or where stuff was found Net version of above. Temporary output file for compiler fasl code. Net version of above Temp-file is created before calling compiler, and this is its write date. The lap file for compiles The file to dump errors into Load compiled file or not? Count of compiler errors. Count of compiler warnings. Count of compiler notes. Note support routines. QUEUE-NOTE -- Internal. This queues note for server. SERVER-INFO-NOTES keeps notes in stack order, not queue order. We also link the note to the server and try to send it to the server. If we didn't send this note, we tell the user the server is busy and that we're queuing his note to be sent later. MAYBE-SEND-NEXT-NOTE -- Internal. Loop over all notes in server. If we see any :pending or :running, then punt since we can't send one. Otherwise, by the end of the list, we may have found an :unsent one, and if we did, next will be the last :unsent note. Remember, SERVER-INFO-NOTES is kept in stack order not queue order. Stuff to send noise to the server. EVAL-FORM-IN-SERVER -- Public. EVAL-FORM-IN-SERVER-1 -- Public. File compiling noise. FILE-COMPILE compiles files in a client Lisp. Because of Unix file protection, one cannot write files over the net unless they are publicly writeable. To get around this, we create a temporary file that is publicly writeable for compiler output. This file is renamed to an ordinary output name if the compiler wrote anything to it, or deleted otherwise. No temporary file is created when output-file is not t. in case of search-list in pathname. FILE-COMPILE-TEMP-FILE creates a a temporary file that is publicly are returned -- a pathname suitable for referencing file remotely, the pathname of the temporary file created, a pathname suitable for referencing the temporary file remotely, and the write date of the temporary file. REGION-CONTEXT -- internal Return a string which describes the code in a region. Thing is the thing being done to the region. "compilation" or "evaluation"... Commands (Gosh, wow gee!) fixme: need to do this on the slave side Quotes next character, even within |...| adapted from swank We use Prin1-To-String in the client so that the expansion gets pretty printed. Since the expansion can contain unreadable stuff, we can't expect to be able to read that string back in the editor. We shove the region right package environment. Error hacking stuff. Display the silly error. Operation management commands: Tell the slave to abort the current operation and to ignore any further operations. Synch'ing with server here, causes any operations queued at the socket or in the server to be ignored, and the last thing evaluated is an instruction to go on accepting operations. tell the editor anything :pending was aborted. Forget anything queued in the editor. Collect all notes, reversing them since they act like a queue but are not in queue order. Describing in the client lisp. as a string. This string is used as the argument to a call to DESCRIBE-FUNCTION-CALL-AUX which is eval'ed in the client lisp. The auxiliary function's name is qualified since it is read in the client Lisp with *package* bound to the buffer's package. The result comes ~:*~S does not exist~]." DESCRIBE-FUNCTION-CALL-AUX is always evaluated in a client Lisp to some editor, relying on the fact that the cores have the same functions. String is the name of a function that is read (in the client Lisp). The result is a string of all the output from EDITOR-DESCRIBE-FUNCTION. call to DESCRIBE-SYMBOL-AUX which is eval'ed in the client lisp. The auxiliary function's name is qualified since it is read in the client Lisp with *package* bound to the buffer's package. The result comes back as a
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . Written by and . (in-package :hemlock) (defstruct (note (:print-function %print-note)) Server - Info for the server this op is on . (defun %print-note (note stream d) (declare (ignore d)) (format stream "#<Eval-Server-Note for ~A [~A]>" (note-context note) (note-state note))) (defun queue-note (note server) (push note (server-info-notes server)) (setf (note-server note) server) (maybe-send-next-note server) (when (eq (note-state note) :unsent) (message "Server ~A busy, ~A queued." (server-info-name server) (note-context note)))) (defun maybe-send-next-note (server) (let ((busy nil) (next nil)) (dolist (note (server-info-notes server)) (ecase (note-state note) ((:pending :running) (setf busy t) (return)) (:unsent (setf next note)) (:aborted :dead))) (when (and (not busy) next) (send-note next)))) (defun send-note (note) (let* ((remote (hemlock.wire:make-remote-object note)) (server (note-server note)) (ts (server-info-slave-info server)) (bg (server-info-background-info server)) (wire (server-info-wire server))) (setf (note-state note) :pending) (message "Sending ~A." (note-context note)) (case (note-kind note) (:eval (hemlock.wire:remote wire (server-eval-text remote (note-package note) (note-text note) (and ts (ts-data-stream ts))))) (:compile (hemlock.wire:remote wire (server-compile-text remote (note-package note) (note-text note) (note-input-file note) (and ts (ts-data-stream ts)) (and bg (ts-data-stream bg))))) (:compile-file (macrolet ((frob (x) `(if (pathnamep ,x) (namestring ,x) ,x))) (hemlock.wire:remote wire (server-compile-file remote (note-package note) (frob (or (note-net-input-file note) (note-input-file note))) (frob (or (note-net-output-file note) (note-output-file note))) (frob (note-error-file note)) (frob (note-lap-file note)) (note-load note) (and ts (ts-data-stream ts)) (and bg (ts-data-stream bg)))))) (t (error "Unknown note kind ~S" (note-kind note)))) (hemlock.wire:wire-force-output wire))) Server Callbacks . (defun operation-started (note) (let ((note (hemlock.wire:remote-object-value note))) (setf (note-state note) :running) (message "The ~A started." (note-context note))) (values)) (defun eval-form-error (message) (editor-error message)) (defun lisp-error (note start end msg) (declare (ignore start end)) (let ((note (hemlock.wire:remote-object-value note))) (loud-message "During ~A: ~A" (note-context note) msg)) (values)) (defun compiler-error (note start end function severity) (let* ((note (hemlock.wire:remote-object-value note)) (server (note-server note)) (line (mark-line (buffer-end-mark (server-info-background-buffer server)))) (message (format nil "~:(~A~) ~@[in ~A ~]during ~A." severity function (note-context note))) (error (make-error-info :buffer (note-buffer note) :message message :line line))) (message "~A" message) (case severity (:error (incf (note-errors note))) (:warning (incf (note-warnings note))) (:note (incf (note-notes note)))) (let ((region (case (note-kind note) (:compile (note-region note)) (:compile-file (let ((buff (note-buffer note))) (and buff (buffer-region buff)))) (t (error "Compiler error in ~S?" note))))) (when region (let* ((region-end (region-end region)) (m1 (copy-mark (region-start region) :left-inserting)) (m2 (copy-mark m1 :left-inserting))) (when start (character-offset m1 start) (when (mark> m1 region-end) (move-mark m1 region-end))) (unless (and end (character-offset m2 end)) (move-mark m2 region-end)) (setf (error-info-region error) (region m1 m2))))) (vector-push-extend error (server-info-errors server))) (values)) (defun eval-text-result (note start end values) (declare (ignore note start end)) (message "=> ~{~#[~;~A~:;~A, ~]~}" values) (values)) (defun operation-completed (note abortp) (let* ((note (hemlock.wire:remote-object-value note)) (server (note-server note)) (file (note-output-file note))) (hemlock.wire:forget-remote-translation note) (setf (note-state note) :dead) (setf (server-info-notes server) (delete note (server-info-notes server) :test #'eq)) (setf (note-server note) nil) (if abortp (loud-message "The ~A aborted." (note-context note)) (let ((errors (note-errors note)) (warnings (note-warnings note)) (notes (note-notes note))) (message "The ~A complete.~ ~@[ ~D error~:P~]~@[ ~D warning~:P~]~@[ ~D note~:P~]" (note-context note) (and (plusp errors) errors) (and (plusp warnings) warnings) (and (plusp notes) notes)))) (let ((region (note-region note))) (when (regionp region) (delete-mark (region-start region)) (delete-mark (region-end region)) (setf (note-region note) nil))) (when (and (eq (note-kind note) :compile-file) (not (eq file t)) file) (if (> (file-write-date file) (note-output-date note)) (let ((new-name (make-pathname :type "fasl" :defaults (note-input-file note)))) (rename-file file new-name) #+NILGB (unix:unix-chmod (namestring new-name) #o644)) (delete-file file))) (maybe-send-next-note server)) (values)) fixme : these two should be the same (defun eval-safely-in-slave (form) (handler-case (eval form) (error (c) (warn "ignoring error in slave request: ~A" c)))) (defun eval-safely-in-master (form) (let (ok) (block nil (unwind-protect (multiple-value-prog1 (eval form) (setf ok t)) (unless ok (return "fell through)")))))) (defvar *synchronous-evaluation-of-slave-requests-in-the-master* nil) (defun eval-in-master (form) (if *synchronous-evaluation-of-slave-requests-in-the-master* (eval form) (hemlock.wire:remote hemlock.wire::*current-wire* (eval-safely-in-master form)))) (defun eval-in-slave (form) (if *synchronous-evaluation-of-slave-requests-in-the-master* (eval form) (hemlock.wire:remote (server-info-wire (get-current-eval-server)) (eval-safely-in-slave form)))) (defun eval-form-in-server (server-info form &optional (package (package-at-point))) "This evals form, a simple-string, in the server for server-info. Package is the name of the package in which the server reads form, and it defaults to the value of \"Current Package\". If package is nil, then the slave uses the value of *package*. If server is busy with other requests, this signals an editor-error to prevent commands using this from hanging. If the server dies while evaluating form, then this signals an editor-error. This returns a list of strings which are the printed representation of all the values returned by form in the server." (declare (simple-string form)) (when (server-info-notes server-info) (editor-error "Server ~S is currently busy. See \"List Operations\"." (server-info-name server-info))) (multiple-value-bind (values error) (hemlock.wire:remote-value (server-info-wire server-info) (server-eval-form package form)) (when error (editor-error "The server died before finishing")) values)) We use VALUES to squelch the second value of READ - FROM - STRING . (defun eval-form-in-server-1 (server-info form &optional (package (package-at-point))) "This calls EVAL-FORM-IN-SERVER and returns the result of READ'ing from the first string EVAL-FORM-IN-SERVER returns." (values (read-from-string (car (eval-form-in-server server-info form package))))) (defun string-eval (string &key (server (get-current-eval-server)) (package (package-at-point)) (context (format nil "evaluation of ~S" string))) "Queues the evaluation of string on an eval server. String is a simple string. If package is not supplied, the string is eval'ed in the slave's current package." (declare (simple-string string)) (queue-note (make-note :kind :eval :context context :package package :text string) server) (values)) (defun region-eval (region &key (server (get-current-eval-server)) (package (package-at-point)) (context (region-context region "evaluation"))) "Queues the evaluation of a region of text on an eval server. If package is not supplied, the string is eval'ed in the slave's current package." (let ((region (region (copy-mark (region-start region) :left-inserting) (copy-mark (region-end region) :left-inserting)))) (queue-note (make-note :kind :eval :context context :region region :package package :text (region-to-string region)) server)) (values)) (defun region-compile (region &key (server (get-current-eval-server)) (package (package-at-point))) "Queues a compilation on an eval server. If package is not supplied, the string is eval'ed in the slave's current package." (let* ((region (region (copy-mark (region-start region) :left-inserting) (copy-mark (region-end region) :left-inserting))) (buf (line-buffer (mark-line (region-start region)))) (pn (and buf (buffer-pathname buf))) (defined-from (if pn (namestring pn) "unknown"))) (queue-note (make-note :kind :compile :context (region-context region "compilation") :buffer (and region (region-start region) (mark-line (region-start region)) (line-buffer (mark-line (region-start region)))) :region region :package package :text (region-to-string region) :input-file defined-from) server)) (values)) (defhvar "Remote Compile File" "When set (the default), this causes slave file compilations to assume the compilation is occurring on a remote machine. This means the source file must be world readable. Unsetting this, causes no file accesses to go through the super root." :value nil) (defun file-compile (file &key buffer (output-file t) error-file lap-file load (server (get-current-compile-server)) (package (package-at-point))) "Compiles file in a client Lisp. When output-file is t, a temporary output file is used that is publicly writeable in case the client is on another machine. This file is renamed or deleted after compilation. Setting \"Remote Compile File\" to nil, inhibits this. If package is not supplied, the string is eval'ed in the slave's current package." (namestring (namestring file)) (note (make-note :kind :compile-file :context (format nil "compilation of ~A" namestring) :buffer buffer :region nil :package package :input-file file :output-file output-file :error-file error-file :lap-file lap-file :load load))) (when (and (value remote-compile-file) (eq output-file t)) (multiple-value-bind (net-infile ofile net-ofile date) (file-compile-temp-file file) (setf (note-net-input-file note) net-infile) (setf (note-output-file note) ofile) (setf (note-net-output-file note) net-ofile) (setf (note-output-date note) date))) (clear-server-errors server #'(lambda (error) (eq (error-info-buffer error) buffer))) (queue-note note server))) writable in the directory file is in and with a .fasl type . Four values #+NILGB (defun file-compile-temp-file (file) (let ((ofile (loop (let* ((sym (gensym)) (f (merge-pathnames (format nil "compile-file-~A.fasl" sym) file))) (unless (probe-file f) (return f)))))) (multiple-value-bind (fd err) (unix:unix-open (namestring ofile) unix:o_creat #o666) (unless fd (editor-error "Couldn't create compiler temporary output file:~%~ ~A" (unix:get-unix-error-msg err))) (unix:unix-fchmod fd #o666) (unix:unix-close fd)) (let ((net-ofile (pathname-for-remote-access ofile))) (values (make-pathname :directory (pathname-directory net-ofile) :defaults file) ofile net-ofile (file-write-date ofile))))) (defun pathname-for-remote-access (file) (let* ((machine (machine-instance)) (usable-name (nstring-downcase (the simple-string (subseq machine 0 (position #\. machine)))))) (declare (simple-string machine usable-name)) (make-pathname :directory (concatenate 'simple-string "/../" usable-name (directory-namestring file)) :defaults file))) (defun region-context (region thing) (declare (simple-string thing)) (pre-command-parse-check (region-start region)) (let ((start (region-start region))) (with-mark ((m1 start)) (unless (start-defun-p m1) (top-level-offset m1 1)) (with-mark ((m2 m1)) (mark-after m2) (form-offset m2 2) (format nil "~A of ~S" thing (if (eq (mark-line m1) (mark-line m2)) (region-to-string (region m1 m2)) (concatenate 'simple-string (line-string (mark-line m1)) "..."))))))) (defcommand "Editor Server Name" (p) "Echos the editor server's name which can be supplied with the -slave switch to connect to a designated editor." "Echos the editor server's name which can be supplied with the -slave switch to connect to a designated editor." (declare (ignore p)) (if *editor-name* (message "This editor is named ~S." *editor-name*) (message "This editor is not currently named."))) (defun invoke-with-save-excursion (fn) (let* ((point (current-point)) (point-pos (mark-charpos point))) (unwind-protect (funcall fn) (move-to-position point point-pos)))) (defmacro save-excursion (&body body) `(invoke-with-save-excursion (lambda () ,@body))) (defclass slave-symbol (hemlock.wire::serializable-object) ((package-name :initarg :package-name :accessor slave-symbol-package-name) (name :initarg :name :accessor slave-symbol-name))) (defmethod hemlock.wire::serialize ((x slave-symbol)) (values 'slave-symbol (list (coerce (slave-symbol-package-name x) 'simple-string) (coerce (slave-symbol-name x) 'simple-string)))) (defmethod hemlock.wire::deserialize-with-type ((type (eql 'slave-symbol)) data) (destructuring-bind (package-name symbol-name) data (make-slave-symbol symbol-name package-name))) (defmethod print-object ((object slave-symbol) stream) (flet ((% () (format stream "~A:~A" (slave-symbol-package-name object) (slave-symbol-name object)))) (if *print-escape* (print-unreadable-object (object stream :type t :identity nil) (%)) (%)))) (defmethod slave-symbol-name ((x symbol)) (symbol-name x)) (defmethod slave-symbol-package-name ((x symbol)) (package-name (symbol-package x))) (defun resolve-slave-symbol (slave-symbol &optional (if-does-not-exist :intern) (if-does-not-exist-value nil)) (with-slots (name package-name) slave-symbol (let ((package (find-package package-name))) (cond ((null package) if-does-not-exist-value) ((and (eq package (find-package :cl)) (equal name (symbol-name nil))) nil) ((find-symbol name package)) (t (ecase if-does-not-exist (:intern (intern name package)) (:error (error "symbol does not exist in this lisp: ~A:~A" package-name name)) ((nil) if-does-not-exist-value))))))) (defun make-slave-symbol (name &optional package) (multiple-value-bind (name package) (if (symbolp name) (values (symbol-name name) (symbol-package name)) (values name package)) (make-instance 'slave-symbol :package-name (etypecase package (package (package-name package)) (string package) (null (or (package-at-point) (symbol-name :common-lisp)))) :name name))) (defun casify-char (char) "Convert CHAR accoring to readtable-case." #-scl (char-upcase char) #+scl (if (eq ext:*case-mode* :upper) (char-upcase char) (char-downcase char)) #+nil (ecase (readtable-case *readtable*) (:preserve char) (:upcase (char-upcase char)) (:downcase (char-downcase char)) (:invert (if (upper-case-p char) (char-downcase char) (char-upcase char))))) (defun tokenize-symbol-thoroughly (string) "This version of TOKENIZE-SYMBOL handles escape characters." (let ((package nil) (token (make-array (length string) :element-type 'character :fill-pointer 0)) (backslash nil) (vertical nil) (internp nil)) (loop for char across string do (cond (backslash (vector-push-extend char token) (setq backslash nil)) (setq backslash t)) ((char= char #\|) (setq vertical t)) (vertical (vector-push-extend char token)) ((char= char #\:) (if package (setq internp t) (setq package token token (make-array (length string) :element-type 'character :fill-pointer 0)))) (t (vector-push-extend (casify-char char) token)))) (values token package (or (not package) internp)))) (defun parse-slave-symbol (string &optional package) (multiple-value-bind (sname pname) (tokenize-symbol-thoroughly string) (when (plusp (length sname)) (make-slave-symbol sname (cond ((equal pname "") (symbol-name :keyword)) (pname (canonicalize-slave-package-name pname)) (t package)))))) (defun slave-symbol-at-point () (parse-slave-symbol (symbol-string-at-point))) (defun symbol-string-at-point () (with-mark ((mark1 (current-point)) (mark2 (current-point))) (mark-symbol mark1 mark2) (region-to-string (region mark1 mark2)))) (defun canonicalize-slave-package-name (str) (cl-ppcre:regex-replace "^SB!" (canonical-case str) "SB-")) (defun package-at-point () (hi::tag-package (hi::line-tag (mark-line (current-point))))) (defcommand "Set Buffer Package" (p) "Set the package to be used by Lisp evaluation and compilation commands while in this buffer. When in a slave's interactive buffers, do NOT set the editor's package variable, but changed the slave's *package*." "Prompt for a package to make into a buffer-local variable current-package." (declare (ignore p)) (let* ((name (string (prompt-for-expression :prompt "Package name: " :help "Name of package to associate with this buffer."))) (buffer (current-buffer)) (info (value current-eval-server))) (cond ((and info (or (eq (server-info-slave-buffer info) buffer) (eq (server-info-background-buffer info) buffer))) (hemlock.wire:remote (server-info-wire info) (server-set-package name)) (hemlock.wire:wire-force-output (server-info-wire info))) #+nil ((eq buffer *selected-eval-buffer*) (setf *package* (maybe-make-package name))) (t (defhvar "Current Package" "The package used for evaluation of Lisp in this buffer." :buffer buffer :value name))) (when (buffer-modeline-field-p buffer :package) (dolist (w (buffer-windows buffer)) (update-modeline-field buffer w :package))))) (defcommand "Current Compile Server" (p) "Echos the current compile server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." "Echos the current compile server's name. With prefix argument, shows global one." (let ((info (if p (variable-value 'current-compile-server :global) (value current-compile-server)))) (if info (message "~A" (server-info-name info)) (message "No ~:[current~;global~] compile server." p)))) (defcommand "Set Compile Server" (p) "Specifies the name of the server used globally for file compilation requests." "Call select-current-compile-server." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (setf (variable-value 'current-compile-server :global) (maybe-create-server)))) (defcommand "Set Buffer Compile Server" (p) "Specifies the name of the server used for file compilation requests in the current buffer." "Call select-current-compile-server after making a buffer local variable." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (defhvar "Current Compile Server" "The Server-Info object for the server currently used for compilation requests." :buffer (current-buffer) :value (maybe-create-server)))) (defcommand "Current Eval Server" (p) "Echos the current eval server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." "Echos the current eval server's name. With prefix argument, shows global one. Does not signal an error or ask about creating a slave." (let ((info (if p (variable-value 'current-eval-server :global) (value current-eval-server)))) (if info (message "~A" (server-info-name info)) (message "No ~:[current~;global~] eval server." p)))) (defcommand "Set Eval Server" (p) "Specifies the name of the server used globally for evaluation and compilation requests." "Call select-current-server." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (setf (variable-value 'current-eval-server :global) (maybe-create-server)))) (defcommand "Set Buffer Eval Server" (p) "Specifies the name of the server used for evaluation and compilation requests in the current buffer." "Call select-current-server after making a buffer local variable." (declare (ignore p)) (hlet ((ask-about-old-servers t)) (defhvar "Current Eval Server" "The Server-Info for the eval server used in this buffer." :buffer (current-buffer) :value (maybe-create-server)))) (defcommand "Evaluate Defun" (p) "Evaluates the current or next top-level form. If the current region is active, then evaluate it." "Evaluates the current or next top-level form." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluate Defun in the editor Lisp ...") (editor-evaluate-defun-command nil)) ((region-active-p) (evaluate-region-command nil)) (t (region-eval (defun-region (current-point))))))) (defcommand "Re-evaluate Defvar" (p) "Evaluate the current or next top-level form if it is a DEFVAR. Treat the form as if the variable is not bound." "Evaluate the current or next top-level form if it is a DEFVAR. Treat the form as if the variable is not bound." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Re-evaluate Defvar in the editor Lisp ...") (editor-re-evaluate-defvar-command nil)) (t (let* ((form (defun-region (current-point))) (start (region-start form))) (with-mark ((var-start start) (var-end start)) (mark-after var-start) (form-offset var-start 1) (form-offset (move-mark var-end var-start) 1) (let ((exp (concatenate 'simple-string "(makunbound '" (region-to-string (region var-start var-end)) ")"))) (eval-form-in-server (get-current-eval-server) exp))) (region-eval form)))))) at the client as a string , so it can read from the string with the (defcommand "Macroexpand Expression" (p) "Show the macroexpansion of the current expression in the null environment. With an argument, use MACROEXPAND instead of MACROEXPAND-1." "Show the macroexpansion of the current expression in the null environment. With an argument, use MACROEXPAND instead of MACROEXPAND-1." (let ((info (value current-eval-server))) (cond ((not info) (message "Macroexpand Expression in the editor Lisp ...") (editor-macroexpand-expression-command nil)) (t (let ((point (current-point))) (with-mark ((start point)) (pre-command-parse-check start) (with-mark ((end start)) (unless (form-offset end 1) (editor-error)) (let ((package (package-at-point))) (with-pop-up-display (s) (write-string (eval-form-in-server-1 (get-current-eval-server) (format nil "(prin1-to-string (~S (read-from-string ~S)))" (if p 'macroexpand 'macroexpand-1) (region-to-string (region start end))) package) s)))))))))) (defcommand "Evaluate Expression" (p) "Prompt for an expression to evaluate." "Prompt for an expression to evaluate." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluate Expression in the editor Lisp ...") (editor-evaluate-expression-command nil)) (t (let ((exp (prompt-for-string :prompt "Eval: " :help "Expression to evaluate."))) (message "=> ~{~#[~;~A~:;~A, ~]~}" (eval-form-in-server (get-current-eval-server) exp))))))) (defcommand "Compile Defun" (p) "Compiles the current or next top-level form. First the form is evaluated, then the result of this evaluation is passed to compile. If the current region is active, compile the region." "Evaluates the current or next top-level form." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compiling in the editor Lisp ...") (editor-compile-defun-command nil)) ((region-active-p) (compile-region-command nil)) (t (region-compile (defun-region (current-point))))))) (defcommand "Compile Region" (p) "Compiles lisp forms between the point and the mark." "Compiles lisp forms between the point and the mark." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compiling in the editor Lisp ...") (editor-compile-region-command nil)) (t (region-compile (current-region)))))) (defcommand "Evaluate Region" (p) "Evaluates lisp forms between the point and the mark." "Evaluates lisp forms between the point and the mark." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluating region in the editor Lisp ...") (editor-evaluate-region-command nil)) (t (region-eval (current-region)))))) (defcommand "Evaluate Buffer" (p) "Evaluates the text in the current buffer." "Evaluates the text in the current buffer redirecting *Standard-Output* to the echo area. The prefix argument is ignored." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Evaluating buffer in the editor Lisp ...") (editor-evaluate-buffer-command nil)) (t (let ((b (current-buffer))) (region-eval (buffer-region b) :context (format nil "evaluation of buffer ``~A''" (buffer-name b)))))))) (defcommand "Load File" (p) "Prompt for a file to load into the current eval server." "Prompt for a file to load into the current eval server." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Load File in the editor Lisp ...") (editor-load-file-command nil)) (t (let ((name (truename (prompt-for-file :default (or (value load-pathname-defaults) (buffer-default-pathname (current-buffer))) :prompt "File to load: " :help "The name of the file to load")))) (setv load-pathname-defaults name) (string-eval (format nil "(load ~S)" (namestring (if (value remote-compile-file) (pathname-for-remote-access name) name))))))))) (defcommand "Compile File" (p) "Prompts for file to compile. Does not compare source and binary write dates. Does not check any buffer for that file for whether the buffer needs to be saved." "Prompts for file to compile." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Compile File in the editor Lisp ...") (editor-compile-file-command nil)) (t (let ((pn (prompt-for-file :default (buffer-default-pathname (current-buffer)) :prompt "File to compile: "))) (file-compile pn)))))) (defhvar "Compile Buffer File Confirm" "When set, \"Compile Buffer File\" prompts before doing anything." :value nil) (defcommand "Compile Buffer File" (p) "Compile the file in the current buffer if its associated binary file (of type .fasl) is older than the source or doesn't exist. When the binary file is up to date, the user is asked if the source should be compiled anyway. When the prefix argument is supplied, compile the file without checking the binary file. When \"Compile Buffer File Confirm\" is set, this command will ask for confirmation when it otherwise would not." "Compile the file in the current buffer if the fasl file isn't up to date. When p, always do it." (let ((info (value current-eval-server))) (cond ((not info) (message "Compile Buffer File in the editor Lisp ...") (editor-compile-buffer-file-command nil)) (t (let* ((buf (current-buffer)) (pn (buffer-pathname buf))) (unless pn (editor-error "Buffer has no associated pathname.")) (cond ((buffer-modified buf) (when (or (not (value compile-buffer-file-confirm)) (prompt-for-y-or-n :default t :default-string "Y" :prompt (list "Save and compile file ~A? " (namestring pn)))) (write-buffer-file buf pn) (file-compile pn :buffer buf))) ((older-or-non-existent-fasl-p pn p) (when (or (not (value compile-buffer-file-confirm)) (prompt-for-y-or-n :default t :default-string "Y" :prompt (list "Compile file ~A? " (namestring pn)))) (file-compile pn :buffer buf))) ((or p (prompt-for-y-or-n :default t :default-string "Y" :prompt "Fasl file up to date, compile source anyway? ")) (file-compile pn :buffer buf)))))))) (defcommand "Compile Group" (p) "Compile each file in the current group which needs it. If a file has type LISP and there is a curresponding file with type FASL which has been written less recently (or it doesn't exit), then the file is compiled, with error output directed to the \"Compiler Warnings\" buffer. If a prefix argument is provided, then all the files are compiled. All modified files are saved beforehand." "Do a Compile-File in each file in the current group that seems to need it." (let ((info (value current-eval-server))) (cond ((not info) (message "Compile Group in the editor Lisp ...") (editor-compile-group-command nil)) (t (save-all-files-command ()) (unless *active-file-group* (editor-error "No active file group.")) (dolist (file *active-file-group*) (when (string-equal (pathname-type file) "lisp") (let ((tn (probe-file file))) (cond ((not tn) (message "File ~A not found." (namestring file))) ((older-or-non-existent-fasl-p tn p) (file-compile tn)))))))))) (defcommand "Flush Compiler Error Information" (p) "Flushes all infomation about errors encountered while compiling using the current server" "Flushes all infomation about errors encountered while compiling using the current server" (declare (ignore p)) (clear-server-errors (get-current-compile-server t))) (defcommand "Next Compiler Error" (p) "Move to the next compiler error for the current server. If an argument is given, advance that many errors." "Move to the next compiler error for the current server. If an argument is given, advance that many errors." (let* ((server (get-current-compile-server t)) (errors (server-info-errors server)) (fp (fill-pointer errors))) (when (zerop fp) (editor-error "There are no compiler errors.")) (let* ((old-index (server-info-error-index server)) (new-index (+ (or old-index -1) (or p 1)))) (when (< new-index 0) (if old-index (editor-error "Can't back up ~R, only at the ~:R compiler error." (- p) (1+ old-index)) (editor-error "Not even at the first compiler error."))) (when (>= new-index fp) (if (= (1+ (or old-index -1)) fp) (editor-error "No more compiler errors.") (editor-error "Only ~R remaining compiler error~:P." (- fp old-index 1)))) (setf (server-info-error-index server) new-index) (let ((error (aref errors new-index))) (let ((region (error-info-region error))) (if region (let* ((start (region-start region)) (buffer (line-buffer (mark-line start)))) (change-to-buffer buffer) (move-mark (buffer-point buffer) start)) (message "Hmm, no region for this error."))) (let* ((line (error-info-line error)) (buffer (line-buffer line))) (if (and line (bufferp buffer)) (let ((mark (mark line 0))) (unless (buffer-windows buffer) (let ((window (find-if-not #'(lambda (window) (or (eq window (current-window)) (eq window *echo-area-window*))) *window-list*))) (if window (setf (window-buffer window) buffer) (make-window mark)))) (move-mark (buffer-point buffer) mark) (dolist (window (buffer-windows buffer)) (move-mark (window-display-start window) mark) (move-mark (window-point window) mark)) (delete-mark mark)) (message "Hmm, no line for this error."))))))) (defcommand "Previous Compiler Error" (p) "Move to the previous compiler error. If an argument is given, move back that many errors." "Move to the previous compiler error. If an argument is given, move back that many errors." (next-compiler-error-command (- (or p 1)))) (defcommand "Abort Operations" (p) "Abort all operations on current eval server connection." "Abort all operations on current eval server connection." (declare (ignore p)) (let* ((server (get-current-eval-server)) (wire (server-info-wire server))) (dolist (note (server-info-notes server)) (setf (note-state note) :aborted)) #+NILGB (ext:send-character-out-of-band (hemlock.wire:wire-fd wire) #\N) (hemlock.wire:remote-value wire (server-accept-operations)) (hemlock.wire:wire-force-output wire) (dolist (note (server-info-notes server)) (when (eq (note-state note) :pending) The HEMLOCK.WIRE : REMOTE - VALUE call should have allowed a handshake to (error "Operation ~S is still around after we aborted it?" note))) (setf (server-info-notes server) nil))) (defcommand "List Operations" (p) "List all eval server operations which have not yet completed." "List all eval server operations which have not yet completed." (declare (ignore p)) (let ((notes nil)) (do-strings (str val *server-names*) (declare (ignore str)) (setq notes (nconc notes (reverse (server-info-notes val))))) (if notes (with-pop-up-display (s) (dolist (note notes) (format s "~@(~8A~) ~A on ~A.~%" (note-state note) (note-context note) (server-info-name (note-server note))))) (message "No uncompleted operations."))) (values)) " Describe Function Call " gets the function name from the current form back as a list of strings , so we read the first string to get out the string value returned by DESCRIBE - FUNCTION - CALL - AUX in the client . (defcommand "Describe Function Call" (p) "Describe the current function call." "Describe the current function call." (let ((info (value current-eval-server))) (cond ((not info) (message "Describing from the editor Lisp ...") (editor-describe-function-call-command p)) (t (with-mark ((mark1 (current-point)) (mark2 (current-point))) (pre-command-parse-check mark1) (unless (backward-up-list mark1) (editor-error)) (form-offset (move-mark mark2 (mark-after mark1)) 1) (let* ((package (package-at-point)) (package-exists (eval-form-in-server-1 info (format nil "(if (find-package ~S) t (package-name *package*))" package) nil))) (unless (eq package-exists t) (message "Using package ~S in ~A since ~ package-exists (server-info-name info) package)) (with-pop-up-display (s) (write-string (eval-form-in-server-1 info (format nil "(hemlock::describe-function-call-aux ~S)" (region-to-string (region mark1 mark2))) (if (eq package-exists t) package nil)) s)))))))) (defun describe-function-call-aux (string) (let* ((sym (read-from-string string)) (fun (function-to-describe sym error))) (with-output-to-string (*standard-output*) (editor-describe-function fun sym)))) " Describe Symbol " gets the symbol name and quotes it as the argument to a list of strings , so we read the first string to get out the string value returned by DESCRIBE - SYMBOL - AUX in the client . (defcommand "Describe Symbol" (p) "Describe the previous s-expression if it is a symbol." "Describe the previous s-expression if it is a symbol." (declare (ignore p)) (let ((info (value current-eval-server))) (cond ((not info) (message "Describing from the editor Lisp ...") (editor-describe-symbol-command nil)) (t (with-mark ((mark1 (current-point)) (mark2 (current-point))) (mark-symbol mark1 mark2) (let ((package (package-at-point))) (with-pop-up-display (s) (write-string (eval-form-in-server-1 info (format nil "(hemlock::describe-symbol-aux '~A)" (region-to-string (region mark1 mark2))) package) s)))))))) (defun describe-symbol-aux (thing) (with-output-to-string (*standard-output*) (describe (if (and (consp thing) (or (eq (car thing) 'quote) (eq (car thing) 'function)) (symbolp (cadr thing))) (cadr thing) thing))))
98d2aef9bf2f4a1eebc0a69a84f8d3d68c46faaf5c7b03cca3b0b1e842f9d070
gvolpe/haskell-book-exercises
sing.hs
module Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" sing = if (x > y) then fstString x else sndString y where x = "Singin" y = "Somewhere"
null
https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter5/sing.hs
haskell
module Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" sing = if (x > y) then fstString x else sndString y where x = "Singin" y = "Somewhere"
29811463c90837e327dec3a2b66b9f9e95221f34ae5e34ca2fea0e8e1ed4c814
bcc32/advent-of-code
a.ml
open! Core open! Async open! Import let main () = let%bind events = Reader.with_file "input" ~f:(fun r -> r |> Reader.lines |> Pipe.to_list) (* times can be compared lexicographically *) >>| List.sort ~compare:String.compare >>| List.map ~f:Event.of_string in let sleeps = events |> Event.analyze |> Int.Table.of_alist_multi in let sleepiest_guard = sleeps |> Hashtbl.map ~f:(fun sleeps -> List.sum (module Int) sleeps ~f:(fun (x, y) -> y - x)) |> Hashtbl.to_alist |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn ~here:[%here] |> fst in let minute = let minutes_slept = Hashtbl.find_exn sleeps sleepiest_guard in List.init 60 ~f:(fun m -> m, List.count minutes_slept ~f:(fun (x, y) -> x <= m && m < y)) |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn ~here:[%here] |> fst in printf "%d\n" (sleepiest_guard * minute); return () ;; let%expect_test "a" = let%bind () = main () in [%expect {| 102688 |}]; return () ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2018/04/a.ml
ocaml
times can be compared lexicographically
open! Core open! Async open! Import let main () = let%bind events = Reader.with_file "input" ~f:(fun r -> r |> Reader.lines |> Pipe.to_list) >>| List.sort ~compare:String.compare >>| List.map ~f:Event.of_string in let sleeps = events |> Event.analyze |> Int.Table.of_alist_multi in let sleepiest_guard = sleeps |> Hashtbl.map ~f:(fun sleeps -> List.sum (module Int) sleeps ~f:(fun (x, y) -> y - x)) |> Hashtbl.to_alist |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn ~here:[%here] |> fst in let minute = let minutes_slept = Hashtbl.find_exn sleeps sleepiest_guard in List.init 60 ~f:(fun m -> m, List.count minutes_slept ~f:(fun (x, y) -> x <= m && m < y)) |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn ~here:[%here] |> fst in printf "%d\n" (sleepiest_guard * minute); return () ;; let%expect_test "a" = let%bind () = main () in [%expect {| 102688 |}]; return () ;;
3a5b93b1df1ee8ad12587a3b36b1df0e7ee48d98a6fcbadd3156c7c8e337d55d
poscat0x04/telegram-types
Document.hs
module Web.Telegram.Types.Internal.Document where import Common import Web.Telegram.Types.Internal.PhotoSize -- | A general file (as opposed to photos, voice messages and audio files) data Document = Document { -- | Identifier for this file, which can be used to download or reuse the file fileId :: Text, -- | Unique identifier for this file, which is supposed to be the same over time -- and for different bots. Can't be used to download or reuse the file. fileUniqueId :: Text, -- | Document thumbnail as defined by sender thumb :: Maybe PhotoSize, -- | Original filename as defined by sender fileName :: Maybe Text, -- | MIME type of the file as defined by sender mimeType :: Maybe Text, -- | File size fileSize :: Maybe Int } deriving stock (Show, Eq) mkLabel ''Document deriveJSON snake ''Document
null
https://raw.githubusercontent.com/poscat0x04/telegram-types/c09ccc81cff10399538894cf2d1273022c797e18/src/Web/Telegram/Types/Internal/Document.hs
haskell
| A general file (as opposed to photos, voice messages and audio files) | Identifier for this file, which can be used to download or reuse the file | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. | Document thumbnail as defined by sender | Original filename as defined by sender | MIME type of the file as defined by sender | File size
module Web.Telegram.Types.Internal.Document where import Common import Web.Telegram.Types.Internal.PhotoSize data Document = Document fileId :: Text, fileUniqueId :: Text, thumb :: Maybe PhotoSize, fileName :: Maybe Text, mimeType :: Maybe Text, fileSize :: Maybe Int } deriving stock (Show, Eq) mkLabel ''Document deriveJSON snake ''Document
ff4378a30853275b506fb24a0faa212848819ed09550df4b83e9fa5f847ee3e3
typedclojure/typedclojure
gen_doc.clj
(ns gen-doc (:require [codox.main :as codox])) (defn -main [& args] (codox/generate-docs {:language :clojure :source-uri "/{git-commit}/typed/clj.refactor/{filepath}#L{line}" :output-path "target/codox"}) (shutdown-agents) (System/exit 0))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/45556897356f3c9cbc7b1b6b4df263086a9d5803/typed/clj.refactor/script/gen_doc.clj
clojure
(ns gen-doc (:require [codox.main :as codox])) (defn -main [& args] (codox/generate-docs {:language :clojure :source-uri "/{git-commit}/typed/clj.refactor/{filepath}#L{line}" :output-path "target/codox"}) (shutdown-agents) (System/exit 0))
39b6837e8eb67afccc759c7eb9246eba2d6c6e28a63cf544d84bcb1077da1b26
jfacorro/clojure-lab
toolbar.clj
(ns lab.ui.swing.toolbar (:require [lab.ui.core :as ui] [lab.ui.protocols :refer [impl to-map listen ignore]] [lab.ui.util :refer [defattributes definitializations]] [lab.ui.swing.util :as util]) (:import [javax.swing JToolBar])) (definitializations :toolbar JToolBar) (defattributes :toolbar (:floatable [c _ v] (.setFloatable ^JToolBar (impl c) v)))
null
https://raw.githubusercontent.com/jfacorro/clojure-lab/f0b5a4b78172984fc876f063f66e5e1592178da9/src/clj/lab/ui/swing/toolbar.clj
clojure
(ns lab.ui.swing.toolbar (:require [lab.ui.core :as ui] [lab.ui.protocols :refer [impl to-map listen ignore]] [lab.ui.util :refer [defattributes definitializations]] [lab.ui.swing.util :as util]) (:import [javax.swing JToolBar])) (definitializations :toolbar JToolBar) (defattributes :toolbar (:floatable [c _ v] (.setFloatable ^JToolBar (impl c) v)))
ca3b3579fc0bb1998bc8aa11590ad72a637d0b003a9770e7e76627b65b325ddd
ghc/packages-dph
HybU.hs
module HybU ( hybrid_connected_components ) where import Data.Array.Parallel.Unlifted enumerate :: UArr Bool -> UArr Int # INLINE enumerate # enumerate = scanU (+) 0 . mapU (\b -> if b then 1 else 0) pack_index :: UArr Bool -> UArr Int # INLINE pack_index # pack_index bs = mapU fstS . filterU sndS $ zipU (enumFromToU 0 (lengthU bs - 1)) bs shortcut_all :: UArr Int -> UArr Int shortcut_all p = let pp = bpermuteU p p in if p == pp then pp else shortcut_all pp compress_graph :: UArr Int -> UArr (Int :*: Int) -> UArr (Int :*: Int) :*: UArr Int compress_graph p e = let e1 :*: e2 = unzipU e e' = zipU (bpermuteU p e1) (bpermuteU p e2) e'' = mapU (\(i :*: j) -> if i > j then j :*: i else i :*: j) . filterU (\(i :*: j) -> i /= j) $ e' roots = zipWithU (==) p (enumFromToU 0 (lengthU p - 1)) labels = enumerate roots e1'' :*: e2'' = unzipU e'' e''' = zipU (bpermuteU labels e1'') (bpermuteU labels e2'') in e''' :*: pack_index roots hybrid_connected_components :: UArr (Int :*: Int) -> Int -> Int :*: UArr Int # NOINLINE hybrid_connected_components # hybrid_connected_components e n | nullU e = 0 :*: enumFromToU 0 (n-1) | otherwise = let p = shortcut_all $ updateU (enumFromToU 0 (n-1)) e e' :*: i = compress_graph p e k :*: r = hybrid_connected_components e' (lengthU i) ins = updateU p . zipU i $ bpermuteU i r in k+1 :*: bpermuteU ins ins
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/icebox/examples/concomp/HybU.hs
haskell
module HybU ( hybrid_connected_components ) where import Data.Array.Parallel.Unlifted enumerate :: UArr Bool -> UArr Int # INLINE enumerate # enumerate = scanU (+) 0 . mapU (\b -> if b then 1 else 0) pack_index :: UArr Bool -> UArr Int # INLINE pack_index # pack_index bs = mapU fstS . filterU sndS $ zipU (enumFromToU 0 (lengthU bs - 1)) bs shortcut_all :: UArr Int -> UArr Int shortcut_all p = let pp = bpermuteU p p in if p == pp then pp else shortcut_all pp compress_graph :: UArr Int -> UArr (Int :*: Int) -> UArr (Int :*: Int) :*: UArr Int compress_graph p e = let e1 :*: e2 = unzipU e e' = zipU (bpermuteU p e1) (bpermuteU p e2) e'' = mapU (\(i :*: j) -> if i > j then j :*: i else i :*: j) . filterU (\(i :*: j) -> i /= j) $ e' roots = zipWithU (==) p (enumFromToU 0 (lengthU p - 1)) labels = enumerate roots e1'' :*: e2'' = unzipU e'' e''' = zipU (bpermuteU labels e1'') (bpermuteU labels e2'') in e''' :*: pack_index roots hybrid_connected_components :: UArr (Int :*: Int) -> Int -> Int :*: UArr Int # NOINLINE hybrid_connected_components # hybrid_connected_components e n | nullU e = 0 :*: enumFromToU 0 (n-1) | otherwise = let p = shortcut_all $ updateU (enumFromToU 0 (n-1)) e e' :*: i = compress_graph p e k :*: r = hybrid_connected_components e' (lengthU i) ins = updateU p . zipU i $ bpermuteU i r in k+1 :*: bpermuteU ins ins
1a8bb3ef14a82f87bff0dc1df7f1ed25a4a3c2904bf5f59f5d5dee93d642e81d
xu-hao/QueryArrow
HSLogger.hs
module QueryArrow.Control.Monad.Logger.HSLogger where import Control.Monad.Logger import System.Log.FastLogger import System.Log.Logger import qualified Data.Text as T import Data.Text.Encoding instance MonadLogger IO where monadLoggerLog loc logsource loglevel msg = do let priority = case loglevel of LevelDebug -> DEBUG LevelInfo -> INFO LevelWarn -> WARNING LevelError -> ERROR LevelOther _ -> NOTICE logM (show logsource) priority (T.unpack (decodeUtf8 (fromLogStr (toLogStr msg)))) instance MonadLoggerIO IO where askLoggerIO = return monadLoggerLog
null
https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/log-adapter/src/QueryArrow/Control/Monad/Logger/HSLogger.hs
haskell
module QueryArrow.Control.Monad.Logger.HSLogger where import Control.Monad.Logger import System.Log.FastLogger import System.Log.Logger import qualified Data.Text as T import Data.Text.Encoding instance MonadLogger IO where monadLoggerLog loc logsource loglevel msg = do let priority = case loglevel of LevelDebug -> DEBUG LevelInfo -> INFO LevelWarn -> WARNING LevelError -> ERROR LevelOther _ -> NOTICE logM (show logsource) priority (T.unpack (decodeUtf8 (fromLogStr (toLogStr msg)))) instance MonadLoggerIO IO where askLoggerIO = return monadLoggerLog
8042d9303ca8a221af28848788869a709ffc6d8cf76042527e10d98acaef481d
bigmlcom/clj-bigml
utils.clj
Copyright 2016 , 2017 BigML Licensed under the Apache License , Version 2.0 ;; -2.0 (ns bigml.test.api.utils "Contains a few facilities especially meant tor testing" (:require (bigml.api [core :as api] [source :as source] [dataset :as dataset] [model :as model] [prediction :as prediction] [evaluation :as evaluation] [cluster :as cluster] [centroid :as centroid]))) (defn authenticated-connection "Returns a properly authenticated connection. Credentials shall be provided through the BIGML_USERNAME and BIGML_API_KEY environment variables" [] (let [username (System/getenv "BIGML_USERNAME") api-key (System/getenv "BIGML_API_KEY")] (api/make-connection username api-key))) (def api-fns {:source {:create source/create} :dataset {:create dataset/create} :model {:create model/create} :cluster {:create cluster/create} :centroid {:create centroid/create} :evaluation {:create evaluation/create} :prediction {:create prediction/create}}) (defn- do-verb "This function is a sort of universal wrapper around individual create functions that reside in specific namespaces. it enables the syntax: (create source file-path options) in place of the less flexible (bigml.api.source/create file-path options)" [verb res-type res-uuid params] (let [inputs (:input_data params) params (:options params)] (if (nil? inputs) (apply (get-in api-fns [res-type verb]) res-uuid (flatten (seq params))) (apply (get-in api-fns [res-type verb]) res-uuid inputs (flatten (seq params)))))) (defn- create-arg-type "This is used to select the proper implementation of the create multimethod" [x & _] (cond (= (type x) (type :keyword)) :single (= (type x) (type [])) :sequence :default :error)) (defmulti create "This function creates either a single resource, or a sequence of resources. It returns the UUID of the resource created or an array thereof. - res-type: resource type(s) to create, a keyword or an array thereof - res-uuid: UUID of the resource which is used to create the requested resource or the first one of the sequence; it can also be a file path/url - params: a list of options for the single-resource case, or a map from a resource type (represented by a keyword) and another map representing the options to use for that resource type" create-arg-type) (defmethod create :single [res-type res-uuid & params] (api/get-final (apply do-verb :create res-type res-uuid params))) (defmethod create :sequence [res-type res-uuid & params] (reduce #(conj %1 (:resource (create %2 (last %1) (%2 (first params))))) [res-uuid] res-type)) (defn create-get-cleanup "This function wraps create so it does a GET of the last resource returned by create and returns it; additionally, it deletes all resources created remotely." [res-type [res-uuid params]] (let [resources (create res-type res-uuid params) result (api/get-final (last resources))] (dorun (pmap api/delete (drop 1 resources))) result))
null
https://raw.githubusercontent.com/bigmlcom/clj-bigml/61579ad473d7e191ed06fb6338847dcb0a664497/test/bigml/test/api/utils.clj
clojure
-2.0 it can also be a file path/url additionally, it deletes
Copyright 2016 , 2017 BigML Licensed under the Apache License , Version 2.0 (ns bigml.test.api.utils "Contains a few facilities especially meant tor testing" (:require (bigml.api [core :as api] [source :as source] [dataset :as dataset] [model :as model] [prediction :as prediction] [evaluation :as evaluation] [cluster :as cluster] [centroid :as centroid]))) (defn authenticated-connection "Returns a properly authenticated connection. Credentials shall be provided through the BIGML_USERNAME and BIGML_API_KEY environment variables" [] (let [username (System/getenv "BIGML_USERNAME") api-key (System/getenv "BIGML_API_KEY")] (api/make-connection username api-key))) (def api-fns {:source {:create source/create} :dataset {:create dataset/create} :model {:create model/create} :cluster {:create cluster/create} :centroid {:create centroid/create} :evaluation {:create evaluation/create} :prediction {:create prediction/create}}) (defn- do-verb "This function is a sort of universal wrapper around individual create functions that reside in specific namespaces. it enables the syntax: (create source file-path options) in place of the less flexible (bigml.api.source/create file-path options)" [verb res-type res-uuid params] (let [inputs (:input_data params) params (:options params)] (if (nil? inputs) (apply (get-in api-fns [res-type verb]) res-uuid (flatten (seq params))) (apply (get-in api-fns [res-type verb]) res-uuid inputs (flatten (seq params)))))) (defn- create-arg-type "This is used to select the proper implementation of the create multimethod" [x & _] (cond (= (type x) (type :keyword)) :single (= (type x) (type [])) :sequence :default :error)) (defmulti create "This function creates either a single resource, or a sequence of resources. It returns the UUID of the resource created or an array thereof. - res-type: resource type(s) to create, a keyword or an array thereof - res-uuid: UUID of the resource which is used to create the requested - params: a list of options for the single-resource case, or a map from a resource type (represented by a keyword) and another map representing the options to use for that resource type" create-arg-type) (defmethod create :single [res-type res-uuid & params] (api/get-final (apply do-verb :create res-type res-uuid params))) (defmethod create :sequence [res-type res-uuid & params] (reduce #(conj %1 (:resource (create %2 (last %1) (%2 (first params))))) [res-uuid] res-type)) (defn create-get-cleanup "This function wraps create so it does a GET of the last resource all resources created remotely." [res-type [res-uuid params]] (let [resources (create res-type res-uuid params) result (api/get-final (last resources))] (dorun (pmap api/delete (drop 1 resources))) result))
91ba84b376111757ce3ffd30377199234394dc1db5d7c0eee8b98425babd6e08
rauhs/clj-bench
misc.clj
(ns clj-bench.misc (:require [criterium.core :as crit]))
null
https://raw.githubusercontent.com/rauhs/clj-bench/6c7148e84fc3ad9cd70db6991fdd8fdb4fc7fdbd/src/clj_bench/misc.clj
clojure
(ns clj-bench.misc (:require [criterium.core :as crit]))
3028a9c48cb16ef1dc4a3d3db25c253b58c35d1107bab1415bf23d10269199ca
threatgrid/ctia
riemann.clj
(ns ctia.lib.riemann (:require [clojure.string :as str] [clojure.tools.logging :as log] [riemann.client :as riemann] [ctia.lib.utils :as utils]) (:import [clojure.lang ExceptionInfo] [io.riemann.riemann.client RiemannBatchClient])) ;; based on riemann-reporter.core/request-to-event (defn request->event [request extra-fields] (into {:uri (str (:uri request)) :_params (utils/safe-pprint-str (:params request)) :remote-addr (str (if-let [xff (get-in request [:headers "x-forwarded-for"])] (peek (str/split xff #"\s*,\s*")) (:remote-addr request))) :request-method (str (:request-method request)) :identity (:identity request) :jwt (:jwt request)} extra-fields)) (defn ms-elapsed "Milliseconds since `nano-start`." [nano-start] (/ (- (System/nanoTime) nano-start) 1000000.0)) ;; based on riemann-reporter.core/send-request-metrics (defn- send-request-logs [send-event-fn request extra-fields] (let [event (request->event request extra-fields)] (try (send-event-fn event) (catch Exception e (log/warnf "A Problem occured while sending request metrics event:\n\n%s\n\nException:\n%s" (utils/safe-pprint-str event) (utils/safe-pprint-str e)) (when (nil? send-event-fn) (log/warn "The send-event-fn looks empty. This is certainly due to a configuration problem or perhaps simply a code bug.")))))) (def kw->jwt-key (into {} (map (fn [[k v]] [k (str "/" v)])) {:client-id "oauth/client/id" :client-name "oauth/client/name" :user-id "user/id" :user-name "user/name" :user-nick "user/nick" :user-email "user/email" :org-id "org/id" :org-name "org/name" :idp-id "user/idp/id" ;; :trace-id (search-event [:trace :id] event) ?? })) ;; should align with riemann-reporter.core/extract-infos-from-event (defn extract-infos-from-event [event] (into {} (map (fn [[kw jwt-key]] (when-let [v (get-in event [:jwt jwt-key])] [kw v]))) kw->jwt-key)) (defn find-and-add-metas [e] (let [infos (extract-infos-from-event e)] (into infos e))) ;; copied from riemann-reporter.core (defn str-protect [s] (str/replace s #"[^a-zA-Z_-]" "-")) ;; copied from riemann-reporter.core (defn- deep-flatten-map-as-couples [prefix m] (apply concat (for [[k v] m] (let [k-str (if (keyword? k) (name k) (str k)) new-pref (if (empty? prefix) k-str (str (name prefix) "-" (str-protect k-str)))] (if (map? v) (deep-flatten-map-as-couples new-pref v) [[(keyword new-pref) (if (string? v) v (pr-str v))]]))))) ;; copied from riemann-reporter.core (defn deep-flatten-map [prefix m] (into {} (deep-flatten-map-as-couples prefix m))) ;; copied from riemann-reporter.core (defn stringify-values [m] (into (deep-flatten-map "" (dissoc m :tags :time :metric)) (select-keys m [:tags :time :metric]))) ;; copied from riemann-reporter.core (defn prepare-event "remove nils, stringify, edn-encode unencoded underscored keys" [event] (->> event utils/deep-remove-nils (into {}) utils/deep-filter-out-creds find-and-add-metas stringify-values)) ;; based on riemann-reporter.core/send-event (defn send-event [conn service-prefix event] (let [prepared-event (-> event prepare-event (update :service #(str service-prefix " " %)))] (if conn (do (log/debugf "Sending event to riemann:\n%s\nprepared:\n%s" (utils/safe-pprint-str event) (utils/safe-pprint-str prepared-event)) (riemann/send-event conn prepared-event)) (when-not (= "log" (:event-type prepared-event)) (log/warnf "Riemann doesn't seem configured. Event: %s" (utils/safe-pprint-str prepared-event)))))) ;; based on riemann-reporter.core/wrap-request-metrics (defn wrap-request-logs "Middleware to log all incoming connections to Riemann" [handler metric-description conn service-prefix] (let [_ (assert (and (string? metric-description) (seq metric-description)) (pr-str metric-description)) _ (log/info "Riemann request logging initialization") send-event-fn (partial send-event conn service-prefix)] (fn [request] (let [start (System/nanoTime)] (try (when-let [response (handler request)] (let [ms (ms-elapsed start)] (send-request-logs send-event-fn request {:metric ms :service metric-description :_headers (prn-str (:headers response)) :status (str (:status response))})) response) (catch ExceptionInfo e (let [data (ex-data e) ex-type (:type data) evt {:metric (ms-elapsed start) :service (str metric-description " error") :description (.getMessage e) :error "true" :status (condp = ex-type :ring.util.http-response/response (get-in data [:response :status]) :compojure.api.exception/response-validation "500" :compojure.api.exception/request-validation "400" "500")}] (send-request-logs send-event-fn request evt)) (throw e)) (catch Throwable e (send-request-logs send-event-fn request {:metric (ms-elapsed start) :service (str metric-description " error") :description (.getMessage e) :stacktrace (.getStackTrace e) :status "500" :error "true"}) (throw e))))))) (defn start [context config] (let [conn (-> (select-keys config [:host :port :interval-in-ms]) riemann/tcp-client (riemann/batch-client (or (:batch-size config) 10))) service-prefix (or (:service-prefix config) "CTIA")] (assoc context :conn conn :service-prefix service-prefix))) (defn stop [{:keys [^RiemannBatchClient conn]}] (when conn (.close conn)) {})
null
https://raw.githubusercontent.com/threatgrid/ctia/9b9f333aeb91dd9faf2541f9d736b8539162d6e9/src/ctia/lib/riemann.clj
clojure
based on riemann-reporter.core/request-to-event based on riemann-reporter.core/send-request-metrics :trace-id (search-event [:trace :id] event) ?? should align with riemann-reporter.core/extract-infos-from-event copied from riemann-reporter.core copied from riemann-reporter.core copied from riemann-reporter.core copied from riemann-reporter.core copied from riemann-reporter.core based on riemann-reporter.core/send-event based on riemann-reporter.core/wrap-request-metrics
(ns ctia.lib.riemann (:require [clojure.string :as str] [clojure.tools.logging :as log] [riemann.client :as riemann] [ctia.lib.utils :as utils]) (:import [clojure.lang ExceptionInfo] [io.riemann.riemann.client RiemannBatchClient])) (defn request->event [request extra-fields] (into {:uri (str (:uri request)) :_params (utils/safe-pprint-str (:params request)) :remote-addr (str (if-let [xff (get-in request [:headers "x-forwarded-for"])] (peek (str/split xff #"\s*,\s*")) (:remote-addr request))) :request-method (str (:request-method request)) :identity (:identity request) :jwt (:jwt request)} extra-fields)) (defn ms-elapsed "Milliseconds since `nano-start`." [nano-start] (/ (- (System/nanoTime) nano-start) 1000000.0)) (defn- send-request-logs [send-event-fn request extra-fields] (let [event (request->event request extra-fields)] (try (send-event-fn event) (catch Exception e (log/warnf "A Problem occured while sending request metrics event:\n\n%s\n\nException:\n%s" (utils/safe-pprint-str event) (utils/safe-pprint-str e)) (when (nil? send-event-fn) (log/warn "The send-event-fn looks empty. This is certainly due to a configuration problem or perhaps simply a code bug.")))))) (def kw->jwt-key (into {} (map (fn [[k v]] [k (str "/" v)])) {:client-id "oauth/client/id" :client-name "oauth/client/name" :user-id "user/id" :user-name "user/name" :user-nick "user/nick" :user-email "user/email" :org-id "org/id" :org-name "org/name" :idp-id "user/idp/id" })) (defn extract-infos-from-event [event] (into {} (map (fn [[kw jwt-key]] (when-let [v (get-in event [:jwt jwt-key])] [kw v]))) kw->jwt-key)) (defn find-and-add-metas [e] (let [infos (extract-infos-from-event e)] (into infos e))) (defn str-protect [s] (str/replace s #"[^a-zA-Z_-]" "-")) (defn- deep-flatten-map-as-couples [prefix m] (apply concat (for [[k v] m] (let [k-str (if (keyword? k) (name k) (str k)) new-pref (if (empty? prefix) k-str (str (name prefix) "-" (str-protect k-str)))] (if (map? v) (deep-flatten-map-as-couples new-pref v) [[(keyword new-pref) (if (string? v) v (pr-str v))]]))))) (defn deep-flatten-map [prefix m] (into {} (deep-flatten-map-as-couples prefix m))) (defn stringify-values [m] (into (deep-flatten-map "" (dissoc m :tags :time :metric)) (select-keys m [:tags :time :metric]))) (defn prepare-event "remove nils, stringify, edn-encode unencoded underscored keys" [event] (->> event utils/deep-remove-nils (into {}) utils/deep-filter-out-creds find-and-add-metas stringify-values)) (defn send-event [conn service-prefix event] (let [prepared-event (-> event prepare-event (update :service #(str service-prefix " " %)))] (if conn (do (log/debugf "Sending event to riemann:\n%s\nprepared:\n%s" (utils/safe-pprint-str event) (utils/safe-pprint-str prepared-event)) (riemann/send-event conn prepared-event)) (when-not (= "log" (:event-type prepared-event)) (log/warnf "Riemann doesn't seem configured. Event: %s" (utils/safe-pprint-str prepared-event)))))) (defn wrap-request-logs "Middleware to log all incoming connections to Riemann" [handler metric-description conn service-prefix] (let [_ (assert (and (string? metric-description) (seq metric-description)) (pr-str metric-description)) _ (log/info "Riemann request logging initialization") send-event-fn (partial send-event conn service-prefix)] (fn [request] (let [start (System/nanoTime)] (try (when-let [response (handler request)] (let [ms (ms-elapsed start)] (send-request-logs send-event-fn request {:metric ms :service metric-description :_headers (prn-str (:headers response)) :status (str (:status response))})) response) (catch ExceptionInfo e (let [data (ex-data e) ex-type (:type data) evt {:metric (ms-elapsed start) :service (str metric-description " error") :description (.getMessage e) :error "true" :status (condp = ex-type :ring.util.http-response/response (get-in data [:response :status]) :compojure.api.exception/response-validation "500" :compojure.api.exception/request-validation "400" "500")}] (send-request-logs send-event-fn request evt)) (throw e)) (catch Throwable e (send-request-logs send-event-fn request {:metric (ms-elapsed start) :service (str metric-description " error") :description (.getMessage e) :stacktrace (.getStackTrace e) :status "500" :error "true"}) (throw e))))))) (defn start [context config] (let [conn (-> (select-keys config [:host :port :interval-in-ms]) riemann/tcp-client (riemann/batch-client (or (:batch-size config) 10))) service-prefix (or (:service-prefix config) "CTIA")] (assoc context :conn conn :service-prefix service-prefix))) (defn stop [{:keys [^RiemannBatchClient conn]}] (when conn (.close conn)) {})
75e9004642ea133fa46f2e2c97cfaff32153776cc99bc1cb5fd7d85c0cb31658
ashinn/chibi-scheme
totient.scm
(define-library (euler totient) (export totient) (import (scheme base) (scheme inexact)) (include "totient-impl.scm"))
null
https://raw.githubusercontent.com/ashinn/chibi-scheme/8b27ce97265e5028c61b2386a86a2c43c1cfba0d/tests/snow/repo3/totient.scm
scheme
(define-library (euler totient) (export totient) (import (scheme base) (scheme inexact)) (include "totient-impl.scm"))
8d3df8b4030eb60a8b2047e756a82423d60668bf425cfebc4dee5806a8865f24
rodo/tsung-gis
postgis_tests.erl
-*- coding : utf-8 -*- %% Copyright ( c ) 2014 < > %% %% 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 </>. %% Unit tests for module : -module(postgis_tests). -author({author, "Rodolphe Quiédeville", "<>"}). -include_lib("eunit/include/eunit.hrl"). -compile(export_all). rnd_point_test()-> %% Url = postgis:rnd_point(), ?assertEqual(true, is_list(Url)). r_point_tsung_test()-> % Tsung call Pid = list_to_pid("<0.42.0>"), Url = postgis:r_point({Pid, []}), ?assertEqual(true, is_list(Url)). rnd_box2d_test()-> Url = postgis:rnd_box2d(), ?assertEqual(true, is_list(Url)). r_box2d_tsung_test()-> % Tsung call Pid = list_to_pid("<0.42.0>"), Url = postgis:r_box2d({Pid,[]}), ?assertEqual(true, is_list(Url)).
null
https://raw.githubusercontent.com/rodo/tsung-gis/d6fc43e5c21d7d12f703cf0766dcd0900ab1d6bc/test/postgis_tests.erl
erlang
This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Tsung call Tsung call
-*- coding : utf-8 -*- Copyright ( c ) 2014 < > 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 Unit tests for module : -module(postgis_tests). -author({author, "Rodolphe Quiédeville", "<>"}). -include_lib("eunit/include/eunit.hrl"). -compile(export_all). rnd_point_test()-> Url = postgis:rnd_point(), ?assertEqual(true, is_list(Url)). r_point_tsung_test()-> Pid = list_to_pid("<0.42.0>"), Url = postgis:r_point({Pid, []}), ?assertEqual(true, is_list(Url)). rnd_box2d_test()-> Url = postgis:rnd_box2d(), ?assertEqual(true, is_list(Url)). r_box2d_tsung_test()-> Pid = list_to_pid("<0.42.0>"), Url = postgis:r_box2d({Pid,[]}), ?assertEqual(true, is_list(Url)).
c877abbdf755ad1b9820a405c519757c08420f390a1c8ae1781f43307883d37c
gothinkster/clojurescript-keechma-realworld-example-app
validators.cljs
(ns app.validators (:require [clojure.string :as str] [forms.validator :as v])) (def countries ["United States" "United Kingdom" "Afghanistan" "Albania" "Algeria" "American Samoa" "Andorra" "Angola" "Anguilla" "Antarctica" "Antigua and Barbuda" "Argentina" "Armenia" "Aruba" "Australia" "Austria" "Azerbaijan" "Bahamas" "Bahrain" "Bangladesh" "Barbados" "Belarus" "Belgium" "Belize" "Benin" "Bermuda" "Bhutan" "Bolivia" "Bosnia and Herzegovina" "Botswana" "Bouvet Island" "Brazil" "British Indian Ocean Territory" "Brunei Darussalam" "Bulgaria" "Burkina Faso" "Burundi" "Cambodia" "Cameroon" "Canada" "Cape Verde" "Cayman Islands" "Central African Republic" "Chad" "Chile" "China" "Christmas Island" "Cocos (Keeling) Islands" "Colombia" "Comoros" "Congo" "Congo, The Democratic Republic of The" "Cook Islands" "Costa Rica" "Cote D'ivoire" "Croatia" "Cuba" "Cyprus" "Czech Republic" "Denmark" "Djibouti" "Dominica" "Dominican Republic" "Ecuador" "Egypt" "El Salvador" "Equatorial Guinea" "Eritrea" "Estonia" "Ethiopia" "Falkland Islands (Malvinas)" "Faroe Islands" "Fiji" "Finland" "France" "French Guiana" "French Polynesia" "French Southern Territories" "Gabon" "Gambia" "Georgia" "Germany" "Ghana" "Gibraltar" "Greece" "Greenland" "Grenada" "Guadeloupe" "Guam" "Guatemala" "Guinea" "Guinea-bissau" "Guyana" "Haiti" "Heard Island and Mcdonald Islands" "Holy See (Vatican City State)" "Honduras" "Hong Kong" "Hungary" "Iceland" "India" "Indonesia" "Iran, Islamic Republic of" "Iraq" "Ireland" "Israel" "Italy" "Jamaica" "Japan" "Jordan" "Kazakhstan" "Kenya" "Kiribati" "Korea, Democratic People's Republic of" "Korea, Republic of" "Kuwait" "Kyrgyzstan" "Lao People's Democratic Republic" "Latvia" "Lebanon" "Lesotho" "Liberia" "Libyan Arab Jamahiriya" "Liechtenstein" "Lithuania" "Luxembourg" "Macao" "Macedonia, The Former Yugoslav Republic of" "Madagascar" "Malawi" "Malaysia" "Maldives" "Mali" "Malta" "Marshall Islands" "Martinique" "Mauritania" "Mauritius" "Mayotte" "Mexico" "Micronesia, Federated States of" "Moldova, Republic of" "Monaco" "Mongolia" "Montenegro" "Montserrat" "Morocco" "Mozambique" "Myanmar" "Namibia" "Nauru" "Nepal" "Netherlands" "Netherlands Antilles" "New Caledonia" "New Zealand" "Nicaragua" "Niger" "Nigeria" "Niue" "Norfolk Island" "Northern Mariana Islands" "Norway" "Oman" "Pakistan" "Palau" "Palestinian Territory, Occupied" "Panama" "Papua New Guinea" "Paraguay" "Peru" "Philippines" "Pitcairn" "Poland" "Portugal" "Puerto Rico" "Qatar" "Reunion" "Romania" "Russian Federation" "Rwanda" "Saint Helena" "Saint Kitts and Nevis" "Saint Lucia" "Saint Pierre and Miquelon" "Saint Vincent and The Grenadines" "Samoa" "San Marino" "Sao Tome and Principe" "Saudi Arabia" "Senegal" "Serbia" "Seychelles" "Sierra Leone" "Singapore" "Slovakia" "Slovenia" "Solomon Islands" "Somalia" "South Africa" "South Georgia and The South Sandwich Islands" "Spain" "Sri Lanka" "Sudan" "Suriname" "Svalbard and Jan Mayen" "Swaziland" "Sweden" "Switzerland" "Syrian Arab Republic" "Taiwan, Province of China" "Tajikistan" "Tanzania, United Republic of" "Thailand" "Timor-leste" "Togo" "Tokelau" "Tonga" "Trinidad and Tobago" "Tunisia" "Turkey" "Turkmenistan" "Turks and Caicos Islands" "Tuvalu" "Uganda" "Ukraine" "United Arab Emirates" "United Kingdom" "United States" "United States Minor Outlying Islands" "Uruguay" "Uzbekistan" "Vanuatu" "Venezuela" "Viet Nam" "Virgin Islands, British" "Virgin Islands, U.S." "Wallis and Futuna" "Western Sahara" "Yemen" "Zambia" "Zimbabwe"]) (def country-set (set countries)) (def email-regex #"^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$") (def email-regex-strict #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") (def url-regex #"https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)") (def us-states #{"AL" "AK" "AS" "AZ" "AR" "CA" "CO" "CT" "DE" "DC" "FL" "GA" "GU" "HI" "ID" "IL" "IN" "IA" "KS" "KY" "LA" "ME" "MD" "MH" "MA" "MI" "FM" "MN" "MS" "MO" "MT" "NE" "NV" "NH" "NJ" "NM" "NY" "NC" "ND" "MP" "OH" "OK" "OR" "PW" "PA" "PR" "RI" "SC" "SD" "TN" "TX" "UT" "VT" "VA" "VI" "WA" "WV" "WI" "WY"}) (def us-states-sorted (sort us-states)) (def phone-regex #"^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$") (defn phone? [v _ _] (not (nil? (re-matches phone-regex (str v))))) (defn zero-count? [v] (if (satisfies? ICounted v) (zero? (count v)) false)) (defn not-empty? [v _ _] (cond (nil? v) false (= "" v) false (zero-count? v) false :else true)) (defn url? [v _ _] (if (seq v) (not (nil? (re-matches url-regex (str v)))) true)) (defn email? [v _ _] (if (or (nil? v) (empty? v)) true (re-matches email-regex-strict (str v)))) (defn edu-email? [v _ _] (if (nil? v) true (str/ends-with? (str/trim v) ".edu"))) (defn number0>100? [v _ _] (if (not (not-empty? v nil nil)) true (let [n (js/parseFloat v 10)] (and (< 0 n) (>= 100 n))))) (defn bool? [v _ _] (if (nil? v) true (or (= true v) (= false v)))) (defn numeric? [v _ _] (if (nil? v) true (re-matches #"^\d+$" (str v)))) (defn numeric-with-decimal? [v _ _] (if (nil? v) true (re-matches #"^[+-]?([0-9]*[.])?[0-9]+" v))) (defn ok-password? [v _ _] (if (seq v) (< 7 (count v)) true)) (defn valid-us-state? [v _ _] (if (seq v) (contains? us-states (str/upper-case v)) true)) (defn valid-country? [v _ _] (if (seq v) (contains? country-set v) true)) (defn valid-cvv? [v _ _] (if (seq v) (or (= 3 (count v)) (= 4 (count v))) true)) (defn valid-zipcode? [v _ _] (if (seq v) (not (nil? (re-matches #"(^\d{5}$)|(^\d{5}-\d{4}$)" (str v)))) true)) (defn password-confirmation [_ data _] (let [pass (get-in data [:enrollInfo :owner :password]) pass-confirmation (get-in data [:enrollInfo :owner :password2])] (if (some nil? [pass pass-confirmation]) true (= pass pass-confirmation)))) (defn cardholder-name [_ data _] (let [nonce (:paypal-nonce data) cardholder-name (:cardholder-name data)] (if nonce true (not-empty? cardholder-name _ _)))) (def default-validations {:not-empty {:message "Please enter a value.", :validator not-empty?}, :true {:message "Please select a value.", :validator #(true? %1)}, :wrong-access-token {:message "Please enter a valid access-token.", :validator (fn [_ _ _] true)}, :bool {:message "Please select a value.", :validator bool?}, :url {:message "Please enter a valid URL.", :validator url?}, :email {:message "Please enter a valid email.", :validator email?}, :edu-email {:message "Please enter a valid .edu email.", :validator edu-email?}, :email-confirmation {:message "Email doesn't match email confirmation.", :validator (fn [_ data _] (let [email (:email data) email-confirmation (:email-confirmation data)] (if (some nil? [email email-confirmation]) true (= email email-confirmation))))}, :email-same {:message "Please enter an email different from old email.", :validator (fn [_ data _] (let [email (:email data) email-old (:email-old data)] (if (some nil? [email email-old]) true (not= email email-old))))}, :us-state {:message "Please select state", :validator (fn [v data _] (let [country (:country data)] (not (and (= "United States" country) (or (= "State *" v) (nil? v) (empty? v))))))}, :password-confirmation {:message "Passwords don't match.", :validator password-confirmation}, :ok-password {:message "Password must contain at least 8 characters.", :validator ok-password?}, :numeric {:message "Please enter a number.", :validator numeric?}, :numeric-with-decimal {:message "Value is not a valid type", :validator numeric-with-decimal?}, :phone {:message "Please enter a valid phone number.", :validator phone?}, :valid-us-state {:message "Please enter an US state", :validator valid-us-state?}, :valid-zipcode {:message "Please enter a valid zip code.", :validator valid-zipcode?}, :valid-country {:message "Please enter a valid country.", :validator valid-country?}, :valid-cardholder {:message "Please enter a cardholder name.", :validator cardholder-name}, :0> {:message "Please enter a value bigger than 0.", :validator (fn [v _ _] (if (not (not-empty? v nil nil)) true (< 0 (js/parseFloat v))))}, :0>100 {:message "Please enter a value between 0 and 100.", :validator number0>100?}}) (def validations$ (atom default-validations)) (defn register-validation! [key validator] (swap! validations$ assoc key validator)) (defn get-validator-message [validation-key] (or (get-in @validations$ [validation-key :message]) "Value failed validation.")) (defn to-validator "Helper function that extracts the validator definitions." [config] (v/validator (reduce-kv (fn [m attr v] (assoc m attr (map (fn [k] [k (get-in @validations$ [k :validator])]) v))) {} config)))
null
https://raw.githubusercontent.com/gothinkster/clojurescript-keechma-realworld-example-app/f6d32f8eea5439b0b33df1afb89da6d27b7da66b/src/app/validators.cljs
clojure
(ns app.validators (:require [clojure.string :as str] [forms.validator :as v])) (def countries ["United States" "United Kingdom" "Afghanistan" "Albania" "Algeria" "American Samoa" "Andorra" "Angola" "Anguilla" "Antarctica" "Antigua and Barbuda" "Argentina" "Armenia" "Aruba" "Australia" "Austria" "Azerbaijan" "Bahamas" "Bahrain" "Bangladesh" "Barbados" "Belarus" "Belgium" "Belize" "Benin" "Bermuda" "Bhutan" "Bolivia" "Bosnia and Herzegovina" "Botswana" "Bouvet Island" "Brazil" "British Indian Ocean Territory" "Brunei Darussalam" "Bulgaria" "Burkina Faso" "Burundi" "Cambodia" "Cameroon" "Canada" "Cape Verde" "Cayman Islands" "Central African Republic" "Chad" "Chile" "China" "Christmas Island" "Cocos (Keeling) Islands" "Colombia" "Comoros" "Congo" "Congo, The Democratic Republic of The" "Cook Islands" "Costa Rica" "Cote D'ivoire" "Croatia" "Cuba" "Cyprus" "Czech Republic" "Denmark" "Djibouti" "Dominica" "Dominican Republic" "Ecuador" "Egypt" "El Salvador" "Equatorial Guinea" "Eritrea" "Estonia" "Ethiopia" "Falkland Islands (Malvinas)" "Faroe Islands" "Fiji" "Finland" "France" "French Guiana" "French Polynesia" "French Southern Territories" "Gabon" "Gambia" "Georgia" "Germany" "Ghana" "Gibraltar" "Greece" "Greenland" "Grenada" "Guadeloupe" "Guam" "Guatemala" "Guinea" "Guinea-bissau" "Guyana" "Haiti" "Heard Island and Mcdonald Islands" "Holy See (Vatican City State)" "Honduras" "Hong Kong" "Hungary" "Iceland" "India" "Indonesia" "Iran, Islamic Republic of" "Iraq" "Ireland" "Israel" "Italy" "Jamaica" "Japan" "Jordan" "Kazakhstan" "Kenya" "Kiribati" "Korea, Democratic People's Republic of" "Korea, Republic of" "Kuwait" "Kyrgyzstan" "Lao People's Democratic Republic" "Latvia" "Lebanon" "Lesotho" "Liberia" "Libyan Arab Jamahiriya" "Liechtenstein" "Lithuania" "Luxembourg" "Macao" "Macedonia, The Former Yugoslav Republic of" "Madagascar" "Malawi" "Malaysia" "Maldives" "Mali" "Malta" "Marshall Islands" "Martinique" "Mauritania" "Mauritius" "Mayotte" "Mexico" "Micronesia, Federated States of" "Moldova, Republic of" "Monaco" "Mongolia" "Montenegro" "Montserrat" "Morocco" "Mozambique" "Myanmar" "Namibia" "Nauru" "Nepal" "Netherlands" "Netherlands Antilles" "New Caledonia" "New Zealand" "Nicaragua" "Niger" "Nigeria" "Niue" "Norfolk Island" "Northern Mariana Islands" "Norway" "Oman" "Pakistan" "Palau" "Palestinian Territory, Occupied" "Panama" "Papua New Guinea" "Paraguay" "Peru" "Philippines" "Pitcairn" "Poland" "Portugal" "Puerto Rico" "Qatar" "Reunion" "Romania" "Russian Federation" "Rwanda" "Saint Helena" "Saint Kitts and Nevis" "Saint Lucia" "Saint Pierre and Miquelon" "Saint Vincent and The Grenadines" "Samoa" "San Marino" "Sao Tome and Principe" "Saudi Arabia" "Senegal" "Serbia" "Seychelles" "Sierra Leone" "Singapore" "Slovakia" "Slovenia" "Solomon Islands" "Somalia" "South Africa" "South Georgia and The South Sandwich Islands" "Spain" "Sri Lanka" "Sudan" "Suriname" "Svalbard and Jan Mayen" "Swaziland" "Sweden" "Switzerland" "Syrian Arab Republic" "Taiwan, Province of China" "Tajikistan" "Tanzania, United Republic of" "Thailand" "Timor-leste" "Togo" "Tokelau" "Tonga" "Trinidad and Tobago" "Tunisia" "Turkey" "Turkmenistan" "Turks and Caicos Islands" "Tuvalu" "Uganda" "Ukraine" "United Arab Emirates" "United Kingdom" "United States" "United States Minor Outlying Islands" "Uruguay" "Uzbekistan" "Vanuatu" "Venezuela" "Viet Nam" "Virgin Islands, British" "Virgin Islands, U.S." "Wallis and Futuna" "Western Sahara" "Yemen" "Zambia" "Zimbabwe"]) (def country-set (set countries)) (def email-regex #"^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$") (def email-regex-strict #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") (def url-regex #"https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)") (def us-states #{"AL" "AK" "AS" "AZ" "AR" "CA" "CO" "CT" "DE" "DC" "FL" "GA" "GU" "HI" "ID" "IL" "IN" "IA" "KS" "KY" "LA" "ME" "MD" "MH" "MA" "MI" "FM" "MN" "MS" "MO" "MT" "NE" "NV" "NH" "NJ" "NM" "NY" "NC" "ND" "MP" "OH" "OK" "OR" "PW" "PA" "PR" "RI" "SC" "SD" "TN" "TX" "UT" "VT" "VA" "VI" "WA" "WV" "WI" "WY"}) (def us-states-sorted (sort us-states)) (def phone-regex #"^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$") (defn phone? [v _ _] (not (nil? (re-matches phone-regex (str v))))) (defn zero-count? [v] (if (satisfies? ICounted v) (zero? (count v)) false)) (defn not-empty? [v _ _] (cond (nil? v) false (= "" v) false (zero-count? v) false :else true)) (defn url? [v _ _] (if (seq v) (not (nil? (re-matches url-regex (str v)))) true)) (defn email? [v _ _] (if (or (nil? v) (empty? v)) true (re-matches email-regex-strict (str v)))) (defn edu-email? [v _ _] (if (nil? v) true (str/ends-with? (str/trim v) ".edu"))) (defn number0>100? [v _ _] (if (not (not-empty? v nil nil)) true (let [n (js/parseFloat v 10)] (and (< 0 n) (>= 100 n))))) (defn bool? [v _ _] (if (nil? v) true (or (= true v) (= false v)))) (defn numeric? [v _ _] (if (nil? v) true (re-matches #"^\d+$" (str v)))) (defn numeric-with-decimal? [v _ _] (if (nil? v) true (re-matches #"^[+-]?([0-9]*[.])?[0-9]+" v))) (defn ok-password? [v _ _] (if (seq v) (< 7 (count v)) true)) (defn valid-us-state? [v _ _] (if (seq v) (contains? us-states (str/upper-case v)) true)) (defn valid-country? [v _ _] (if (seq v) (contains? country-set v) true)) (defn valid-cvv? [v _ _] (if (seq v) (or (= 3 (count v)) (= 4 (count v))) true)) (defn valid-zipcode? [v _ _] (if (seq v) (not (nil? (re-matches #"(^\d{5}$)|(^\d{5}-\d{4}$)" (str v)))) true)) (defn password-confirmation [_ data _] (let [pass (get-in data [:enrollInfo :owner :password]) pass-confirmation (get-in data [:enrollInfo :owner :password2])] (if (some nil? [pass pass-confirmation]) true (= pass pass-confirmation)))) (defn cardholder-name [_ data _] (let [nonce (:paypal-nonce data) cardholder-name (:cardholder-name data)] (if nonce true (not-empty? cardholder-name _ _)))) (def default-validations {:not-empty {:message "Please enter a value.", :validator not-empty?}, :true {:message "Please select a value.", :validator #(true? %1)}, :wrong-access-token {:message "Please enter a valid access-token.", :validator (fn [_ _ _] true)}, :bool {:message "Please select a value.", :validator bool?}, :url {:message "Please enter a valid URL.", :validator url?}, :email {:message "Please enter a valid email.", :validator email?}, :edu-email {:message "Please enter a valid .edu email.", :validator edu-email?}, :email-confirmation {:message "Email doesn't match email confirmation.", :validator (fn [_ data _] (let [email (:email data) email-confirmation (:email-confirmation data)] (if (some nil? [email email-confirmation]) true (= email email-confirmation))))}, :email-same {:message "Please enter an email different from old email.", :validator (fn [_ data _] (let [email (:email data) email-old (:email-old data)] (if (some nil? [email email-old]) true (not= email email-old))))}, :us-state {:message "Please select state", :validator (fn [v data _] (let [country (:country data)] (not (and (= "United States" country) (or (= "State *" v) (nil? v) (empty? v))))))}, :password-confirmation {:message "Passwords don't match.", :validator password-confirmation}, :ok-password {:message "Password must contain at least 8 characters.", :validator ok-password?}, :numeric {:message "Please enter a number.", :validator numeric?}, :numeric-with-decimal {:message "Value is not a valid type", :validator numeric-with-decimal?}, :phone {:message "Please enter a valid phone number.", :validator phone?}, :valid-us-state {:message "Please enter an US state", :validator valid-us-state?}, :valid-zipcode {:message "Please enter a valid zip code.", :validator valid-zipcode?}, :valid-country {:message "Please enter a valid country.", :validator valid-country?}, :valid-cardholder {:message "Please enter a cardholder name.", :validator cardholder-name}, :0> {:message "Please enter a value bigger than 0.", :validator (fn [v _ _] (if (not (not-empty? v nil nil)) true (< 0 (js/parseFloat v))))}, :0>100 {:message "Please enter a value between 0 and 100.", :validator number0>100?}}) (def validations$ (atom default-validations)) (defn register-validation! [key validator] (swap! validations$ assoc key validator)) (defn get-validator-message [validation-key] (or (get-in @validations$ [validation-key :message]) "Value failed validation.")) (defn to-validator "Helper function that extracts the validator definitions." [config] (v/validator (reduce-kv (fn [m attr v] (assoc m attr (map (fn [k] [k (get-in @validations$ [k :validator])]) v))) {} config)))
8cc2012bfe8b6f27765ff4a8eb640a4d12e6005f0dfade51fe5636c1e2831e98
hududed/cardano-cli-scripts
HelloWorldPerson.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE MultiParamTypeClasses # module Cardano.PlutusExample.HelloWorldPerson ( person , PersonDetails(..) , helloWorldSerialised , helloWorldSBS ) where import Prelude hiding (($)) import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1) import Codec.Serialise import qualified Data.ByteString.Short as SBS import qualified Data.ByteString.Lazy as LBS import Ledger hiding (singleton) import qualified Ledger.Typed.Scripts as Scripts import qualified PlutusTx import PlutusTx.Prelude as P hiding (Semigroup (..), unless) data PersonDetails = PersonDetails { pName :: P.ByteString , pDob :: P.ByteString } deriving Show PlutusTx.makeLift ''PersonDetails person :: PersonDetails person = PersonDetails { pName = "JJ Olatunji", pDob = "1989/09/09" } # INLINABLE helloWorld # helloWorld :: PersonDetails -> P.ByteString -> P.ByteString -> ScriptContext -> P.Bool helloWorld thePerson datum redeemer context = pName thePerson P.== datum P.&& pDob thePerson P.== redeemer As a ScriptInstance As a ScriptInstance -} data HelloWorld instance Scripts.ValidatorTypes HelloWorld where type instance DatumType HelloWorld = P.ByteString type instance RedeemerType HelloWorld = P.ByteString helloWorldInstance :: Scripts.TypedValidator HelloWorld helloWorldInstance = Scripts.mkTypedValidator @HelloWorld ($$(PlutusTx.compile [|| helloWorld ||]) `PlutusTx.applyCode` PlutusTx.liftCode person) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.wrapValidator @P.ByteString @P.ByteString {- As a Validator -} helloWorldValidator :: Validator helloWorldValidator = Scripts.validatorScript helloWorldInstance {- As a Script -} helloWorldScript :: Script helloWorldScript = unValidatorScript helloWorldValidator {- As a Short Byte String -} helloWorldSBS :: SBS.ShortByteString helloWorldSBS = SBS.toShort . LBS.toStrict $ serialise helloWorldScript {- As a Serialised Script -} helloWorldSerialised :: PlutusScript PlutusScriptV1 helloWorldSerialised = PlutusScriptSerialised helloWorldSBS
null
https://raw.githubusercontent.com/hududed/cardano-cli-scripts/6844548eb0f5f05d4756c3bd1bd6523de010147f/plutus-sources/plutus-helloworld/src/Cardano/PlutusExample/HelloWorldPerson.hs
haskell
# LANGUAGE OverloadedStrings # As a Validator As a Script As a Short Byte String As a Serialised Script
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE MultiParamTypeClasses # module Cardano.PlutusExample.HelloWorldPerson ( person , PersonDetails(..) , helloWorldSerialised , helloWorldSBS ) where import Prelude hiding (($)) import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1) import Codec.Serialise import qualified Data.ByteString.Short as SBS import qualified Data.ByteString.Lazy as LBS import Ledger hiding (singleton) import qualified Ledger.Typed.Scripts as Scripts import qualified PlutusTx import PlutusTx.Prelude as P hiding (Semigroup (..), unless) data PersonDetails = PersonDetails { pName :: P.ByteString , pDob :: P.ByteString } deriving Show PlutusTx.makeLift ''PersonDetails person :: PersonDetails person = PersonDetails { pName = "JJ Olatunji", pDob = "1989/09/09" } # INLINABLE helloWorld # helloWorld :: PersonDetails -> P.ByteString -> P.ByteString -> ScriptContext -> P.Bool helloWorld thePerson datum redeemer context = pName thePerson P.== datum P.&& pDob thePerson P.== redeemer As a ScriptInstance As a ScriptInstance -} data HelloWorld instance Scripts.ValidatorTypes HelloWorld where type instance DatumType HelloWorld = P.ByteString type instance RedeemerType HelloWorld = P.ByteString helloWorldInstance :: Scripts.TypedValidator HelloWorld helloWorldInstance = Scripts.mkTypedValidator @HelloWorld ($$(PlutusTx.compile [|| helloWorld ||]) `PlutusTx.applyCode` PlutusTx.liftCode person) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.wrapValidator @P.ByteString @P.ByteString helloWorldValidator :: Validator helloWorldValidator = Scripts.validatorScript helloWorldInstance helloWorldScript :: Script helloWorldScript = unValidatorScript helloWorldValidator helloWorldSBS :: SBS.ShortByteString helloWorldSBS = SBS.toShort . LBS.toStrict $ serialise helloWorldScript helloWorldSerialised :: PlutusScript PlutusScriptV1 helloWorldSerialised = PlutusScriptSerialised helloWorldSBS
79a1f887e0c3bfda6d49f61ffd44eb88589ded8ef9be8cc3df92b50da9f58532
binsec/haunted
sploit1.mli
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** Example: breaking a Write-what-where (outdated) *) class sploit1 : Trace_config.t -> object inherit Path_predicate.dse_analysis method generate_new_file : Smt_model.t -> unit end
null
https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/dynamic/examples/sploit1.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * Example: breaking a Write-what-where (outdated)
This file is part of BINSEC . Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . class sploit1 : Trace_config.t -> object inherit Path_predicate.dse_analysis method generate_new_file : Smt_model.t -> unit end
86f4bb92c417aaf8a0ac0f4f302aa820993eacf3c0b754753bf1980795d49aae
lojic/RacketChess
board-slow.rkt
#lang racket ;; Functions that are not speed sensitive (require "./board.rkt" "./global.rkt" "./piece.rkt") (provide get-pieces-file-rank) ;; Return a list of all pieces on the board in the following form: ;; ( (piece file rank) ;; (piece file rank) ;; ... ) ;; Where file & rank are characters e.g. # \c & # \4 (define (get-pieces-file-rank b [ pred? is-piece? ]) (define squares (board-squares b)) (for*/fold ([ result '() ]) ([ rank (in-range 8) ] [ file (in-range 8) ]) (let* ([ idx (file-rank->idx file rank) ] [ pos (idx->pos idx) ] [ piece (get-square (board-squares b) idx) ]) (if (pred? piece) (cons (list piece (string-ref pos 0) (string-ref pos 1)) result) result))))
null
https://raw.githubusercontent.com/lojic/RacketChess/115ca7fecca9eaf31f9b2f4ef59935372c9920c8/src/board-slow.rkt
racket
Functions that are not speed sensitive Return a list of all pieces on the board in the following form: ( (piece file rank) (piece file rank) ... )
#lang racket (require "./board.rkt" "./global.rkt" "./piece.rkt") (provide get-pieces-file-rank) Where file & rank are characters e.g. # \c & # \4 (define (get-pieces-file-rank b [ pred? is-piece? ]) (define squares (board-squares b)) (for*/fold ([ result '() ]) ([ rank (in-range 8) ] [ file (in-range 8) ]) (let* ([ idx (file-rank->idx file rank) ] [ pos (idx->pos idx) ] [ piece (get-square (board-squares b) idx) ]) (if (pred? piece) (cons (list piece (string-ref pos 0) (string-ref pos 1)) result) result))))
8cda902873c15680f4bcd64e9fb9b9836a133861ab518a6bb15764ef5e76b50e
MastodonC/kixi.datastore
file.clj
(ns kixi.datastore.file (:import [java.io File OutputStream])) (defn temp-file ^File [name] (doto (File/createTempFile name ".tmp") .deleteOnExit)) (defn close [^OutputStream os] (.close os))
null
https://raw.githubusercontent.com/MastodonC/kixi.datastore/f33bba4b1fdd8c56cc7ac0f559ffe35254c9ca99/src/kixi/datastore/file.clj
clojure
(ns kixi.datastore.file (:import [java.io File OutputStream])) (defn temp-file ^File [name] (doto (File/createTempFile name ".tmp") .deleteOnExit)) (defn close [^OutputStream os] (.close os))
30b4c22b6c36b0109e934be34408048c062df91f83b4e641c9cafb0887e1829b
phoe-trash/gateway
standard-persona.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; GATEWAY " phoe " Herda 2016 ;;;; standard-persona.lisp (in-package #:gateway) (defclass standard-persona (persona) ((%name :accessor name :initarg :name :initform "Must provide name.") (%player :accessor player :initarg :player :initform nil) (%owner :accessor owner :initarg :owner :initform nil) (%chats :accessor chats :initform ()) (%lock :accessor lock))) (defconstructor (standard-persona) (unless (owner standard-persona) (setf (owner standard-persona) (player standard-persona))) (setf (lock standard-persona) (make-lock (format nil "Lock for persona ~S" (name standard-persona))))) (defun %make-persona (name &optional owner) (make-instance 'standard-persona :name name :player owner :owner owner))
null
https://raw.githubusercontent.com/phoe-trash/gateway/a8d579ccbafcaee8678caf59d365ec2eab0b1a7e/_old/classes/standard-persona.lisp
lisp
GATEWAY standard-persona.lisp
" phoe " Herda 2016 (in-package #:gateway) (defclass standard-persona (persona) ((%name :accessor name :initarg :name :initform "Must provide name.") (%player :accessor player :initarg :player :initform nil) (%owner :accessor owner :initarg :owner :initform nil) (%chats :accessor chats :initform ()) (%lock :accessor lock))) (defconstructor (standard-persona) (unless (owner standard-persona) (setf (owner standard-persona) (player standard-persona))) (setf (lock standard-persona) (make-lock (format nil "Lock for persona ~S" (name standard-persona))))) (defun %make-persona (name &optional owner) (make-instance 'standard-persona :name name :player owner :owner owner))
85e3bc3612109939ad61bd2997822f46878023714d0112f5cadad7851fe557b5
yeller/logfmt
logfmt.clj
(ns logfmt (:require [clojure.string :as s])) (defn ^String msg "takes a series of k/v pairs and turns them into a formatted string. retains order of the pairs" [& pairs] (s/join " " (map (fn [[k v]] (str (name k) "=" v)) (partition 2 pairs)))) (defn ^String map->msg "takes a map, and turns it into a logfmt string. sorts the order of the keys output, so your log messages are stable" [m] (s/join " " (map (fn [[k v]] (str (name k) "=" v)) m))) (defn atomic-literal? [x] (or (string? x) (keyword? x) (number? x))) (defn format-pairs "helper function for out and err expands any literal values into string values, doing string concatenation at compile time" [pairs] (let [partitioned-pairs (partition 2 pairs)] `(str ~@(loop [[k v :as current] (first partitioned-pairs) remaining (rest partitioned-pairs) out []] (if (nil? current) out (recur (first remaining) (rest remaining) (if (first out) (if (atomic-literal? v) (conj out (str " " (name k) "=" v)) (conj out (str " " (name k) "=") v)) (if (atomic-literal? v) (conj out (str (name k) "=" v)) (conj out (str (name k) "=") v))))))))) (defn safe-println "a println that doesn't have race conditions" [x] (.write *out* (str x "\n"))) (defmacro out "formats a static pair of keys/values and logs it to stdout. Specifically designed for speed - does a bunch of string concatenation at compile time (out :foo a) expands to something like (println (str \"foo= \" a)) (out :foo a :bar 1) expands to something like (println (str \"foo= \" a \" bar=1\")) " [& pairs] `(safe-println ~(format-pairs pairs))) (defmacro err "formats a static pair of keys/values and logs it to stderr. Specifically designed for speed - does a bunch of string concatenation at compile time expands exactly like logfmt/out, except it prints to stderr" [& pairs] (binding [*out* *err*] `(safe-println ~(format-pairs pairs))))
null
https://raw.githubusercontent.com/yeller/logfmt/381af9fe7717b64a79f3eba617ccceeb59b77323/src/logfmt.clj
clojure
(ns logfmt (:require [clojure.string :as s])) (defn ^String msg "takes a series of k/v pairs and turns them into a formatted string. retains order of the pairs" [& pairs] (s/join " " (map (fn [[k v]] (str (name k) "=" v)) (partition 2 pairs)))) (defn ^String map->msg "takes a map, and turns it into a logfmt string. sorts the order of the keys output, so your log messages are stable" [m] (s/join " " (map (fn [[k v]] (str (name k) "=" v)) m))) (defn atomic-literal? [x] (or (string? x) (keyword? x) (number? x))) (defn format-pairs "helper function for out and err expands any literal values into string values, doing string concatenation at compile time" [pairs] (let [partitioned-pairs (partition 2 pairs)] `(str ~@(loop [[k v :as current] (first partitioned-pairs) remaining (rest partitioned-pairs) out []] (if (nil? current) out (recur (first remaining) (rest remaining) (if (first out) (if (atomic-literal? v) (conj out (str " " (name k) "=" v)) (conj out (str " " (name k) "=") v)) (if (atomic-literal? v) (conj out (str (name k) "=" v)) (conj out (str (name k) "=") v))))))))) (defn safe-println "a println that doesn't have race conditions" [x] (.write *out* (str x "\n"))) (defmacro out "formats a static pair of keys/values and logs it to stdout. Specifically designed for speed - does a bunch of string concatenation at compile time (out :foo a) expands to something like (println (str \"foo= \" a)) (out :foo a :bar 1) expands to something like (println (str \"foo= \" a \" bar=1\")) " [& pairs] `(safe-println ~(format-pairs pairs))) (defmacro err "formats a static pair of keys/values and logs it to stderr. Specifically designed for speed - does a bunch of string concatenation at compile time expands exactly like logfmt/out, except it prints to stderr" [& pairs] (binding [*out* *err*] `(safe-println ~(format-pairs pairs))))
ae694c5b1e776015cf53a205851553b289e8ac94bfa0d9162d577cf495f99b40
circuithub/rel8
Eq.hs
{-# language FlexibleContexts #-} # language FlexibleInstances # # language MonoLocalBinds # # language MultiParamTypeClasses # # language StandaloneKindSignatures # {-# language UndecidableInstances #-} module Rel8.Type.Eq ( DBEq ) where -- aeson import Data.Aeson ( Value ) -- base import Data.List.NonEmpty ( NonEmpty ) import Data.Int ( Int16, Int32, Int64 ) import Data.Kind ( Constraint, Type ) import Prelude -- bytestring import Data.ByteString ( ByteString ) import qualified Data.ByteString.Lazy as Lazy ( ByteString ) -- case-insensitive import Data.CaseInsensitive ( CI ) -- rel8 import Rel8.Schema.Null ( Sql ) import Rel8.Type ( DBType ) -- scientific import Data.Scientific ( Scientific ) -- text import Data.Text ( Text ) import qualified Data.Text.Lazy as Lazy ( Text ) -- time import Data.Time.Calendar ( Day ) import Data.Time.Clock ( UTCTime ) import Data.Time.LocalTime ( CalendarDiffTime, LocalTime, TimeOfDay ) -- uuid import Data.UUID ( UUID ) -- | Database types that can be compared for equality in queries. If a type is an instance of ' DBEq ' , it means we can compare expressions for equality -- using the SQL @=@ operator. type DBEq :: Type -> Constraint class DBType a => DBEq a instance DBEq Bool instance DBEq Char instance DBEq Int16 instance DBEq Int32 instance DBEq Int64 instance DBEq Float instance DBEq Double instance DBEq Scientific instance DBEq UTCTime instance DBEq Day instance DBEq LocalTime instance DBEq TimeOfDay instance DBEq CalendarDiffTime instance DBEq Text instance DBEq Lazy.Text instance DBEq (CI Text) instance DBEq (CI Lazy.Text) instance DBEq ByteString instance DBEq Lazy.ByteString instance DBEq UUID instance DBEq Value instance Sql DBEq a => DBEq [a] instance Sql DBEq a => DBEq (NonEmpty a)
null
https://raw.githubusercontent.com/circuithub/rel8/93638f8bdf98023fb5ac2d9b38867af51561a063/src/Rel8/Type/Eq.hs
haskell
# language FlexibleContexts # # language UndecidableInstances # aeson base bytestring case-insensitive rel8 scientific text time uuid | Database types that can be compared for equality in queries. If a type is using the SQL @=@ operator.
# language FlexibleInstances # # language MonoLocalBinds # # language MultiParamTypeClasses # # language StandaloneKindSignatures # module Rel8.Type.Eq ( DBEq ) where import Data.Aeson ( Value ) import Data.List.NonEmpty ( NonEmpty ) import Data.Int ( Int16, Int32, Int64 ) import Data.Kind ( Constraint, Type ) import Prelude import Data.ByteString ( ByteString ) import qualified Data.ByteString.Lazy as Lazy ( ByteString ) import Data.CaseInsensitive ( CI ) import Rel8.Schema.Null ( Sql ) import Rel8.Type ( DBType ) import Data.Scientific ( Scientific ) import Data.Text ( Text ) import qualified Data.Text.Lazy as Lazy ( Text ) import Data.Time.Calendar ( Day ) import Data.Time.Clock ( UTCTime ) import Data.Time.LocalTime ( CalendarDiffTime, LocalTime, TimeOfDay ) import Data.UUID ( UUID ) an instance of ' DBEq ' , it means we can compare expressions for equality type DBEq :: Type -> Constraint class DBType a => DBEq a instance DBEq Bool instance DBEq Char instance DBEq Int16 instance DBEq Int32 instance DBEq Int64 instance DBEq Float instance DBEq Double instance DBEq Scientific instance DBEq UTCTime instance DBEq Day instance DBEq LocalTime instance DBEq TimeOfDay instance DBEq CalendarDiffTime instance DBEq Text instance DBEq Lazy.Text instance DBEq (CI Text) instance DBEq (CI Lazy.Text) instance DBEq ByteString instance DBEq Lazy.ByteString instance DBEq UUID instance DBEq Value instance Sql DBEq a => DBEq [a] instance Sql DBEq a => DBEq (NonEmpty a)
f94edcbe7b38df1dfbca1762921f38a2c001554301f210180a6e6e79457d8888
fogus/thneed
maps.clj
(ns fogus.maps (:require fogus.meta)) (defn keys-apply [m ks f] "Takes a function, a set of keys, and a map and applies the function to the map on the given keys. A new map of the results of the function applied to the keyed entries is returned." (let [only (select-keys m ks)] (zipmap (keys only) (map f (vals only))))) (defn manip-map [m ks f] "Takes a function, a set of keys, and a map and applies the function to the map on the given keys. A modified version of the original map is returned with the results of the function applied to each keyed entry." (conj m (keys-apply m ks f))) (defn manip-keys [m ks f] (reduce (fn [acc key] (if-let [v (get m key)] (-> acc (dissoc key) (assoc (f key) v)) m)) m ks)) (comment (keys-apply {:a 1, :b 2, :c 3} [:a :c] inc) = > { : a 2 , : c 4 } (manip-map {:a 1, :b 2, :c 3} [:a :c] inc) = > { : c 4 , : b 2 , : a 2 } (manip-keys {:a 1, :b 2} [:a] str) = > { : b 2 , " : a " 1 } ) (defn assoc-iff ([m k v] (if (nil? v) (fogus.meta/mupdate m ::missed-keys (fnil conj #{}) k) (assoc m k v))) ([m k v & kvs] (reduce (fn [m [k v]] (assoc-iff m k v)) (assoc-iff m k v) (partition 2 kvs)))) (defn deep-merge [& vals] (if (every? map? vals) (apply merge-with deep-merge vals) (last vals))) (comment (-> {} (assoc-iff :a 1, :b 2, :c nil) meta) (deep-merge {:a 1} {:b 2} {:b 3 :c {:d 1}} {:c {:d 2}}) )
null
https://raw.githubusercontent.com/fogus/thneed/0d791418b7b20a1249c52c925eac0f1254756eff/src/fogus/maps.clj
clojure
(ns fogus.maps (:require fogus.meta)) (defn keys-apply [m ks f] "Takes a function, a set of keys, and a map and applies the function to the map on the given keys. A new map of the results of the function applied to the keyed entries is returned." (let [only (select-keys m ks)] (zipmap (keys only) (map f (vals only))))) (defn manip-map [m ks f] "Takes a function, a set of keys, and a map and applies the function to the map on the given keys. A modified version of the original map is returned with the results of the function applied to each keyed entry." (conj m (keys-apply m ks f))) (defn manip-keys [m ks f] (reduce (fn [acc key] (if-let [v (get m key)] (-> acc (dissoc key) (assoc (f key) v)) m)) m ks)) (comment (keys-apply {:a 1, :b 2, :c 3} [:a :c] inc) = > { : a 2 , : c 4 } (manip-map {:a 1, :b 2, :c 3} [:a :c] inc) = > { : c 4 , : b 2 , : a 2 } (manip-keys {:a 1, :b 2} [:a] str) = > { : b 2 , " : a " 1 } ) (defn assoc-iff ([m k v] (if (nil? v) (fogus.meta/mupdate m ::missed-keys (fnil conj #{}) k) (assoc m k v))) ([m k v & kvs] (reduce (fn [m [k v]] (assoc-iff m k v)) (assoc-iff m k v) (partition 2 kvs)))) (defn deep-merge [& vals] (if (every? map? vals) (apply merge-with deep-merge vals) (last vals))) (comment (-> {} (assoc-iff :a 1, :b 2, :c nil) meta) (deep-merge {:a 1} {:b 2} {:b 3 :c {:d 1}} {:c {:d 2}}) )
13c3ccc818c131000626689c0b7dc1bf60e1a928711558effc7af7401e1475ac
jasonstolaruk/CurryMUD
Database.hs
# LANGUAGE DeriveGeneric , DuplicateRecordFields , OverloadedStrings , RecordWildCards , TypeApplications , ViewPatterns # module Mud.Misc.Database ( AdminChanRec(..) , AdminMsgRec(..) , AlertExecRec(..) , AlertMsgRec(..) , BanHostRec(..) , BanPCRec(..) , BonusRec(..) , BugRec(..) , ChanRec(..) , CountDbTblRecsFun , DiscoverRec(..) , DbTblName , ProfRec(..) , PropNameRec(..) , PurgeDbTblFun , QuestionRec(..) , SacBonusRec(..) , SacrificeRec(..) , SecRec(..) , TTypeRec(..) , TeleRec(..) , TelnetCharsRec(..) , TypoRec(..) , UnPwRec(..) , WordRec(..) , countDbTblRecsAdminChan , countDbTblRecsAdminMsg , countDbTblRecsChan , countDbTblRecsPropNames , countDbTblRecsQuestion , countDbTblRecsTele , countDbTblRecsWords , createDbTbls , dbOperation , deleteDbTblRec , deleteDbTblRecs , getDbTblRecs , insertDbTblAdminChan , insertDbTblAdminMsg , insertDbTblAlertExec , insertDbTblAlertMsg , insertDbTblBanHost , insertDbTblBanPC , insertDbTblBonus , insertDbTblBug , insertDbTblChan , insertDbTblDiscover , insertDbTblProf , insertDbTblQuestion , insertDbTblSacBonus , insertDbTblSacrifice , insertDbTblSec , insertDbTblTType , insertDbTblTele , insertDbTblTelnetChars , insertDbTblTypo , insertDbTblUnPw , insertPropNames , insertWords , lookupBonuses , lookupBonusesFromTo , lookupPW , lookupPropName , lookupSacBonusTime , lookupSacrifices , lookupSec , lookupTeleNames , lookupWord , purgeDbTblAdminChan , purgeDbTblAdminMsg , purgeDbTblChan , purgeDbTblQuestion , purgeDbTblTele ) where import Mud.Data.State.MudData import Mud.Data.State.Util.Locks import Mud.TopLvlDefs.FilePaths import Mud.TopLvlDefs.Misc import Mud.Util.Misc import Mud.Util.Quoting import Control.Monad (forM_, when) import Control.Monad.IO.Class (liftIO) import Crypto.BCrypt (fastBcryptHashingPolicy, hashPasswordUsingPolicy) import Data.Aeson (FromJSON(..), ToJSON(..)) import qualified Data.ByteString.Char8 as B import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy as LT import Data.Time (UTCTime) import Database.SQLite.Simple (Connection, FromRow, Only(..), Query(..), ToRow, execute, execute_, field, fromRow, query, query_, toRow, withConnection) import GHC.Generics (Generic) data AdminChanRec = AdminChanRec { dbTimestamp :: Text , dbName :: Text , dbMsg :: Text } data AdminMsgRec = AdminMsgRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbMsg :: Text } data AlertExecRec = AlertExecRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbCmdName :: Text , dbTarget :: Text , dbArgs :: Text } deriving Generic data AlertMsgRec = AlertMsgRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbCmdName :: Text , dbTrigger :: Text , dbMsg :: Text } deriving Generic data BanHostRec = BanHostRec { dbId :: Maybe Int , dbTimestamp :: Text , dbHost :: Text , dbIsBanned :: Bool , dbReason :: Text } deriving Generic data BanPCRec = BanPCRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbIsBanned :: Bool , dbReason :: Text } deriving Generic data BonusRec = BonusRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbAmt :: Int } data BugRec = BugRec { dbTimestamp :: Text , dbName :: Text , dbLoc :: Text , dbDesc :: Text } deriving Generic data ChanRec = ChanRec { dbTimestamp :: Text , dbChanId :: Int , dbChanName :: Text , dbName :: Text , dbMsg :: Text } data DiscoverRec = DiscoverRec { dbTimestamp :: Text , dbHost :: Text , dbMsg :: Text } deriving Generic data ProfRec = ProfRec { dbTimestamp :: Text , dbHost :: Text , dbProfanity :: Text } deriving Generic newtype PropNameRec = PropNameRec { dbWord :: Text } deriving Generic data QuestionRec = QuestionRec { dbTimestamp :: Text , dbName :: Text , dbMsg :: Text } data SacBonusRec = SacBonusRec { dbUTCTime :: Text , dbName :: Text , dbGodName :: Text } data SacrificeRec = SacrificeRec { dbUTCTime :: Text , dbName :: Text , dbGodName :: Text } data SecRec = SecRec { dbName :: Text , dbQ :: Text , dbA :: Text } deriving Eq data TeleRec = TeleRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbMsg :: Text } data TelnetCharsRec = TelnetCharsRec { dbTimestamp :: Text , dbHost :: Text , dbTelnetChars :: Text } deriving Generic data TTypeRec = TTypeRec { dbTimestamp :: Text , dbHost :: Text , dbTType :: Text } deriving Generic data TypoRec = TypoRec { dbTimestamp :: Text , dbName :: Text , dbLoc :: Text , dbDesc :: Text } deriving Generic data UnPwRec = UnPwRec { dbUn :: Text , dbPw :: Text } newtype WordRec = WordRec { dbWord :: Text } deriving Generic ----- instance FromRow AdminChanRec where fromRow = AdminChanRec <$ field @Int <*> field <*> field <*> field instance FromRow AdminMsgRec where fromRow = AdminMsgRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow AlertExecRec where fromRow = AlertExecRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field <*> field instance FromRow AlertMsgRec where fromRow = AlertMsgRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field <*> field instance FromRow BanHostRec where fromRow = BanHostRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field instance FromRow BanPCRec where fromRow = BanPCRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field instance FromRow BonusRec where fromRow = BonusRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow BugRec where fromRow = BugRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow ChanRec where fromRow = ChanRec <$ field @Int <*> field <*> field <*> field <*> field <*> field instance FromRow DiscoverRec where fromRow = DiscoverRec <$ field @Int <*> field <*> field <*> field instance FromRow ProfRec where fromRow = ProfRec <$ field @Int <*> field <*> field <*> field instance FromRow PropNameRec where fromRow = PropNameRec <$ field @Int <*> field instance FromRow QuestionRec where fromRow = QuestionRec <$ field @Int <*> field <*> field <*> field instance FromRow SacBonusRec where fromRow = SacBonusRec <$ field @Int <*> field <*> field <*> field instance FromRow SacrificeRec where fromRow = SacrificeRec <$ field @Int <*> field <*> field <*> field instance FromRow SecRec where fromRow = SecRec <$ field @Int <*> field <*> field <*> field instance FromRow TeleRec where fromRow = TeleRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow TelnetCharsRec where fromRow = TelnetCharsRec <$ field @Int <*> field <*> field <*> field instance FromRow TTypeRec where fromRow = TTypeRec <$ field @Int <*> field <*> field <*> field instance FromRow TypoRec where fromRow = TypoRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow UnPwRec where fromRow = UnPwRec <$ field @Int <*> field <*> field instance FromRow WordRec where fromRow = WordRec <$ field @Int <*> field ----- instance ToRow AdminChanRec where toRow (AdminChanRec a b c) = toRow (a, b, c) instance ToRow AdminMsgRec where toRow (AdminMsgRec a b c d) = toRow (a, b, c, d) instance ToRow AlertExecRec where toRow (AlertExecRec _ a b c d e) = toRow (a, b, c, d, e) instance ToRow AlertMsgRec where toRow (AlertMsgRec _ a b c d e) = toRow (a, b, c, d, e) instance ToRow BanHostRec where toRow (BanHostRec _ a b c d) = toRow (a, b, c, d) instance ToRow BanPCRec where toRow (BanPCRec _ a b c d) = toRow (a, b, c, d) instance ToRow BonusRec where toRow (BonusRec a b c d) = toRow (a, b, c, d) instance ToRow BugRec where toRow (BugRec a b c d) = toRow (a, b, c, d) instance ToRow ChanRec where toRow (ChanRec a b c d e) = toRow (a, b, c, d, e) instance ToRow DiscoverRec where toRow (DiscoverRec a b c) = toRow (a, b, c) instance ToRow ProfRec where toRow (ProfRec a b c) = toRow (a, b, c) instance ToRow PropNameRec where toRow (PropNameRec a) = toRow . Only $ a instance ToRow QuestionRec where toRow (QuestionRec a b c) = toRow (a, b, c) instance ToRow SacBonusRec where toRow (SacBonusRec a b c) = toRow (a, b, c) instance ToRow SacrificeRec where toRow (SacrificeRec a b c) = toRow (a, b, c) instance ToRow SecRec where toRow (SecRec a b c) = toRow (a, b, c) instance ToRow TeleRec where toRow (TeleRec a b c d) = toRow (a, b, c, d) instance ToRow TelnetCharsRec where toRow (TelnetCharsRec a b c) = toRow (a, b, c) instance ToRow TTypeRec where toRow (TTypeRec a b c) = toRow (a, b, c) instance ToRow TypoRec where toRow (TypoRec a b c d) = toRow (a, b, c, d) instance ToRow UnPwRec where toRow (UnPwRec a b) = toRow (a, b) instance ToRow WordRec where toRow (WordRec a) = toRow . Only $ a ----- instance FromJSON AlertExecRec instance FromJSON AlertMsgRec instance FromJSON BanHostRec instance FromJSON BanPCRec instance FromJSON BugRec instance FromJSON DiscoverRec instance FromJSON ProfRec instance FromJSON PropNameRec instance FromJSON TelnetCharsRec instance FromJSON TTypeRec instance FromJSON TypoRec instance FromJSON WordRec instance ToJSON AlertExecRec instance ToJSON AlertMsgRec instance ToJSON BanHostRec instance ToJSON BanPCRec instance ToJSON BugRec instance ToJSON DiscoverRec instance ToJSON ProfRec instance ToJSON PropNameRec instance ToJSON TelnetCharsRec instance ToJSON TTypeRec instance ToJSON TypoRec instance ToJSON WordRec ----- dbOperation :: IO a -> MudStack a dbOperation f = liftIO . flip withLock f =<< getLock dbLock onDbFile :: (Connection -> IO a) -> IO a onDbFile f = flip withConnection f =<< mkMudFilePath dbFileFun createDbTbls :: IO () createDbTbls = onDbFile $ \conn -> do forM_ qs $ execute_ conn . Query x <- onlyIntsHelper <$> query_ conn (Query "select count(*) from unpw") when (isZero x) . execute conn (Query "insert into unpw (id, un, pw) values (2, 'Curry', ?)") . Only =<< hashPW "curry" execute conn (Query "insert or ignore into unpw (id, un, pw) values (1, 'Root', ?)") . Only =<< hashPW "root" where qs = [ "create table if not exists admin_chan (id integer primary key, timestamp text, name text, msg text)" , "create table if not exists admin_msg (id integer primary key, timestamp text, from_name text, to_name text, \ \msg text)" , "create table if not exists alert_exec (id integer primary key, timestamp text, name text, cmd_name text, \ \target text, args text)" , "create table if not exists alert_msg (id integer primary key, timestamp text, name text, cmd_name text, \ \trigger text, msg text)" , "create table if not exists ban_host (id integer primary key, timestamp text, host text, is_banned \ \integer, reason text)" , "create table if not exists ban_pc (id integer primary key, timestamp text, name text, is_banned \ \integer, reason text)" , "create table if not exists bonus (id integer primary key, timestamp text, from_name text, to_name text, \ \amt integer)" , "create table if not exists bug (id integer primary key, timestamp text, name text, loc text, desc text)" , "create table if not exists chan (id integer primary key, timestamp text, chan_id integer, chan_name \ \text, name text, msg text)" , "create table if not exists discover (id integer primary key, timestamp text, host text, msg text)" , "create table if not exists profanity (id integer primary key, timestamp text, host text, prof text)" , "create table if not exists prop_names (id integer primary key, prop_name text)" , "create table if not exists question (id integer primary key, timestamp text, name text, msg text)" , "create table if not exists sac_bonus (id integer primary key, utc_time text, name text, god_name text)" , "create table if not exists sacrifice (id integer primary key, utc_time text, name text, god_name text)" , "create table if not exists sec (id integer primary key, name text, question text, answer text)" , "create table if not exists tele (id integer primary key, timestamp text, from_name text, to_name text, \ \msg text)" , "create table if not exists telnet_chars (id integer primary key, timestamp text, host text, telnet_chars text)" , "create table if not exists ttype (id integer primary key, timestamp text, host text, ttype text)" , "create table if not exists typo (id integer primary key, timestamp text, name text, loc text, desc text)" , "create table if not exists unpw (id integer primary key, un text, pw text)" , "create table if not exists words (id integer primary key, word text)" ] onlyIntsHelper :: [Only Int] -> Int onlyIntsHelper [] = 0 onlyIntsHelper (Only x:_) = x hashPW :: String -> IO Text hashPW = maybeEmp TE.decodeUtf8 `fmap2` (hashPasswordUsingPolicy fastBcryptHashingPolicy . B.pack) ----- type DbTblName = Text getDbTblRecs :: (FromRow a) => DbTblName -> IO [a] getDbTblRecs tblName = onDbFile (\conn -> query_ conn . Query $ "select * from " <> tblName) deleteDbTblRec :: DbTblName -> Int -> IO () deleteDbTblRec tblName i = onDbFile $ \conn -> execute conn (Query $ "delete from " <> tblName <> " where id=?") . Only $ i deleteDbTblRecs :: DbTblName -> IO () deleteDbTblRecs tblName = onDbFile (\conn -> execute_ conn . Query $ "delete from " <> tblName) ----- insertDbTblHelper :: (ToRow a) => Query -> a -> IO () insertDbTblHelper q x = onDbFile $ \conn -> execute conn q x insertDbTblAdminChan :: AdminChanRec -> IO () insertDbTblAdminChan = insertDbTblHelper "insert into admin_chan (timestamp, name, msg) values (?, ?, ?)" insertDbTblAdminMsg :: AdminMsgRec -> IO () insertDbTblAdminMsg = insertDbTblHelper "insert into admin_msg (timestamp, from_name, to_name, msg) values (?, ?, ?, ?)" insertDbTblAlertExec :: AlertExecRec -> IO () insertDbTblAlertExec = insertDbTblHelper "insert into alert_exec (timestamp, name, cmd_name, target, args) values \ \(?, ?, ?, ?, ?)" insertDbTblAlertMsg :: AlertMsgRec -> IO () insertDbTblAlertMsg = insertDbTblHelper "insert into alert_msg (timestamp, name, cmd_name, trigger, msg) values \ \(?, ?, ?, ?, ?)" insertDbTblBanHost :: BanHostRec -> IO () insertDbTblBanHost = insertDbTblHelper "insert into ban_host (timestamp, host, is_banned, reason) values (?, ?, ?, ?)" insertDbTblBanPC :: BanPCRec -> IO () insertDbTblBanPC = insertDbTblHelper "insert into ban_pc (timestamp, name, is_banned, reason) values (?, ?, ?, ?)" insertDbTblBonus :: BonusRec -> IO () insertDbTblBonus = insertDbTblHelper "insert into bonus (timestamp, from_name, to_name, amt) values (?, ?, ?, ?)" insertDbTblBug :: BugRec -> IO () insertDbTblBug = insertDbTblHelper "insert into bug (timestamp, name, loc, desc) values (?, ?, ?, ?)" insertDbTblChan :: ChanRec -> IO () insertDbTblChan = insertDbTblHelper "insert into chan (timestamp, chan_id, chan_name, name, msg) values (?, ?, ?, ?, ?)" insertDbTblDiscover :: DiscoverRec -> IO () insertDbTblDiscover = insertDbTblHelper "insert into discover (timestamp, host, msg) values (?, ?, ?)" insertDbTblProf :: ProfRec -> IO () insertDbTblProf = insertDbTblHelper "insert into profanity (timestamp, host, prof) values (?, ?, ?)" insertDbTblQuestion :: QuestionRec -> IO () insertDbTblQuestion = insertDbTblHelper "insert into question (timestamp, name, msg) values (?, ?, ?)" insertDbTblSacBonus :: SacBonusRec -> IO () insertDbTblSacBonus = insertDbTblHelper "insert into sac_bonus (utc_time, name, god_name) values (?, ?, ?)" insertDbTblSacrifice :: SacrificeRec -> IO () insertDbTblSacrifice = insertDbTblHelper "insert into sacrifice (utc_time, name, god_name) values (?, ?, ?)" insertDbTblSec :: SecRec -> IO () insertDbTblSec = insertDbTblHelper "insert into sec (name, question, answer) values (?, ?, ?)" insertDbTblTele :: TeleRec -> IO () insertDbTblTele = insertDbTblHelper "insert into tele (timestamp, from_name, to_name, msg) values (?, ?, ?, ?)" insertDbTblTelnetChars :: TelnetCharsRec -> IO () insertDbTblTelnetChars = insertDbTblHelper "insert into telnet_chars (timestamp, host, telnet_chars) values (?, ?, ?)" insertDbTblTType :: TTypeRec -> IO () insertDbTblTType = insertDbTblHelper "insert into ttype (timestamp, host, ttype) values (?, ?, ?)" insertDbTblTypo :: TypoRec -> IO () insertDbTblTypo = insertDbTblHelper "insert into typo (timestamp, name, loc, desc) values (?, ?, ?, ?)" insertDbTblUnPw :: UnPwRec -> IO () insertDbTblUnPw rec@UnPwRec { .. } = hashPW (T.unpack dbPw) >>= \pw -> onDbFile $ \conn -> do execute conn "delete from unpw where un=?" . Only $ dbUn execute conn "insert into unpw (un, pw) values (?, ?)" rec { dbPw = pw } ----- type CountDbTblRecsFun = IO Int countDbTblRecsAdminChan :: CountDbTblRecsFun countDbTblRecsAdminChan = countHelper "admin_chan" countDbTblRecsAdminMsg :: CountDbTblRecsFun countDbTblRecsAdminMsg = countHelper "admin_msg" countDbTblRecsChan :: CountDbTblRecsFun countDbTblRecsChan = countHelper "chan" countDbTblRecsPropNames :: CountDbTblRecsFun countDbTblRecsPropNames = countHelper "prop_names" countDbTblRecsQuestion :: CountDbTblRecsFun countDbTblRecsQuestion = countHelper "question" countDbTblRecsTele :: CountDbTblRecsFun countDbTblRecsTele = countHelper "tele" countDbTblRecsWords :: CountDbTblRecsFun countDbTblRecsWords = countHelper "words" countHelper :: DbTblName -> IO Int countHelper tblName = let q = Query $ "select count(*) from " <> tblName in onDbFile $ \conn -> onlyIntsHelper <$> query_ conn q ----- type PurgeDbTblFun = IO () purgeDbTblAdminChan :: PurgeDbTblFun purgeDbTblAdminChan = purgeHelper "admin_chan" purgeDbTblAdminMsg :: PurgeDbTblFun purgeDbTblAdminMsg = purgeHelper "admin_msg" purgeDbTblChan :: PurgeDbTblFun purgeDbTblChan = purgeHelper "chan" purgeDbTblQuestion :: PurgeDbTblFun purgeDbTblQuestion = purgeHelper "question" purgeDbTblTele :: PurgeDbTblFun purgeDbTblTele = purgeHelper "tele" purgeHelper :: DbTblName -> IO () purgeHelper tblName = onDbFile $ \conn -> execute conn q (Only noOfDbTblRecsToPurge) where q = Query . T.concat $ [ "delete from ", tblName, " where id in (select id from ", tblName, " limit ?)" ] ----- lookupPropName :: Text -> IO (Maybe Text) lookupPropName txt = let q = Query "select prop_name from prop_names where prop_name = ? collate nocase" in onDbFile $ \conn -> onlyTxtsHelper <$> query conn q (Only txt) onlyTxtsHelper :: [Only Text] -> Maybe Text onlyTxtsHelper = listToMaybe . map fromOnly lookupBonuses :: Sing -> IO [BonusRec] lookupBonuses s = let q = Query "select * from bonus where from_name = ? or to_name = ?" in onDbFile $ \conn -> query conn q . dup $ s lookupBonusesFromTo :: Sing -> Sing -> IO Int lookupBonusesFromTo fromSing toSing = let q = Query "select count(*) from bonus where from_name = ? and to_name = ?" in onDbFile $ \conn -> onlyIntsHelper <$> query conn q (fromSing, toSing) lookupPW :: Sing -> IO (Maybe Text) lookupPW s = onDbFile $ \conn -> onlyTxtsHelper <$> query conn (Query "select pw from unpw where un = ?") (Only s) lookupSacBonusTime :: Sing -> Text -> IO (Maybe UTCTime) -- When was the last sacrifice bonus given? lookupSacBonusTime s gn = let q = Query "select utc_time from sac_bonus where name = ? and god_name = ?" in onDbFile $ \conn -> f <$> query conn q (s, gn) where f (reverse -> (Only t:_)) = case reads t of [(time, "")] -> Just time _ -> Nothing f _ = Nothing lookupSacrifices :: Sing -> Text -> IO Int -- How many sacrifices have been made? lookupSacrifices s gn = let q = Query "select count(*) from sacrifice where name = ? and god_name = ?" in onDbFile $ \conn -> onlyIntsHelper <$> query conn q (s, gn) lookupSec :: Sing -> IO [SecRec] lookupSec s = onDbFile $ \conn -> query conn (Query "select * from sec where name = ?") (Only s) lookupTeleNames :: Sing -> IO [Text] lookupTeleNames s = onDbFile $ \conn -> map fromOnly <$> query conn (Query t) (dup4 s) where t = "select case\ \ when from_name != ? then from_name\ \ when to_name != ? then to_name\ \ end as name \ \from (select from_name, to_name from tele where from_name = ? or to_name = ?)" lookupWord :: Text -> IO (Maybe Text) lookupWord txt = onDbFile $ \conn -> let t = "select word from words where word = ? collate nocase" in onlyTxtsHelper <$> query conn (Query t) (Only txt) ----- insertPropNames :: LT.Text -> IO () insertPropNames = procSrcFileTxt "prop_names" "prop_name" procSrcFileTxt :: Text -> Text -> LT.Text -> IO () procSrcFileTxt tblName colName = onDbFile . flip execute_ . buildQuery where buildQuery = let txt = T.concat [ "insert into ", tblName, " ", parensQuote colName, " values " ] in Query . (txt <>) . LT.toStrict . buildVals buildVals txt = LT.intercalate ", " [ "(\"" <> t <> "\")" | t <- LT.lines txt ] insertWords :: LT.Text -> IO () insertWords = procSrcFileTxt "words" "word"
null
https://raw.githubusercontent.com/jasonstolaruk/CurryMUD/f9775fb3ede08610f33f27bb1fb5fc0565e98266/lib/Mud/Misc/Database.hs
haskell
--- --- --- --- --- --- --- --- --- When was the last sacrifice bonus given? How many sacrifices have been made? ---
# LANGUAGE DeriveGeneric , DuplicateRecordFields , OverloadedStrings , RecordWildCards , TypeApplications , ViewPatterns # module Mud.Misc.Database ( AdminChanRec(..) , AdminMsgRec(..) , AlertExecRec(..) , AlertMsgRec(..) , BanHostRec(..) , BanPCRec(..) , BonusRec(..) , BugRec(..) , ChanRec(..) , CountDbTblRecsFun , DiscoverRec(..) , DbTblName , ProfRec(..) , PropNameRec(..) , PurgeDbTblFun , QuestionRec(..) , SacBonusRec(..) , SacrificeRec(..) , SecRec(..) , TTypeRec(..) , TeleRec(..) , TelnetCharsRec(..) , TypoRec(..) , UnPwRec(..) , WordRec(..) , countDbTblRecsAdminChan , countDbTblRecsAdminMsg , countDbTblRecsChan , countDbTblRecsPropNames , countDbTblRecsQuestion , countDbTblRecsTele , countDbTblRecsWords , createDbTbls , dbOperation , deleteDbTblRec , deleteDbTblRecs , getDbTblRecs , insertDbTblAdminChan , insertDbTblAdminMsg , insertDbTblAlertExec , insertDbTblAlertMsg , insertDbTblBanHost , insertDbTblBanPC , insertDbTblBonus , insertDbTblBug , insertDbTblChan , insertDbTblDiscover , insertDbTblProf , insertDbTblQuestion , insertDbTblSacBonus , insertDbTblSacrifice , insertDbTblSec , insertDbTblTType , insertDbTblTele , insertDbTblTelnetChars , insertDbTblTypo , insertDbTblUnPw , insertPropNames , insertWords , lookupBonuses , lookupBonusesFromTo , lookupPW , lookupPropName , lookupSacBonusTime , lookupSacrifices , lookupSec , lookupTeleNames , lookupWord , purgeDbTblAdminChan , purgeDbTblAdminMsg , purgeDbTblChan , purgeDbTblQuestion , purgeDbTblTele ) where import Mud.Data.State.MudData import Mud.Data.State.Util.Locks import Mud.TopLvlDefs.FilePaths import Mud.TopLvlDefs.Misc import Mud.Util.Misc import Mud.Util.Quoting import Control.Monad (forM_, when) import Control.Monad.IO.Class (liftIO) import Crypto.BCrypt (fastBcryptHashingPolicy, hashPasswordUsingPolicy) import Data.Aeson (FromJSON(..), ToJSON(..)) import qualified Data.ByteString.Char8 as B import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy as LT import Data.Time (UTCTime) import Database.SQLite.Simple (Connection, FromRow, Only(..), Query(..), ToRow, execute, execute_, field, fromRow, query, query_, toRow, withConnection) import GHC.Generics (Generic) data AdminChanRec = AdminChanRec { dbTimestamp :: Text , dbName :: Text , dbMsg :: Text } data AdminMsgRec = AdminMsgRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbMsg :: Text } data AlertExecRec = AlertExecRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbCmdName :: Text , dbTarget :: Text , dbArgs :: Text } deriving Generic data AlertMsgRec = AlertMsgRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbCmdName :: Text , dbTrigger :: Text , dbMsg :: Text } deriving Generic data BanHostRec = BanHostRec { dbId :: Maybe Int , dbTimestamp :: Text , dbHost :: Text , dbIsBanned :: Bool , dbReason :: Text } deriving Generic data BanPCRec = BanPCRec { dbId :: Maybe Int , dbTimestamp :: Text , dbName :: Text , dbIsBanned :: Bool , dbReason :: Text } deriving Generic data BonusRec = BonusRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbAmt :: Int } data BugRec = BugRec { dbTimestamp :: Text , dbName :: Text , dbLoc :: Text , dbDesc :: Text } deriving Generic data ChanRec = ChanRec { dbTimestamp :: Text , dbChanId :: Int , dbChanName :: Text , dbName :: Text , dbMsg :: Text } data DiscoverRec = DiscoverRec { dbTimestamp :: Text , dbHost :: Text , dbMsg :: Text } deriving Generic data ProfRec = ProfRec { dbTimestamp :: Text , dbHost :: Text , dbProfanity :: Text } deriving Generic newtype PropNameRec = PropNameRec { dbWord :: Text } deriving Generic data QuestionRec = QuestionRec { dbTimestamp :: Text , dbName :: Text , dbMsg :: Text } data SacBonusRec = SacBonusRec { dbUTCTime :: Text , dbName :: Text , dbGodName :: Text } data SacrificeRec = SacrificeRec { dbUTCTime :: Text , dbName :: Text , dbGodName :: Text } data SecRec = SecRec { dbName :: Text , dbQ :: Text , dbA :: Text } deriving Eq data TeleRec = TeleRec { dbTimestamp :: Text , dbFromName :: Text , dbToName :: Text , dbMsg :: Text } data TelnetCharsRec = TelnetCharsRec { dbTimestamp :: Text , dbHost :: Text , dbTelnetChars :: Text } deriving Generic data TTypeRec = TTypeRec { dbTimestamp :: Text , dbHost :: Text , dbTType :: Text } deriving Generic data TypoRec = TypoRec { dbTimestamp :: Text , dbName :: Text , dbLoc :: Text , dbDesc :: Text } deriving Generic data UnPwRec = UnPwRec { dbUn :: Text , dbPw :: Text } newtype WordRec = WordRec { dbWord :: Text } deriving Generic instance FromRow AdminChanRec where fromRow = AdminChanRec <$ field @Int <*> field <*> field <*> field instance FromRow AdminMsgRec where fromRow = AdminMsgRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow AlertExecRec where fromRow = AlertExecRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field <*> field instance FromRow AlertMsgRec where fromRow = AlertMsgRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field <*> field instance FromRow BanHostRec where fromRow = BanHostRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field instance FromRow BanPCRec where fromRow = BanPCRec <$> field @(Maybe Int) <*> field <*> field <*> field <*> field instance FromRow BonusRec where fromRow = BonusRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow BugRec where fromRow = BugRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow ChanRec where fromRow = ChanRec <$ field @Int <*> field <*> field <*> field <*> field <*> field instance FromRow DiscoverRec where fromRow = DiscoverRec <$ field @Int <*> field <*> field <*> field instance FromRow ProfRec where fromRow = ProfRec <$ field @Int <*> field <*> field <*> field instance FromRow PropNameRec where fromRow = PropNameRec <$ field @Int <*> field instance FromRow QuestionRec where fromRow = QuestionRec <$ field @Int <*> field <*> field <*> field instance FromRow SacBonusRec where fromRow = SacBonusRec <$ field @Int <*> field <*> field <*> field instance FromRow SacrificeRec where fromRow = SacrificeRec <$ field @Int <*> field <*> field <*> field instance FromRow SecRec where fromRow = SecRec <$ field @Int <*> field <*> field <*> field instance FromRow TeleRec where fromRow = TeleRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow TelnetCharsRec where fromRow = TelnetCharsRec <$ field @Int <*> field <*> field <*> field instance FromRow TTypeRec where fromRow = TTypeRec <$ field @Int <*> field <*> field <*> field instance FromRow TypoRec where fromRow = TypoRec <$ field @Int <*> field <*> field <*> field <*> field instance FromRow UnPwRec where fromRow = UnPwRec <$ field @Int <*> field <*> field instance FromRow WordRec where fromRow = WordRec <$ field @Int <*> field instance ToRow AdminChanRec where toRow (AdminChanRec a b c) = toRow (a, b, c) instance ToRow AdminMsgRec where toRow (AdminMsgRec a b c d) = toRow (a, b, c, d) instance ToRow AlertExecRec where toRow (AlertExecRec _ a b c d e) = toRow (a, b, c, d, e) instance ToRow AlertMsgRec where toRow (AlertMsgRec _ a b c d e) = toRow (a, b, c, d, e) instance ToRow BanHostRec where toRow (BanHostRec _ a b c d) = toRow (a, b, c, d) instance ToRow BanPCRec where toRow (BanPCRec _ a b c d) = toRow (a, b, c, d) instance ToRow BonusRec where toRow (BonusRec a b c d) = toRow (a, b, c, d) instance ToRow BugRec where toRow (BugRec a b c d) = toRow (a, b, c, d) instance ToRow ChanRec where toRow (ChanRec a b c d e) = toRow (a, b, c, d, e) instance ToRow DiscoverRec where toRow (DiscoverRec a b c) = toRow (a, b, c) instance ToRow ProfRec where toRow (ProfRec a b c) = toRow (a, b, c) instance ToRow PropNameRec where toRow (PropNameRec a) = toRow . Only $ a instance ToRow QuestionRec where toRow (QuestionRec a b c) = toRow (a, b, c) instance ToRow SacBonusRec where toRow (SacBonusRec a b c) = toRow (a, b, c) instance ToRow SacrificeRec where toRow (SacrificeRec a b c) = toRow (a, b, c) instance ToRow SecRec where toRow (SecRec a b c) = toRow (a, b, c) instance ToRow TeleRec where toRow (TeleRec a b c d) = toRow (a, b, c, d) instance ToRow TelnetCharsRec where toRow (TelnetCharsRec a b c) = toRow (a, b, c) instance ToRow TTypeRec where toRow (TTypeRec a b c) = toRow (a, b, c) instance ToRow TypoRec where toRow (TypoRec a b c d) = toRow (a, b, c, d) instance ToRow UnPwRec where toRow (UnPwRec a b) = toRow (a, b) instance ToRow WordRec where toRow (WordRec a) = toRow . Only $ a instance FromJSON AlertExecRec instance FromJSON AlertMsgRec instance FromJSON BanHostRec instance FromJSON BanPCRec instance FromJSON BugRec instance FromJSON DiscoverRec instance FromJSON ProfRec instance FromJSON PropNameRec instance FromJSON TelnetCharsRec instance FromJSON TTypeRec instance FromJSON TypoRec instance FromJSON WordRec instance ToJSON AlertExecRec instance ToJSON AlertMsgRec instance ToJSON BanHostRec instance ToJSON BanPCRec instance ToJSON BugRec instance ToJSON DiscoverRec instance ToJSON ProfRec instance ToJSON PropNameRec instance ToJSON TelnetCharsRec instance ToJSON TTypeRec instance ToJSON TypoRec instance ToJSON WordRec dbOperation :: IO a -> MudStack a dbOperation f = liftIO . flip withLock f =<< getLock dbLock onDbFile :: (Connection -> IO a) -> IO a onDbFile f = flip withConnection f =<< mkMudFilePath dbFileFun createDbTbls :: IO () createDbTbls = onDbFile $ \conn -> do forM_ qs $ execute_ conn . Query x <- onlyIntsHelper <$> query_ conn (Query "select count(*) from unpw") when (isZero x) . execute conn (Query "insert into unpw (id, un, pw) values (2, 'Curry', ?)") . Only =<< hashPW "curry" execute conn (Query "insert or ignore into unpw (id, un, pw) values (1, 'Root', ?)") . Only =<< hashPW "root" where qs = [ "create table if not exists admin_chan (id integer primary key, timestamp text, name text, msg text)" , "create table if not exists admin_msg (id integer primary key, timestamp text, from_name text, to_name text, \ \msg text)" , "create table if not exists alert_exec (id integer primary key, timestamp text, name text, cmd_name text, \ \target text, args text)" , "create table if not exists alert_msg (id integer primary key, timestamp text, name text, cmd_name text, \ \trigger text, msg text)" , "create table if not exists ban_host (id integer primary key, timestamp text, host text, is_banned \ \integer, reason text)" , "create table if not exists ban_pc (id integer primary key, timestamp text, name text, is_banned \ \integer, reason text)" , "create table if not exists bonus (id integer primary key, timestamp text, from_name text, to_name text, \ \amt integer)" , "create table if not exists bug (id integer primary key, timestamp text, name text, loc text, desc text)" , "create table if not exists chan (id integer primary key, timestamp text, chan_id integer, chan_name \ \text, name text, msg text)" , "create table if not exists discover (id integer primary key, timestamp text, host text, msg text)" , "create table if not exists profanity (id integer primary key, timestamp text, host text, prof text)" , "create table if not exists prop_names (id integer primary key, prop_name text)" , "create table if not exists question (id integer primary key, timestamp text, name text, msg text)" , "create table if not exists sac_bonus (id integer primary key, utc_time text, name text, god_name text)" , "create table if not exists sacrifice (id integer primary key, utc_time text, name text, god_name text)" , "create table if not exists sec (id integer primary key, name text, question text, answer text)" , "create table if not exists tele (id integer primary key, timestamp text, from_name text, to_name text, \ \msg text)" , "create table if not exists telnet_chars (id integer primary key, timestamp text, host text, telnet_chars text)" , "create table if not exists ttype (id integer primary key, timestamp text, host text, ttype text)" , "create table if not exists typo (id integer primary key, timestamp text, name text, loc text, desc text)" , "create table if not exists unpw (id integer primary key, un text, pw text)" , "create table if not exists words (id integer primary key, word text)" ] onlyIntsHelper :: [Only Int] -> Int onlyIntsHelper [] = 0 onlyIntsHelper (Only x:_) = x hashPW :: String -> IO Text hashPW = maybeEmp TE.decodeUtf8 `fmap2` (hashPasswordUsingPolicy fastBcryptHashingPolicy . B.pack) type DbTblName = Text getDbTblRecs :: (FromRow a) => DbTblName -> IO [a] getDbTblRecs tblName = onDbFile (\conn -> query_ conn . Query $ "select * from " <> tblName) deleteDbTblRec :: DbTblName -> Int -> IO () deleteDbTblRec tblName i = onDbFile $ \conn -> execute conn (Query $ "delete from " <> tblName <> " where id=?") . Only $ i deleteDbTblRecs :: DbTblName -> IO () deleteDbTblRecs tblName = onDbFile (\conn -> execute_ conn . Query $ "delete from " <> tblName) insertDbTblHelper :: (ToRow a) => Query -> a -> IO () insertDbTblHelper q x = onDbFile $ \conn -> execute conn q x insertDbTblAdminChan :: AdminChanRec -> IO () insertDbTblAdminChan = insertDbTblHelper "insert into admin_chan (timestamp, name, msg) values (?, ?, ?)" insertDbTblAdminMsg :: AdminMsgRec -> IO () insertDbTblAdminMsg = insertDbTblHelper "insert into admin_msg (timestamp, from_name, to_name, msg) values (?, ?, ?, ?)" insertDbTblAlertExec :: AlertExecRec -> IO () insertDbTblAlertExec = insertDbTblHelper "insert into alert_exec (timestamp, name, cmd_name, target, args) values \ \(?, ?, ?, ?, ?)" insertDbTblAlertMsg :: AlertMsgRec -> IO () insertDbTblAlertMsg = insertDbTblHelper "insert into alert_msg (timestamp, name, cmd_name, trigger, msg) values \ \(?, ?, ?, ?, ?)" insertDbTblBanHost :: BanHostRec -> IO () insertDbTblBanHost = insertDbTblHelper "insert into ban_host (timestamp, host, is_banned, reason) values (?, ?, ?, ?)" insertDbTblBanPC :: BanPCRec -> IO () insertDbTblBanPC = insertDbTblHelper "insert into ban_pc (timestamp, name, is_banned, reason) values (?, ?, ?, ?)" insertDbTblBonus :: BonusRec -> IO () insertDbTblBonus = insertDbTblHelper "insert into bonus (timestamp, from_name, to_name, amt) values (?, ?, ?, ?)" insertDbTblBug :: BugRec -> IO () insertDbTblBug = insertDbTblHelper "insert into bug (timestamp, name, loc, desc) values (?, ?, ?, ?)" insertDbTblChan :: ChanRec -> IO () insertDbTblChan = insertDbTblHelper "insert into chan (timestamp, chan_id, chan_name, name, msg) values (?, ?, ?, ?, ?)" insertDbTblDiscover :: DiscoverRec -> IO () insertDbTblDiscover = insertDbTblHelper "insert into discover (timestamp, host, msg) values (?, ?, ?)" insertDbTblProf :: ProfRec -> IO () insertDbTblProf = insertDbTblHelper "insert into profanity (timestamp, host, prof) values (?, ?, ?)" insertDbTblQuestion :: QuestionRec -> IO () insertDbTblQuestion = insertDbTblHelper "insert into question (timestamp, name, msg) values (?, ?, ?)" insertDbTblSacBonus :: SacBonusRec -> IO () insertDbTblSacBonus = insertDbTblHelper "insert into sac_bonus (utc_time, name, god_name) values (?, ?, ?)" insertDbTblSacrifice :: SacrificeRec -> IO () insertDbTblSacrifice = insertDbTblHelper "insert into sacrifice (utc_time, name, god_name) values (?, ?, ?)" insertDbTblSec :: SecRec -> IO () insertDbTblSec = insertDbTblHelper "insert into sec (name, question, answer) values (?, ?, ?)" insertDbTblTele :: TeleRec -> IO () insertDbTblTele = insertDbTblHelper "insert into tele (timestamp, from_name, to_name, msg) values (?, ?, ?, ?)" insertDbTblTelnetChars :: TelnetCharsRec -> IO () insertDbTblTelnetChars = insertDbTblHelper "insert into telnet_chars (timestamp, host, telnet_chars) values (?, ?, ?)" insertDbTblTType :: TTypeRec -> IO () insertDbTblTType = insertDbTblHelper "insert into ttype (timestamp, host, ttype) values (?, ?, ?)" insertDbTblTypo :: TypoRec -> IO () insertDbTblTypo = insertDbTblHelper "insert into typo (timestamp, name, loc, desc) values (?, ?, ?, ?)" insertDbTblUnPw :: UnPwRec -> IO () insertDbTblUnPw rec@UnPwRec { .. } = hashPW (T.unpack dbPw) >>= \pw -> onDbFile $ \conn -> do execute conn "delete from unpw where un=?" . Only $ dbUn execute conn "insert into unpw (un, pw) values (?, ?)" rec { dbPw = pw } type CountDbTblRecsFun = IO Int countDbTblRecsAdminChan :: CountDbTblRecsFun countDbTblRecsAdminChan = countHelper "admin_chan" countDbTblRecsAdminMsg :: CountDbTblRecsFun countDbTblRecsAdminMsg = countHelper "admin_msg" countDbTblRecsChan :: CountDbTblRecsFun countDbTblRecsChan = countHelper "chan" countDbTblRecsPropNames :: CountDbTblRecsFun countDbTblRecsPropNames = countHelper "prop_names" countDbTblRecsQuestion :: CountDbTblRecsFun countDbTblRecsQuestion = countHelper "question" countDbTblRecsTele :: CountDbTblRecsFun countDbTblRecsTele = countHelper "tele" countDbTblRecsWords :: CountDbTblRecsFun countDbTblRecsWords = countHelper "words" countHelper :: DbTblName -> IO Int countHelper tblName = let q = Query $ "select count(*) from " <> tblName in onDbFile $ \conn -> onlyIntsHelper <$> query_ conn q type PurgeDbTblFun = IO () purgeDbTblAdminChan :: PurgeDbTblFun purgeDbTblAdminChan = purgeHelper "admin_chan" purgeDbTblAdminMsg :: PurgeDbTblFun purgeDbTblAdminMsg = purgeHelper "admin_msg" purgeDbTblChan :: PurgeDbTblFun purgeDbTblChan = purgeHelper "chan" purgeDbTblQuestion :: PurgeDbTblFun purgeDbTblQuestion = purgeHelper "question" purgeDbTblTele :: PurgeDbTblFun purgeDbTblTele = purgeHelper "tele" purgeHelper :: DbTblName -> IO () purgeHelper tblName = onDbFile $ \conn -> execute conn q (Only noOfDbTblRecsToPurge) where q = Query . T.concat $ [ "delete from ", tblName, " where id in (select id from ", tblName, " limit ?)" ] lookupPropName :: Text -> IO (Maybe Text) lookupPropName txt = let q = Query "select prop_name from prop_names where prop_name = ? collate nocase" in onDbFile $ \conn -> onlyTxtsHelper <$> query conn q (Only txt) onlyTxtsHelper :: [Only Text] -> Maybe Text onlyTxtsHelper = listToMaybe . map fromOnly lookupBonuses :: Sing -> IO [BonusRec] lookupBonuses s = let q = Query "select * from bonus where from_name = ? or to_name = ?" in onDbFile $ \conn -> query conn q . dup $ s lookupBonusesFromTo :: Sing -> Sing -> IO Int lookupBonusesFromTo fromSing toSing = let q = Query "select count(*) from bonus where from_name = ? and to_name = ?" in onDbFile $ \conn -> onlyIntsHelper <$> query conn q (fromSing, toSing) lookupPW :: Sing -> IO (Maybe Text) lookupPW s = onDbFile $ \conn -> onlyTxtsHelper <$> query conn (Query "select pw from unpw where un = ?") (Only s) lookupSacBonusTime s gn = let q = Query "select utc_time from sac_bonus where name = ? and god_name = ?" in onDbFile $ \conn -> f <$> query conn q (s, gn) where f (reverse -> (Only t:_)) = case reads t of [(time, "")] -> Just time _ -> Nothing f _ = Nothing lookupSacrifices s gn = let q = Query "select count(*) from sacrifice where name = ? and god_name = ?" in onDbFile $ \conn -> onlyIntsHelper <$> query conn q (s, gn) lookupSec :: Sing -> IO [SecRec] lookupSec s = onDbFile $ \conn -> query conn (Query "select * from sec where name = ?") (Only s) lookupTeleNames :: Sing -> IO [Text] lookupTeleNames s = onDbFile $ \conn -> map fromOnly <$> query conn (Query t) (dup4 s) where t = "select case\ \ when from_name != ? then from_name\ \ when to_name != ? then to_name\ \ end as name \ \from (select from_name, to_name from tele where from_name = ? or to_name = ?)" lookupWord :: Text -> IO (Maybe Text) lookupWord txt = onDbFile $ \conn -> let t = "select word from words where word = ? collate nocase" in onlyTxtsHelper <$> query conn (Query t) (Only txt) insertPropNames :: LT.Text -> IO () insertPropNames = procSrcFileTxt "prop_names" "prop_name" procSrcFileTxt :: Text -> Text -> LT.Text -> IO () procSrcFileTxt tblName colName = onDbFile . flip execute_ . buildQuery where buildQuery = let txt = T.concat [ "insert into ", tblName, " ", parensQuote colName, " values " ] in Query . (txt <>) . LT.toStrict . buildVals buildVals txt = LT.intercalate ", " [ "(\"" <> t <> "\")" | t <- LT.lines txt ] insertWords :: LT.Text -> IO () insertWords = procSrcFileTxt "words" "word"
df64f11503b77e7d04a725c9905fbe7535249d366dc3be55c094fbfbd59cc672
lispnik/iup
pixel.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload '("iup" "iup-cd" "cd"))) (defpackage #:iup-examples.pixel (:use #:common-lisp) (:export #:pixel)) (in-package #:iup-examples.pixel) (defparameter *canvas* nil) (defun canvas-redraw (handle x y) (declare (ignore handle x y)) (cd:activate *canvas*) (setf (cd:background *canvas*) cd:+white+) (cd:clear *canvas*) (multiple-value-bind (w h) (cd:size *canvas*) (cd:pixel *canvas* (/ w 2) (/ h 2) cd:+black+)) (cd:flush *canvas*) iup:+default+) (defun canvas-map (handle) (setf *canvas* (cd:create-canvas (iup-cd:context-iup-dbuffer) handle)) iup:+default+) (defun canvas-unmap (handle) (cd:kill *canvas*) (setf *canvas* nil) iup:+default+) (defun canvas () (iup:with-iup () (let* ((canvas (iup:canvas :rastersize "320x200" :map_cb 'canvas-map :unmap_cb 'canvas-unmap :action 'canvas-redraw)) (dialog (iup:dialog canvas :title "Pixel example"))) (iup:show dialog) (iup:main-loop)))) #-sbcl (canvas) #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (canvas))
null
https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/examples/pixel.lisp
lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload '("iup" "iup-cd" "cd"))) (defpackage #:iup-examples.pixel (:use #:common-lisp) (:export #:pixel)) (in-package #:iup-examples.pixel) (defparameter *canvas* nil) (defun canvas-redraw (handle x y) (declare (ignore handle x y)) (cd:activate *canvas*) (setf (cd:background *canvas*) cd:+white+) (cd:clear *canvas*) (multiple-value-bind (w h) (cd:size *canvas*) (cd:pixel *canvas* (/ w 2) (/ h 2) cd:+black+)) (cd:flush *canvas*) iup:+default+) (defun canvas-map (handle) (setf *canvas* (cd:create-canvas (iup-cd:context-iup-dbuffer) handle)) iup:+default+) (defun canvas-unmap (handle) (cd:kill *canvas*) (setf *canvas* nil) iup:+default+) (defun canvas () (iup:with-iup () (let* ((canvas (iup:canvas :rastersize "320x200" :map_cb 'canvas-map :unmap_cb 'canvas-unmap :action 'canvas-redraw)) (dialog (iup:dialog canvas :title "Pixel example"))) (iup:show dialog) (iup:main-loop)))) #-sbcl (canvas) #+sbcl (sb-int:with-float-traps-masked (:divide-by-zero :invalid) (canvas))
45d327a12e066a0d4301acc993082aa1e07b3ba5c29518d2fb633de5be3dde84
enaeher/local-time-duration
cl-postgres.lisp
(in-package :local-time-duration) (export 'set-local-time-duration-cl-postgres-reader :local-time-duration) (defun set-local-time-duration-cl-postgres-reader (&optional (table cl-postgres:*sql-readtable*)) (cl-postgres::set-interval-reader (lambda (months days usec) (assert (= 0 months) (months) "local-time-duration does not yet support intervals with months.") (duration :day days :nsec (* usec 1000))) table)) (defmethod cl-postgres:to-sql-string ((duration duration)) (format nil "'~A'::interval" (format-iso8601-duration nil duration)))
null
https://raw.githubusercontent.com/enaeher/local-time-duration/fa20a4a03a1ee076eada649796e2f2345c930c21/cl-postgres.lisp
lisp
(in-package :local-time-duration) (export 'set-local-time-duration-cl-postgres-reader :local-time-duration) (defun set-local-time-duration-cl-postgres-reader (&optional (table cl-postgres:*sql-readtable*)) (cl-postgres::set-interval-reader (lambda (months days usec) (assert (= 0 months) (months) "local-time-duration does not yet support intervals with months.") (duration :day days :nsec (* usec 1000))) table)) (defmethod cl-postgres:to-sql-string ((duration duration)) (format nil "'~A'::interval" (format-iso8601-duration nil duration)))
997ce4a0e31099cec41b18d51196d89a2bbe563afdc5a27163bc2f97ce9f5ea9
meooow25/haccepted
BinSearchBench.hs
module BinSearchBench where import Data.Array import Data.List import Criterion import BinSearch ( binSearch, binSearchA ) import Util ( evalR, randIntsR, sizedBench ) benchmark :: Benchmark benchmark = bgroup "BinSearch" [ -- n searches on a range of size n bgroup "binSearch" $ map benchBinSearch sizes -- n searches on an array of size n , bgroup "binSearchA" $ map benchBinSearchA sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchBinSearch :: Int -> Benchmark benchBinSearch n = sizedBench n gen $ \qs -> whnf (go n) qs where gen = evalR $ randIntsR (1, n) n go n qs = foldl' (\_ i -> binSearch (>= i) 1 n `seq` ()) () qs benchBinSearchA :: Int -> Benchmark benchBinSearchA n = sizedBench n gen $ \ ~(a, qs) -> whnf (go a) qs where gen = (listArray (1, n) [1..n], evalR $ randIntsR (1, n) n) go a qs = foldl' (\_ i -> binSearchA (>= i) a `seq` ()) () qs
null
https://raw.githubusercontent.com/meooow25/haccepted/2bc153ca95038de3b8bac83eee4419b3ecc116c5/bench/BinSearchBench.hs
haskell
n searches on a range of size n n searches on an array of size n
module BinSearchBench where import Data.Array import Data.List import Criterion import BinSearch ( binSearch, binSearchA ) import Util ( evalR, randIntsR, sizedBench ) benchmark :: Benchmark benchmark = bgroup "BinSearch" bgroup "binSearch" $ map benchBinSearch sizes , bgroup "binSearchA" $ map benchBinSearchA sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchBinSearch :: Int -> Benchmark benchBinSearch n = sizedBench n gen $ \qs -> whnf (go n) qs where gen = evalR $ randIntsR (1, n) n go n qs = foldl' (\_ i -> binSearch (>= i) 1 n `seq` ()) () qs benchBinSearchA :: Int -> Benchmark benchBinSearchA n = sizedBench n gen $ \ ~(a, qs) -> whnf (go a) qs where gen = (listArray (1, n) [1..n], evalR $ randIntsR (1, n) n) go a qs = foldl' (\_ i -> binSearchA (>= i) a `seq` ()) () qs
99ced789bbeed380b37c69751b29f8ead5a1e16d90227affdd56cbb0621c40bd
uhc/uhc
CoreSaturate.hs
----------------------------------------------------------------------- The Core Assembler . Copyright 2001 , . All rights reserved . This file is distributed under the terms of the GHC license . For more information , see the file " license.txt " , which is included in the distribution . ----------------------------------------------------------------------- The Core Assembler. Copyright 2001, Daan Leijen. All rights reserved. This file is distributed under the terms of the GHC license. For more information, see the file "license.txt", which is included in the distribution. ------------------------------------------------------------------------} $ I d : CoreSaturate.hs 222 2004 - 02 - 14 16:33:04Z uust $ ---------------------------------------------------------------- -- saturate all calls to externals, instructions and constructors. -- pre: [coreNoShadow] ---------------------------------------------------------------- module Lvm.Core.CoreSaturate( coreSaturate ) where import List ( mapAccumR ) import Lvm.Common.Id ( Id, NameSupply, freshId, splitNameSupply, splitNameSupplies ) import Lvm.Common.IdMap ( IdMap, emptyMap, lookupMap, filterMap, mapFromList ) import Lvm.Core.Core ---------------------------------------------------------------- -- Environment: a name supply and a map from id to its arity ---------------------------------------------------------------- data Env = Env NameSupply (IdMap Int) uniqueId (Env supply arities) = let (id,supply') = freshId supply in (id,Env supply' arities) findArity id (Env supply arities) = case lookupMap id arities of Nothing -> 0 Just n -> n splitEnv (Env supply arities) = let (s0,s1) = splitNameSupply supply in (Env s0 arities, Env s1 arities) splitEnvs (Env supply arities) = map (\s -> Env s arities) (splitNameSupplies supply) ---------------------------------------------------------------- -- coreSaturate ---------------------------------------------------------------- coreSaturate :: NameSupply -> CoreModule -> CoreModule coreSaturate supply mod = mapExprWithSupply (satDeclExpr arities) supply mod where arities = mapFromList [(declName d,declArity d) | d <- moduleDecls mod, isDeclCon d || isDeclExtern d] satDeclExpr :: IdMap Int -> NameSupply -> Expr -> Expr satDeclExpr arities supply expr = satExpr (Env supply arities) expr ---------------------------------------------------------------- -- saturate expressions ---------------------------------------------------------------- satExpr :: Env -> Expr -> Expr satExpr env expr = case expr of Let binds expr -> let (env0,env1) = splitEnv env in Let (satBinds env0 binds) (satExpr env1 expr) Match id alts -> Match id (satAlts env alts) Lam id expr -> Lam id (satExpr env expr) Note n expr -> Note n (satExpr env expr) other -> let expr' = satExprSimple env expr in addLam env (requiredArgs env expr') expr' satBinds env binds = zipBindsWith (\env id expr -> Bind id (satExpr env expr)) (splitEnvs env) binds satAlts env alts = zipAltsWith (\env pat expr -> Alt pat (satExpr env expr)) (splitEnvs env) alts do n't saturate Ap , Var and Con here satExprSimple env expr = case expr of Let _ _ -> satExpr env expr Match _ _ -> satExpr env expr Lam _ _ -> satExpr env expr Ap e1 e2 -> let (env1,env2) = splitEnv env in Ap (satExprSimple env1 e1) (satExpr env2 e2) Note n e -> Note n (satExprSimple env e) other -> expr ---------------------------------------------------------------- -- Add lambda's ---------------------------------------------------------------- addLam env n expr = let (env',ids) = mapAccumR (\env i -> let (id,env') = uniqueId env in (env',id)) env [1..n] in foldr Lam (foldl Ap expr (map Var ids)) ids requiredArgs env expr = case expr of Let binds expr -> 0 Match id alts -> 0 Lam id expr -> 0 Ap expr1 expr2 -> requiredArgs env expr1 - 1 Var id -> findArity id env Con (ConId id) -> findArity id env Con (ConTag e arity) -> arity Note n expr -> requiredArgs env expr other -> 0
null
https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/src/lvm/Core/CoreSaturate.hs
haskell
--------------------------------------------------------------------- --------------------------------------------------------------------- ----------------------------------------------------------------------} -------------------------------------------------------------- saturate all calls to externals, instructions and constructors. pre: [coreNoShadow] -------------------------------------------------------------- -------------------------------------------------------------- Environment: a name supply and a map from id to its arity -------------------------------------------------------------- -------------------------------------------------------------- coreSaturate -------------------------------------------------------------- -------------------------------------------------------------- saturate expressions -------------------------------------------------------------- -------------------------------------------------------------- Add lambda's --------------------------------------------------------------
The Core Assembler . Copyright 2001 , . All rights reserved . This file is distributed under the terms of the GHC license . For more information , see the file " license.txt " , which is included in the distribution . The Core Assembler. Copyright 2001, Daan Leijen. All rights reserved. This file is distributed under the terms of the GHC license. For more information, see the file "license.txt", which is included in the distribution. $ I d : CoreSaturate.hs 222 2004 - 02 - 14 16:33:04Z uust $ module Lvm.Core.CoreSaturate( coreSaturate ) where import List ( mapAccumR ) import Lvm.Common.Id ( Id, NameSupply, freshId, splitNameSupply, splitNameSupplies ) import Lvm.Common.IdMap ( IdMap, emptyMap, lookupMap, filterMap, mapFromList ) import Lvm.Core.Core data Env = Env NameSupply (IdMap Int) uniqueId (Env supply arities) = let (id,supply') = freshId supply in (id,Env supply' arities) findArity id (Env supply arities) = case lookupMap id arities of Nothing -> 0 Just n -> n splitEnv (Env supply arities) = let (s0,s1) = splitNameSupply supply in (Env s0 arities, Env s1 arities) splitEnvs (Env supply arities) = map (\s -> Env s arities) (splitNameSupplies supply) coreSaturate :: NameSupply -> CoreModule -> CoreModule coreSaturate supply mod = mapExprWithSupply (satDeclExpr arities) supply mod where arities = mapFromList [(declName d,declArity d) | d <- moduleDecls mod, isDeclCon d || isDeclExtern d] satDeclExpr :: IdMap Int -> NameSupply -> Expr -> Expr satDeclExpr arities supply expr = satExpr (Env supply arities) expr satExpr :: Env -> Expr -> Expr satExpr env expr = case expr of Let binds expr -> let (env0,env1) = splitEnv env in Let (satBinds env0 binds) (satExpr env1 expr) Match id alts -> Match id (satAlts env alts) Lam id expr -> Lam id (satExpr env expr) Note n expr -> Note n (satExpr env expr) other -> let expr' = satExprSimple env expr in addLam env (requiredArgs env expr') expr' satBinds env binds = zipBindsWith (\env id expr -> Bind id (satExpr env expr)) (splitEnvs env) binds satAlts env alts = zipAltsWith (\env pat expr -> Alt pat (satExpr env expr)) (splitEnvs env) alts do n't saturate Ap , Var and Con here satExprSimple env expr = case expr of Let _ _ -> satExpr env expr Match _ _ -> satExpr env expr Lam _ _ -> satExpr env expr Ap e1 e2 -> let (env1,env2) = splitEnv env in Ap (satExprSimple env1 e1) (satExpr env2 e2) Note n e -> Note n (satExprSimple env e) other -> expr addLam env n expr = let (env',ids) = mapAccumR (\env i -> let (id,env') = uniqueId env in (env',id)) env [1..n] in foldr Lam (foldl Ap expr (map Var ids)) ids requiredArgs env expr = case expr of Let binds expr -> 0 Match id alts -> 0 Lam id expr -> 0 Ap expr1 expr2 -> requiredArgs env expr1 - 1 Var id -> findArity id env Con (ConId id) -> findArity id env Con (ConTag e arity) -> arity Note n expr -> requiredArgs env expr other -> 0
4fa2f080dcd40e3fdaeb78808dd5a4cf1ed2ff64ae1ad86d6fa13ae3a7d06666
symbiont-io/detsys-testkit
LogicalTime.hs
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DeriveGeneric # This module implements logical time via Lamport clocks , we do n't need vector -- clocks because we can't have events happening concurrently anyway. module StuntDouble.LogicalTime where import GHC.Generics (Generic) import Data.Aeson (FromJSON, ToJSON) import Data.IORef import Data.String (IsString) ------------------------------------------------------------------------ newtype NodeName = NodeName String deriving (Eq, Ord, IsString, Show, Read, Generic) instance ToJSON NodeName instance FromJSON NodeName data LogicalClock = LogicalClock NodeName (IORef LogicalTimeInt) newtype LogicalTimeInt = LogicalTimeInt Int deriving (Show, Eq, Read, Generic, Num, Ord, Enum) instance ToJSON LogicalTimeInt instance FromJSON LogicalTimeInt data LogicalTime = LogicalTime NodeName LogicalTimeInt deriving (Show, Eq, Read, Generic) instance ToJSON LogicalTime instance FromJSON LogicalTime getLogicalTimeInt :: LogicalTime -> LogicalTimeInt getLogicalTimeInt (LogicalTime _n i) = i succLogicalTime :: LogicalTime -> LogicalTime succLogicalTime (LogicalTime n i) = LogicalTime n (succ i) data Relation = HappenedBeforeOrConcurrently | HappenedAfter relation :: LogicalTime -> LogicalTime -> Relation relation (LogicalTime n t) (LogicalTime n' t') | t < t' || (t == t' && n < n') = HappenedBeforeOrConcurrently | otherwise = HappenedAfter newLogicalClock :: NodeName -> IO LogicalClock newLogicalClock n = do c <- newIORef 0 return (LogicalClock n c) -- Upon sending or logging local events we should increment the counter before -- creating the timestamp. timestamp :: LogicalClock -> IO LogicalTime timestamp (LogicalClock n c) = do t' <- atomicModifyIORef' c (\t -> let t' = t + 1 in (t', t')) return (LogicalTime n t') timestampInt :: LogicalClock -> IO LogicalTimeInt timestampInt (LogicalClock n c) = atomicModifyIORef' c (\t -> let t' = t + 1 in (t', t')) -- Upon receving a timestamped message we should update our clock. update :: LogicalClock -> LogicalTimeInt -> IO LogicalTime update (LogicalClock n c) t' = atomicModifyIORef' c (\t -> let t'' = max t t' + 1 in (t'', LogicalTime n t''))
null
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/29a3a0140730420e4c5cc8db23df6fdb03f9302c/src/runtime-prototype/src/StuntDouble/LogicalTime.hs
haskell
clocks because we can't have events happening concurrently anyway. ---------------------------------------------------------------------- Upon sending or logging local events we should increment the counter before creating the timestamp. Upon receving a timestamped message we should update our clock.
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DeriveGeneric # This module implements logical time via Lamport clocks , we do n't need vector module StuntDouble.LogicalTime where import GHC.Generics (Generic) import Data.Aeson (FromJSON, ToJSON) import Data.IORef import Data.String (IsString) newtype NodeName = NodeName String deriving (Eq, Ord, IsString, Show, Read, Generic) instance ToJSON NodeName instance FromJSON NodeName data LogicalClock = LogicalClock NodeName (IORef LogicalTimeInt) newtype LogicalTimeInt = LogicalTimeInt Int deriving (Show, Eq, Read, Generic, Num, Ord, Enum) instance ToJSON LogicalTimeInt instance FromJSON LogicalTimeInt data LogicalTime = LogicalTime NodeName LogicalTimeInt deriving (Show, Eq, Read, Generic) instance ToJSON LogicalTime instance FromJSON LogicalTime getLogicalTimeInt :: LogicalTime -> LogicalTimeInt getLogicalTimeInt (LogicalTime _n i) = i succLogicalTime :: LogicalTime -> LogicalTime succLogicalTime (LogicalTime n i) = LogicalTime n (succ i) data Relation = HappenedBeforeOrConcurrently | HappenedAfter relation :: LogicalTime -> LogicalTime -> Relation relation (LogicalTime n t) (LogicalTime n' t') | t < t' || (t == t' && n < n') = HappenedBeforeOrConcurrently | otherwise = HappenedAfter newLogicalClock :: NodeName -> IO LogicalClock newLogicalClock n = do c <- newIORef 0 return (LogicalClock n c) timestamp :: LogicalClock -> IO LogicalTime timestamp (LogicalClock n c) = do t' <- atomicModifyIORef' c (\t -> let t' = t + 1 in (t', t')) return (LogicalTime n t') timestampInt :: LogicalClock -> IO LogicalTimeInt timestampInt (LogicalClock n c) = atomicModifyIORef' c (\t -> let t' = t + 1 in (t', t')) update :: LogicalClock -> LogicalTimeInt -> IO LogicalTime update (LogicalClock n c) t' = atomicModifyIORef' c (\t -> let t'' = max t t' + 1 in (t'', LogicalTime n t''))
ccf93a6e21cc43d00250c97a89e19f02a59f0adad949aaba07e978dde51f3c8b
kit-ty-kate/mastodon-archive-viewer
gif_detect.mli
type filename = string val is_gif : filename -> bool
null
https://raw.githubusercontent.com/kit-ty-kate/mastodon-archive-viewer/09aa343054c6894dc2cc18ea09f04b5ebf6bab01/src/gif_detect.mli
ocaml
type filename = string val is_gif : filename -> bool
1f976bc8ac6c6bef161c8e2eb44b989786895cdc6caf2e05a704e47bc5e4b278
ha-mo-we/Racer
concrete-domains.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : RACER ; Base : 10 -*- Copyright ( c ) 1998 - 2014 , , , . ;;; All rights reserved. Racer is distributed under the following BSD 3 - clause license ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are ;;; met: ;;; Redistributions of source code must retain the above copyright notice, ;;; this list of conditions and the following disclaimer. ;;; Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. Neither the name Racer nor the names of its contributors may be used ;;; to endorse or promote products derived from this software without ;;; specific prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , ;;; BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND ;;; FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VOLKER HAARSLEV , RALF MOELLER , NOR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER ;;; IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ;;; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ;;; ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :racer) (defstruct (concrete-domain (:conc-name cd-)) (name nil) (objects nil) (domain-predicate nil) (predicates (make-hash-table)) (supported-types '(cardinal integer real complex string)) (registered-predicate-forms (racer-make-hash-table :test 'equal))) (defun create-concrete-domain () (make-concrete-domain :name 'racer-default-cd :domain-predicate 'concrete-domain-object-p)) ;;; ====================================================================== (defstruct (predicate (:include racer-structure-id)) (name nil) (definition nil) (parameters nil) (operator nil) (arity nil) (negation nil) (type nil) ) (defmethod print-object ((object predicate) stream) (cond ((predicate-definition object) (print-unreadable-object (object stream :type t :identity t) (format stream "~S" (predicate-definition object)))) ((predicate-definition (predicate-negation object)) (print-unreadable-object (object stream :type t :identity t) (format stream "(NEG ~S)" (predicate-definition (predicate-negation object))))) (t (print-unreadable-object (object stream :type t :identity nil) (format stream "~S" (predicate-name object)))))) (defstruct (linear-predicate (:include predicate) ;(:print-function print-predicate) (:conc-name predicate-)) (coefficients nil) (right-side nil)) (defvar *cd-debug* nil) (defun print-predicate (predicate stream depth) Ausgabefunktion fuer predicate (declare (ignore depth)) (if *cd-debug* (let ((name (predicate-name predicate)) (coefficients (predicate-coefficients predicate)) (right-side (predicate-right-side predicate)) (operator (predicate-operator predicate)) (negation (predicate-negation predicate))) (format stream "<#predicate: ~A: " name) (loop for coeff across coefficients and n from 1 do (if (eql n 1) (format stream "~A*x_~A " coeff n) (format stream "+ ~A*x_~A " coeff n))) (format stream "~A ~A~% Negation: ~A>" operator right-side (predicate-name negation))) (print-unreadable-object (predicate stream :type t :identity t) (format stream "Lin:~A" (predicate-name predicate))))) (defstruct (nonlinear-predicate (:include predicate) (:conc-name predicate-)) ) (defstruct (equal-unequal-predicate (:include linear-predicate) (:conc-name predicate-)) predicate-1 predicate-2) (defstruct (equal-predicate (:include equal-unequal-predicate))) (defstruct (unequal-predicate (:include equal-unequal-predicate))) (defstruct (divisible-predicate (:include predicate) (:conc-name predicate-))) (defstruct (string-predicate (:include predicate) (:conc-name predicate-))) (defstruct (unary-string-predicate (:include string-predicate) (:conc-name predicate-)) string) (defstruct (binary-string-predicate (:include string-predicate) (:conc-name predicate-))) ;;; ====================================================================== (defstruct cd-constraint (varlist nil) (predicate nil) (negated-p nil)) (defmethod print-object ((object cd-constraint) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "~S ~S" (if (cd-constraint-negated-p object) (predicate-negation (cd-constraint-predicate object)) (cd-constraint-predicate object)) (cd-constraint-varlist object)))) (defun make-constraint (predicate args &optional (negated nil)) (make-cd-constraint :predicate predicate :varlist args :negated-p negated)) ;;; ====================================================================== (defun parse-linear-constraint-body (concrete-domain parameters expr arity) (declare (ignore concrete-domain)) ; expr hat folgende Struktur: ; expr = (op arg arg) ; op = < | <= | > | >= ; arg = real | symbol | product | sum ; product = (* real symbol) ; sum = (+ {real | symbol | product}*) ; > wird in < und >= in <= umgewandelt, durch Multiplikation mit -1 ( expr ( first body ) ) ; falls body weitere expressions enthaelt werden diese noch ignoriert ! (par (make-hash-table)) (coeff (make-array arity :initial-element 0)) (rs 0)) (flet ((proper-var (var fac) (let ((par-pos (gethash var par))) ( format t " var : , fac : ~A , pos : ~A~% " var ) (if (and (symbolp var) par-pos) (setf (svref coeff par-pos) (+ (svref coeff par-pos) (rationalize fac))) (error "variable not in parameter-list"))))) (flet ((parse-arg (arg fac) (cond ((realp arg) (setf rs (- rs (* (rationalize fac) (rationalize arg))))) ((and (listp arg) (eql (length arg) 3) (eql '* (first arg)) (realp (second arg)) (proper-var (third arg) (* (rationalize fac) (rationalize (second arg)))))) ((and (listp arg) (eql '+ (first arg))) (dolist (a (rest arg)) (cond ((realp a) (setf rs (- rs (* (rationalize fac) (rationalize a))))) ((and (listp a) (eql (length a) 3) (eql '* (first a)) (realp (second a)) (proper-var (third a) (* (rationalize fac) (rationalize (second a)))))) ((not (listp a)) (proper-var a fac)) (t (error "Syntax error: ~A" expr))))) ((not (listp arg)) (proper-var arg fac)) (t (error "incorrect first argument"))))) ; paremeters mit position in Hash-tabelle par ablegen: (loop for p in parameters and i from 0 below arity do (setf (gethash p par) i)) (if (not (and (listp expr) (eql (length expr) 3) (member (first expr) '(< <= > >=)))) (error "Syntax error1: ~A" expr)) (let ((op (first expr)) (arg1 (second expr)) (arg2 (third expr))) (if (or (eql op '<) (eql op '<=)) (progn (parse-arg arg1 1) (parse-arg arg2 -1)) (progn (parse-arg arg1 -1) (parse-arg arg2 1) (setf op (case op (> '<) (>= '<=))))) (values op coeff rs)))) )) ;;; ====================================================================== (defun add-special-predicate (op definition parameters name neg-name concrete-domain datatype) (let* ((pred (make-predicate :name name :definition definition :parameters parameters :operator op :arity 1 :negation neg-name :type datatype )) ; negiertes Praedikat ezeugen: (neg-op (case op (top 'bottom) (bottom 'top) (otherwise (error "wrong operator: only TOP or BOTTOM allowed")))) (neg-pred (make-predicate :name neg-name :definition (if (eq neg-op 'top) `(a . ,(rest definition)) `(no . ,(rest definition))) :parameters parameters :operator neg-op :arity 1 :negation pred :type datatype )) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (setf (predicate-negation pred) neg-pred) pred)) (defun add-integer-predicate (op definition parameters name neg-name concrete-domain) (unless (symbolp (second definition)) (error "concrete domain attribute ~S is not a name in ~S." (second definition) definition)) (if (third definition) (unless (integerp (third definition)) (error "~S in ~S must be an integer." (third definition) definition)) (error "A number is missing in ~S." definition)) (let ((form (ecase op (min (list '>= (second definition) (third definition))) (max (list '<= (second definition) (third definition)))))) (unless form (error "concrete domain operator MIN or MAX expected in ~S." definition)) (multiple-value-bind (op1 coeff rs) (parse-linear-constraint-body concrete-domain parameters form 1) (let ((predicate (make-linear-predicate :name name :definition definition :parameters parameters :coefficients coeff :right-side rs :operator op1 :arity 1 :negation neg-name :type 'integer ))) ; negiertes Praedikat ezeugen: (let ((neg-form (ecase op (min (list '<= (second form) (- (third form) 1))) (max (list '>= (second form) (+ (third form) 1)))))) (multiple-value-bind (neg-op neg-coeff neg-rs) (parse-linear-constraint-body concrete-domain parameters neg-form 1) (let ((neg-predicate (make-linear-predicate :name neg-name :definition (if (eq op 'min) `(max ,(second definition) ,(1- (third definition))) `(min ,(second definition) ,(1+ (third definition)))) :parameters parameters :coefficients neg-coeff :right-side neg-rs :operator neg-op :arity 1 :negation predicate :type 'integer)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-predicate) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (gethash definition forms-table) predicate) (setf (gethash (predicate-definition neg-predicate) forms-table) neg-predicate) (setf (predicate-negation predicate) neg-predicate)))) predicate)))) ;;; ====================================================================== (defun add-linear-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (cond ((or (eq (first form) '=) (eq (first form) 'equal)) (let* ((predicate-1 (add-linear-predicate name neg-name parameters (cons '>= (rest form)) concrete-domain)) (predicate-2 (add-linear-predicate name neg-name parameters (cons '<= (rest form)) concrete-domain)) (predicate (make-equal-predicate :name name :predicate-1 predicate-1 :predicate-2 predicate-2 :type (predicate-type predicate-1) :parameters parameters :definition form :arity arity :operator (if (eq (first form) 'equal) 'equal '=)))) (let* ((neg-predicate-1 (add-linear-predicate name neg-name parameters (cons '> (rest form)) concrete-domain)) (neg-predicate-2 (add-linear-predicate name neg-name parameters (cons '< (rest form)) concrete-domain)) (neg-pred (make-unequal-predicate :name neg-name :predicate-1 neg-predicate-1 :predicate-2 neg-predicate-2 :parameters parameters :negation predicate :definition (cons (if (eq (first form) 'equal) 'unequal '<>) (rest form)) :type (predicate-type neg-predicate-1) :arity arity :operator (if (eq (first form) 'equal) 'unequal '<>))) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (when (eq (first form) 'equal) THIS IS OK BECAUSE INTEGER PREDICATES MIN / MAX ;; ARE HANDLED IN THE SAME WAY AS REAL PREDICATES (setf (predicate-type predicate) 'integer) (setf (predicate-type neg-pred) 'integer)) predicate))) ((or (eq (first form) '<>) (eq (first form) 'unequal)) (let* ((predicate-1 (add-linear-predicate name neg-name parameters (cons '> (rest form)) concrete-domain)) (predicate-2 (add-linear-predicate name neg-name parameters (cons '< (rest form)) concrete-domain)) (predicate (make-unequal-predicate :name name :predicate-1 predicate-1 :predicate-2 predicate-2 :type (predicate-type predicate-1) :parameters parameters :definition form :arity arity :operator (if (eq (first form) 'unequal) 'unequal '<>)))) (let* ((neg-predicate-1 (add-linear-predicate name neg-name parameters (cons '>= (rest form)) concrete-domain)) (neg-predicate-2 (add-linear-predicate name neg-name parameters (cons '<= (rest form)) concrete-domain)) (neg-pred (make-equal-predicate :name neg-name :predicate-1 neg-predicate-1 :predicate-2 neg-predicate-2 :parameters parameters :definition (cons (if (eq (first form) 'unequal) 'equal '=) (rest form)) :negation predicate :type (predicate-type neg-predicate-1) :arity arity :operator (if (eq (first form) 'unequal) 'equal '=))) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (when (eq (first form) 'unequal) THIS IS OK BECAUSE INTEGER PREDICATES MIN / MAX ;; ARE HANDLED IN THE SAME WAY AS REAL PREDICATES (setf (predicate-type predicate) 'integer) (setf (predicate-type neg-pred) 'integer)) predicate))) (t (multiple-value-bind (op coeff rs) (parse-linear-constraint-body concrete-domain parameters form arity) (let ((predicate (add-linear-predicate-definition form parameters name neg-name arity op coeff rs concrete-domain))) (when (loop for parameter-name in (predicate-parameters predicate) for role = (get-role parameter-name) thereis (and role (eq (role-cd-attribute role) 'cardinal))) HMM ... CONVERTING THE PREDICATE TYPE TO CARDINALS WORKS ONLY FOR ROLES ;; BUT NOT FOR OBJECT-NAMES!!! So we have to deal with object names explicitly in the code . (unless (loop for parameter-name in parameters for role = (encode-role-term parameter-name :cd-attribute 'cardinal) always (eq (role-cd-attribute role) 'cardinal)) (error "All attributes must be cardinals in ~A." form)) ;(break "~S" predicate) (setf (predicate-type predicate) 'cardinal)) predicate)))))) (defun add-nonlinear-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (let ((predicate (add-nonlinear-predicate-definition form parameters name neg-name arity (first form) concrete-domain))) predicate))) (defun negated-cd-operator (operator) (ecase operator (< '>=) (<= '>) (> '<=) (>= '<) (= '<>) (equal 'unequal) (unequal 'equal) (<> '=) (string= 'string<>) (string<> 'string=) (boolean= 'boolean<>) (boolean<> 'boolean=) (a 'no) (no 'a) (divisible 'not-divisible) (not-divisible 'divisible))) (defun add-linear-predicate-definition (definition parameters pred-name neg-name arity op coeff rs concrete-domain) (or (gethash definition (cd-registered-predicate-forms concrete-domain)) (let ((pred (make-linear-predicate :name pred-name :definition definition :parameters parameters :coefficients coeff :right-side rs :operator op :arity arity :negation neg-name :type 'real))) ; negiertes Praedikat ezeugen: (let ((neg-op (ecase op (< '<=) (<= '<) ; !!! DIESES KANN MAN NICHT VERSTEHEN!!! AENDERUNGEN SIND FATAL!!! : Wenn das Praedikat den Operator > ( bzw . > , wird implizit mit -1 ( bzw . < =) man die Faelle > und > = hier nicht zu behandeln . Vor dem Negieren wird dann noch mit -1 multipliziert . > ( bzw . > =) an < ( bzw . > =) . , den < ( bzw . < =) bekommen muss ( rm -- 26.5.03 ) ;(= '<>) ;(<> '=) )) (neg-coeff (make-array (array-dimension coeff 0)))) alle Koeffizienten negieren (loop for c across coeff and pos from 0 do (setf (aref neg-coeff pos) (- c))) (let ((neg-pred (make-linear-predicate :name neg-name :definition (list* (negated-cd-operator (first definition)) (rest definition)) :parameters parameters :coefficients neg-coeff :right-side (- rs) :operator neg-op :arity arity :negation pred :type 'real)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash pred-name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred))))) (defun add-nonlinear-predicate-definition (definition parameters pred-name neg-name arity op concrete-domain) (or (gethash definition (cd-registered-predicate-forms concrete-domain)) (let ((pred (make-nonlinear-predicate :name pred-name :definition definition :parameters parameters :operator op :arity arity :negation neg-name :type 'complex))) ; negiertes Praedikat ezeugen: (let ((neg-op (case op (= '<>) (<> '=) ;(< '<=) ;(<= '<) ;(> '<=) ;(>= '<) (otherwise (error "Wrong operator: only = supported for nonlinear predicates."))))) (let ((neg-pred (make-nonlinear-predicate :name neg-name :parameters parameters :operator neg-op :arity arity :negation pred :type 'complex)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash pred-name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred))))) (defun add-divisible-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (cond ((eq (first form) 'divisible) (let* ((predicate (make-divisible-predicate :name name :type 'cardinal :parameters parameters :definition form :arity arity :operator 'divisible))) (let* ((neg-pred (make-divisible-predicate :name neg-name :parameters parameters :negation predicate :definition (cons 'not-divisible (rest form)) :type 'cardinal :arity arity :operator 'not-divisible)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) predicate))) ((eq (first form) 'not-divisible) (let* ((predicate (make-divisible-predicate :name name :type 'cardinal :parameters parameters :definition form :arity arity :operator 'not-divisible))) (let* ((neg-pred (make-divisible-predicate :name neg-name :parameters parameters :definition (cons 'divisible (rest form)) :negation predicate :type 'cardinal :arity arity :operator 'divisible)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) predicate))) (t (error "Internal error: unknown divisible predicate. This should not happen."))))) (defun add-string-predicate (name neg-name parameters form concrete-domain) (or (gethash form (cd-registered-predicate-forms concrete-domain)) (let ((arity (length parameters))) (cond ((stringp (third form)) (let* ((pred (make-unary-string-predicate :name name :parameters parameters :definition form :type 'string :string (third form) :arity arity :operator (first form))) (neg-op (ecase (first form) (string= 'string<>) (string<> 'string=))) (neg-pred (make-unary-string-predicate :name neg-name :parameters parameters :definition (list* neg-op (rest form)) :operator neg-op :arity arity :negation pred :string (third form) :type 'string)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash form forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred)) (t (let* ((pred (make-binary-string-predicate :name name :parameters parameters :definition form :type 'string :arity arity :operator (first form))) (neg-op (ecase (first form) (string= 'string<>) (string<> 'string=))) (neg-pred (make-binary-string-predicate :name neg-name :parameters parameters :definition (list* neg-op (rest form)) :operator neg-op :arity arity :negation pred :type 'string)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash form forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred)))))) ;;; ====================================================================== (defstruct (racer-boolean (:predicate racer-boolean-p) (:conc-name boolean-)) value) (defmethod print-object ((object racer-boolean) stream) (declare (ignorable stream)) (if (string= (boolean-value object) "false") (write-string "#F" stream) (write-string "#T" stream))) (defparameter *true* (make-racer-boolean :value "true")) (defparameter *false* (make-racer-boolean :value "false")) (defmethod make-load-form ((object racer-boolean) &optional env) (declare (ignore env)) (cond ((eq object *true*) '*true*) ((eq object *false*) '*false*))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun true-value-reader (stream subchar arg) (declare (ignore stream subchar arg)) *true*) (defun false-value-reader (stream subchar arg) (declare (ignore stream subchar arg)) *false*)) (defun true? (object) (and (racer-boolean-p object) (string= (boolean-value object) "true"))) (defun false? (object) (and (racer-boolean-p object) (string= (boolean-value object) "false"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun enable-boolean-readers () (setf *readtable* (copy-readtable)) (set-dispatch-macro-character #\# #\T 'true-value-reader) (set-dispatch-macro-character #\# #\F 'false-value-reader) (set-dispatch-macro-character #\# #\t 'true-value-reader) (set-dispatch-macro-character #\# #\f 'false-value-reader)) (enable-boolean-readers)) (defun boolean-value-from-string (value) (cond ((string= value "true") *true*) ((string= value "false") *false*) (t (error "Boolean value true or false expected.")))) (defun add-boolean-predicate (name neg-name parameters form concrete-domain) (let ((value (boolean-value (third form)))) (add-string-predicate name neg-name parameters (ecase (first form) (boolean= `(string= ,(second form) ,value)) (boolean<> `(string<> ,(second form) ,value))) concrete-domain)))
null
https://raw.githubusercontent.com/ha-mo-we/Racer/d690841d10015c7a75b1ded393fcf0a33092c4de/source/concrete-domains.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : RACER ; Base : 10 -*- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ====================================================================== (:print-function print-predicate) ====================================================================== ====================================================================== expr hat folgende Struktur: expr = (op arg arg) op = < | <= | > | >= arg = real | symbol | product | sum product = (* real symbol) sum = (+ {real | symbol | product}*) > wird in < und >= in <= umgewandelt, durch Multiplikation mit -1 falls body weitere expressions enthaelt werden diese noch ignoriert ! paremeters mit position in Hash-tabelle par ablegen: ====================================================================== negiertes Praedikat ezeugen: negiertes Praedikat ezeugen: ====================================================================== ARE HANDLED IN THE SAME WAY AS REAL PREDICATES ARE HANDLED IN THE SAME WAY AS REAL PREDICATES BUT NOT FOR OBJECT-NAMES!!! So we have to deal with object names (break "~S" predicate) negiertes Praedikat ezeugen: !!! DIESES KANN MAN NICHT VERSTEHEN!!! AENDERUNGEN SIND FATAL!!! (= '<>) (<> '=) negiertes Praedikat ezeugen: (< '<=) (<= '<) (> '<=) (>= '<) ======================================================================
Copyright ( c ) 1998 - 2014 , , , . Racer is distributed under the following BSD 3 - clause license Neither the name Racer nor the names of its contributors may be used CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , VOLKER HAARSLEV , RALF MOELLER , NOR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER (in-package :racer) (defstruct (concrete-domain (:conc-name cd-)) (name nil) (objects nil) (domain-predicate nil) (predicates (make-hash-table)) (supported-types '(cardinal integer real complex string)) (registered-predicate-forms (racer-make-hash-table :test 'equal))) (defun create-concrete-domain () (make-concrete-domain :name 'racer-default-cd :domain-predicate 'concrete-domain-object-p)) (defstruct (predicate (:include racer-structure-id)) (name nil) (definition nil) (parameters nil) (operator nil) (arity nil) (negation nil) (type nil) ) (defmethod print-object ((object predicate) stream) (cond ((predicate-definition object) (print-unreadable-object (object stream :type t :identity t) (format stream "~S" (predicate-definition object)))) ((predicate-definition (predicate-negation object)) (print-unreadable-object (object stream :type t :identity t) (format stream "(NEG ~S)" (predicate-definition (predicate-negation object))))) (t (print-unreadable-object (object stream :type t :identity nil) (format stream "~S" (predicate-name object)))))) (defstruct (linear-predicate (:include predicate) (:conc-name predicate-)) (coefficients nil) (right-side nil)) (defvar *cd-debug* nil) (defun print-predicate (predicate stream depth) Ausgabefunktion fuer predicate (declare (ignore depth)) (if *cd-debug* (let ((name (predicate-name predicate)) (coefficients (predicate-coefficients predicate)) (right-side (predicate-right-side predicate)) (operator (predicate-operator predicate)) (negation (predicate-negation predicate))) (format stream "<#predicate: ~A: " name) (loop for coeff across coefficients and n from 1 do (if (eql n 1) (format stream "~A*x_~A " coeff n) (format stream "+ ~A*x_~A " coeff n))) (format stream "~A ~A~% Negation: ~A>" operator right-side (predicate-name negation))) (print-unreadable-object (predicate stream :type t :identity t) (format stream "Lin:~A" (predicate-name predicate))))) (defstruct (nonlinear-predicate (:include predicate) (:conc-name predicate-)) ) (defstruct (equal-unequal-predicate (:include linear-predicate) (:conc-name predicate-)) predicate-1 predicate-2) (defstruct (equal-predicate (:include equal-unequal-predicate))) (defstruct (unequal-predicate (:include equal-unequal-predicate))) (defstruct (divisible-predicate (:include predicate) (:conc-name predicate-))) (defstruct (string-predicate (:include predicate) (:conc-name predicate-))) (defstruct (unary-string-predicate (:include string-predicate) (:conc-name predicate-)) string) (defstruct (binary-string-predicate (:include string-predicate) (:conc-name predicate-))) (defstruct cd-constraint (varlist nil) (predicate nil) (negated-p nil)) (defmethod print-object ((object cd-constraint) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "~S ~S" (if (cd-constraint-negated-p object) (predicate-negation (cd-constraint-predicate object)) (cd-constraint-predicate object)) (cd-constraint-varlist object)))) (defun make-constraint (predicate args &optional (negated nil)) (make-cd-constraint :predicate predicate :varlist args :negated-p negated)) (defun parse-linear-constraint-body (concrete-domain parameters expr arity) (declare (ignore concrete-domain)) (par (make-hash-table)) (coeff (make-array arity :initial-element 0)) (rs 0)) (flet ((proper-var (var fac) (let ((par-pos (gethash var par))) ( format t " var : , fac : ~A , pos : ~A~% " var ) (if (and (symbolp var) par-pos) (setf (svref coeff par-pos) (+ (svref coeff par-pos) (rationalize fac))) (error "variable not in parameter-list"))))) (flet ((parse-arg (arg fac) (cond ((realp arg) (setf rs (- rs (* (rationalize fac) (rationalize arg))))) ((and (listp arg) (eql (length arg) 3) (eql '* (first arg)) (realp (second arg)) (proper-var (third arg) (* (rationalize fac) (rationalize (second arg)))))) ((and (listp arg) (eql '+ (first arg))) (dolist (a (rest arg)) (cond ((realp a) (setf rs (- rs (* (rationalize fac) (rationalize a))))) ((and (listp a) (eql (length a) 3) (eql '* (first a)) (realp (second a)) (proper-var (third a) (* (rationalize fac) (rationalize (second a)))))) ((not (listp a)) (proper-var a fac)) (t (error "Syntax error: ~A" expr))))) ((not (listp arg)) (proper-var arg fac)) (t (error "incorrect first argument"))))) (loop for p in parameters and i from 0 below arity do (setf (gethash p par) i)) (if (not (and (listp expr) (eql (length expr) 3) (member (first expr) '(< <= > >=)))) (error "Syntax error1: ~A" expr)) (let ((op (first expr)) (arg1 (second expr)) (arg2 (third expr))) (if (or (eql op '<) (eql op '<=)) (progn (parse-arg arg1 1) (parse-arg arg2 -1)) (progn (parse-arg arg1 -1) (parse-arg arg2 1) (setf op (case op (> '<) (>= '<=))))) (values op coeff rs)))) )) (defun add-special-predicate (op definition parameters name neg-name concrete-domain datatype) (let* ((pred (make-predicate :name name :definition definition :parameters parameters :operator op :arity 1 :negation neg-name :type datatype )) (neg-op (case op (top 'bottom) (bottom 'top) (otherwise (error "wrong operator: only TOP or BOTTOM allowed")))) (neg-pred (make-predicate :name neg-name :definition (if (eq neg-op 'top) `(a . ,(rest definition)) `(no . ,(rest definition))) :parameters parameters :operator neg-op :arity 1 :negation pred :type datatype )) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (setf (predicate-negation pred) neg-pred) pred)) (defun add-integer-predicate (op definition parameters name neg-name concrete-domain) (unless (symbolp (second definition)) (error "concrete domain attribute ~S is not a name in ~S." (second definition) definition)) (if (third definition) (unless (integerp (third definition)) (error "~S in ~S must be an integer." (third definition) definition)) (error "A number is missing in ~S." definition)) (let ((form (ecase op (min (list '>= (second definition) (third definition))) (max (list '<= (second definition) (third definition)))))) (unless form (error "concrete domain operator MIN or MAX expected in ~S." definition)) (multiple-value-bind (op1 coeff rs) (parse-linear-constraint-body concrete-domain parameters form 1) (let ((predicate (make-linear-predicate :name name :definition definition :parameters parameters :coefficients coeff :right-side rs :operator op1 :arity 1 :negation neg-name :type 'integer ))) (let ((neg-form (ecase op (min (list '<= (second form) (- (third form) 1))) (max (list '>= (second form) (+ (third form) 1)))))) (multiple-value-bind (neg-op neg-coeff neg-rs) (parse-linear-constraint-body concrete-domain parameters neg-form 1) (let ((neg-predicate (make-linear-predicate :name neg-name :definition (if (eq op 'min) `(max ,(second definition) ,(1- (third definition))) `(min ,(second definition) ,(1+ (third definition)))) :parameters parameters :coefficients neg-coeff :right-side neg-rs :operator neg-op :arity 1 :negation predicate :type 'integer)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-predicate) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (gethash definition forms-table) predicate) (setf (gethash (predicate-definition neg-predicate) forms-table) neg-predicate) (setf (predicate-negation predicate) neg-predicate)))) predicate)))) (defun add-linear-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (cond ((or (eq (first form) '=) (eq (first form) 'equal)) (let* ((predicate-1 (add-linear-predicate name neg-name parameters (cons '>= (rest form)) concrete-domain)) (predicate-2 (add-linear-predicate name neg-name parameters (cons '<= (rest form)) concrete-domain)) (predicate (make-equal-predicate :name name :predicate-1 predicate-1 :predicate-2 predicate-2 :type (predicate-type predicate-1) :parameters parameters :definition form :arity arity :operator (if (eq (first form) 'equal) 'equal '=)))) (let* ((neg-predicate-1 (add-linear-predicate name neg-name parameters (cons '> (rest form)) concrete-domain)) (neg-predicate-2 (add-linear-predicate name neg-name parameters (cons '< (rest form)) concrete-domain)) (neg-pred (make-unequal-predicate :name neg-name :predicate-1 neg-predicate-1 :predicate-2 neg-predicate-2 :parameters parameters :negation predicate :definition (cons (if (eq (first form) 'equal) 'unequal '<>) (rest form)) :type (predicate-type neg-predicate-1) :arity arity :operator (if (eq (first form) 'equal) 'unequal '<>))) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (when (eq (first form) 'equal) THIS IS OK BECAUSE INTEGER PREDICATES MIN / MAX (setf (predicate-type predicate) 'integer) (setf (predicate-type neg-pred) 'integer)) predicate))) ((or (eq (first form) '<>) (eq (first form) 'unequal)) (let* ((predicate-1 (add-linear-predicate name neg-name parameters (cons '> (rest form)) concrete-domain)) (predicate-2 (add-linear-predicate name neg-name parameters (cons '< (rest form)) concrete-domain)) (predicate (make-unequal-predicate :name name :predicate-1 predicate-1 :predicate-2 predicate-2 :type (predicate-type predicate-1) :parameters parameters :definition form :arity arity :operator (if (eq (first form) 'unequal) 'unequal '<>)))) (let* ((neg-predicate-1 (add-linear-predicate name neg-name parameters (cons '>= (rest form)) concrete-domain)) (neg-predicate-2 (add-linear-predicate name neg-name parameters (cons '<= (rest form)) concrete-domain)) (neg-pred (make-equal-predicate :name neg-name :predicate-1 neg-predicate-1 :predicate-2 neg-predicate-2 :parameters parameters :definition (cons (if (eq (first form) 'unequal) 'equal '=) (rest form)) :negation predicate :type (predicate-type neg-predicate-1) :arity arity :operator (if (eq (first form) 'unequal) 'equal '=))) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) (when (eq (first form) 'unequal) THIS IS OK BECAUSE INTEGER PREDICATES MIN / MAX (setf (predicate-type predicate) 'integer) (setf (predicate-type neg-pred) 'integer)) predicate))) (t (multiple-value-bind (op coeff rs) (parse-linear-constraint-body concrete-domain parameters form arity) (let ((predicate (add-linear-predicate-definition form parameters name neg-name arity op coeff rs concrete-domain))) (when (loop for parameter-name in (predicate-parameters predicate) for role = (get-role parameter-name) thereis (and role (eq (role-cd-attribute role) 'cardinal))) HMM ... CONVERTING THE PREDICATE TYPE TO CARDINALS WORKS ONLY FOR ROLES explicitly in the code . (unless (loop for parameter-name in parameters for role = (encode-role-term parameter-name :cd-attribute 'cardinal) always (eq (role-cd-attribute role) 'cardinal)) (error "All attributes must be cardinals in ~A." form)) (setf (predicate-type predicate) 'cardinal)) predicate)))))) (defun add-nonlinear-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (let ((predicate (add-nonlinear-predicate-definition form parameters name neg-name arity (first form) concrete-domain))) predicate))) (defun negated-cd-operator (operator) (ecase operator (< '>=) (<= '>) (> '<=) (>= '<) (= '<>) (equal 'unequal) (unequal 'equal) (<> '=) (string= 'string<>) (string<> 'string=) (boolean= 'boolean<>) (boolean<> 'boolean=) (a 'no) (no 'a) (divisible 'not-divisible) (not-divisible 'divisible))) (defun add-linear-predicate-definition (definition parameters pred-name neg-name arity op coeff rs concrete-domain) (or (gethash definition (cd-registered-predicate-forms concrete-domain)) (let ((pred (make-linear-predicate :name pred-name :definition definition :parameters parameters :coefficients coeff :right-side rs :operator op :arity arity :negation neg-name :type 'real))) (let ((neg-op (ecase op (< '<=) : Wenn das Praedikat den Operator > ( bzw . > , wird implizit mit -1 ( bzw . < =) man die Faelle > und > = hier nicht zu behandeln . Vor dem Negieren wird dann noch mit -1 multipliziert . > ( bzw . > =) an < ( bzw . > =) . , den < ( bzw . < =) bekommen muss ( rm -- 26.5.03 ) )) (neg-coeff (make-array (array-dimension coeff 0)))) alle Koeffizienten negieren (loop for c across coeff and pos from 0 do (setf (aref neg-coeff pos) (- c))) (let ((neg-pred (make-linear-predicate :name neg-name :definition (list* (negated-cd-operator (first definition)) (rest definition)) :parameters parameters :coefficients neg-coeff :right-side (- rs) :operator neg-op :arity arity :negation pred :type 'real)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash pred-name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred))))) (defun add-nonlinear-predicate-definition (definition parameters pred-name neg-name arity op concrete-domain) (or (gethash definition (cd-registered-predicate-forms concrete-domain)) (let ((pred (make-nonlinear-predicate :name pred-name :definition definition :parameters parameters :operator op :arity arity :negation neg-name :type 'complex))) (let ((neg-op (case op (= '<>) (<> '=) (otherwise (error "Wrong operator: only = supported for nonlinear predicates."))))) (let ((neg-pred (make-nonlinear-predicate :name neg-name :parameters parameters :operator neg-op :arity arity :negation pred :type 'complex)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash pred-name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash definition forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred))))) (defun add-divisible-predicate (name neg-name parameters form concrete-domain) (let ((arity (length parameters))) (cond ((eq (first form) 'divisible) (let* ((predicate (make-divisible-predicate :name name :type 'cardinal :parameters parameters :definition form :arity arity :operator 'divisible))) (let* ((neg-pred (make-divisible-predicate :name neg-name :parameters parameters :negation predicate :definition (cons 'not-divisible (rest form)) :type 'cardinal :arity arity :operator 'not-divisible)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) predicate))) ((eq (first form) 'not-divisible) (let* ((predicate (make-divisible-predicate :name name :type 'cardinal :parameters parameters :definition form :arity arity :operator 'not-divisible))) (let* ((neg-pred (make-divisible-predicate :name neg-name :parameters parameters :definition (cons 'divisible (rest form)) :negation predicate :type 'cardinal :arity arity :operator 'divisible)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) predicate) (setf (predicate-negation predicate) neg-pred) (setf (gethash form forms-table) predicate) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) predicate))) (t (error "Internal error: unknown divisible predicate. This should not happen."))))) (defun add-string-predicate (name neg-name parameters form concrete-domain) (or (gethash form (cd-registered-predicate-forms concrete-domain)) (let ((arity (length parameters))) (cond ((stringp (third form)) (let* ((pred (make-unary-string-predicate :name name :parameters parameters :definition form :type 'string :string (third form) :arity arity :operator (first form))) (neg-op (ecase (first form) (string= 'string<>) (string<> 'string=))) (neg-pred (make-unary-string-predicate :name neg-name :parameters parameters :definition (list* neg-op (rest form)) :operator neg-op :arity arity :negation pred :string (third form) :type 'string)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash form forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred)) (t (let* ((pred (make-binary-string-predicate :name name :parameters parameters :definition form :type 'string :arity arity :operator (first form))) (neg-op (ecase (first form) (string= 'string<>) (string<> 'string=))) (neg-pred (make-binary-string-predicate :name neg-name :parameters parameters :definition (list* neg-op (rest form)) :operator neg-op :arity arity :negation pred :type 'string)) (forms-table (cd-registered-predicate-forms concrete-domain))) (setf (gethash neg-name (cd-predicates concrete-domain)) neg-pred) (setf (gethash name (cd-predicates concrete-domain)) pred) (setf (predicate-negation pred) neg-pred) (setf (gethash form forms-table) pred) (setf (gethash (predicate-definition neg-pred) forms-table) neg-pred) pred)))))) (defstruct (racer-boolean (:predicate racer-boolean-p) (:conc-name boolean-)) value) (defmethod print-object ((object racer-boolean) stream) (declare (ignorable stream)) (if (string= (boolean-value object) "false") (write-string "#F" stream) (write-string "#T" stream))) (defparameter *true* (make-racer-boolean :value "true")) (defparameter *false* (make-racer-boolean :value "false")) (defmethod make-load-form ((object racer-boolean) &optional env) (declare (ignore env)) (cond ((eq object *true*) '*true*) ((eq object *false*) '*false*))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun true-value-reader (stream subchar arg) (declare (ignore stream subchar arg)) *true*) (defun false-value-reader (stream subchar arg) (declare (ignore stream subchar arg)) *false*)) (defun true? (object) (and (racer-boolean-p object) (string= (boolean-value object) "true"))) (defun false? (object) (and (racer-boolean-p object) (string= (boolean-value object) "false"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun enable-boolean-readers () (setf *readtable* (copy-readtable)) (set-dispatch-macro-character #\# #\T 'true-value-reader) (set-dispatch-macro-character #\# #\F 'false-value-reader) (set-dispatch-macro-character #\# #\t 'true-value-reader) (set-dispatch-macro-character #\# #\f 'false-value-reader)) (enable-boolean-readers)) (defun boolean-value-from-string (value) (cond ((string= value "true") *true*) ((string= value "false") *false*) (t (error "Boolean value true or false expected.")))) (defun add-boolean-predicate (name neg-name parameters form concrete-domain) (let ((value (boolean-value (third form)))) (add-string-predicate name neg-name parameters (ecase (first form) (boolean= `(string= ,(second form) ,value)) (boolean<> `(string<> ,(second form) ,value))) concrete-domain)))
66e167f6f328258651743e00f1c4c522f1061c30effdbac101ed7335f051222d
hraberg/deuce
textprop.clj
(ns deuce.emacs.textprop (:use [deuce.emacs-lisp :only (defun defvar)]) (:require [clojure.core :as c]) (:refer-clojure :exclude [])) (defvar default-text-properties nil "Property-list used as default values. The value of a property in this list is seen as the value for every character that does not have its own value for that property.") (defvar text-property-default-nonsticky nil "Alist of properties vs the corresponding non-stickiness. Each element has the form (PROPERTY . NONSTICKINESS). If a character in a buffer has PROPERTY, new text inserted adjacent to the character doesn't inherit PROPERTY if NONSTICKINESS is non-nil, inherits it if NONSTICKINESS is nil. The `front-sticky' and `rear-nonsticky' properties of the character override NONSTICKINESS.") (defvar char-property-alias-alist nil "Alist of alternative properties for properties without a value. Each element should look like (PROPERTY ALTERNATIVE1 ALTERNATIVE2...). If a piece of text has no direct value for a particular property, then this alist is consulted. If that property appears in the alist, then the first non-nil value from the associated alternative properties is returned.") (defvar inhibit-point-motion-hooks nil "If non-nil, don't run `point-left' and `point-entered' text properties. This also inhibits the use of the `intangible' text property.") (defun next-char-property-change (position &optional limit) "Return the position of next text property or overlay change. This scans characters forward in the current buffer from POSITION till it finds a change in some text property, or the beginning or end of an overlay, and returns the position of that. If none is found up to (point-max), the function returns (point-max). If the optional second argument LIMIT is non-nil, don't search past position LIMIT; return LIMIT if nothing is found before LIMIT. LIMIT is a no-op if it is greater than (point-max)." ) (defun remove-list-of-text-properties (start end list-of-properties &optional object) "Remove some properties from text from START to END. The third argument LIST-OF-PROPERTIES is a list of property names to remove. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property was actually removed, nil otherwise." ) (defun next-property-change (position &optional object limit) "Return the position of next property change. Scans characters forward from POSITION in OBJECT till it finds a change in some text property, then returns the position of the change. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. Return nil if the property is constant all the way to the end of OBJECT. If the value is non-nil, it is a position greater than POSITION, never equal. If the optional third argument LIMIT is non-nil, don't search past position LIMIT; return LIMIT if nothing is found before LIMIT." ) (defun text-property-not-all (start end property value &optional object) "Check text from START to END for property PROPERTY not equaling VALUE. If so, return the position of the first character whose property PROPERTY is not `eq' to VALUE. Otherwise, return nil. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun add-text-properties (start end properties &optional object) "Add properties to the text from START to END. The third argument PROPERTIES is a property list specifying the property values to add. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property value actually changed, nil otherwise." ) (defun previous-single-char-property-change (position prop &optional object limit) "Return the position of previous text property or overlay change for a specific property. Scans characters backward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. In a string, scan runs to the start of the string. In a buffer, it runs to (point-min), and the value cannot be less than that. The property values are compared with `eq'. If the property is constant all the way to the start of OBJECT, return the first valid position in OBJECT. If the optional fourth argument LIMIT is non-nil, don't search back past position LIMIT; return LIMIT if nothing is found before reaching LIMIT." ) (defun text-property-any (start end property value &optional object) "Check text from START to END for property PROPERTY equaling VALUE. If so, return the position of the first character whose property PROPERTY is `eq' to VALUE. Otherwise return nil. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun get-char-property-and-overlay (position prop &optional object) "Like `get-char-property', but with extra overlay information. The value is a cons cell. Its car is the return value of `get-char-property' with the same arguments--that is, the value of POSITION's property PROP in OBJECT. Its cdr is the overlay in which the property was found, or nil, if it was found as a text property or not found at all. OBJECT is optional and defaults to the current buffer. OBJECT may be a string, a buffer or a window. For strings, the cdr of the return value is always nil, since strings do not have overlays. If OBJECT is a window, then that window's buffer is used, but window-specific overlays are considered only if they are associated with OBJECT. If POSITION is at the end of OBJECT, both car and cdr are nil." ) (defun previous-char-property-change (position &optional limit) "Return the position of previous text property or overlay change. Scans characters backward in the current buffer from POSITION till it finds a change in some text property, or the beginning or end of an overlay, and returns the position of that. If none is found since (point-min), the function returns (point-min). If the optional second argument LIMIT is non-nil, don't search past position LIMIT; return LIMIT if nothing is found before LIMIT. LIMIT is a no-op if it is less than (point-min)." ) (defun put-text-property (start end property value &optional object) "Set one property of the text from START to END. The third and fourth arguments PROPERTY and VALUE specify the property to add. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun remove-text-properties (start end properties &optional object) "Remove some properties from text from START to END. The third argument PROPERTIES is a property list whose property names specify the properties to remove. (The values stored in PROPERTIES are ignored.) If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property was actually removed, nil otherwise. Use `set-text-properties' if you want to remove all text properties." ) (defun get-char-property (position prop &optional object) "Return the value of POSITION's property PROP, in OBJECT. Both overlay properties and text properties are checked. OBJECT is optional and defaults to the current buffer. If POSITION is at the end of OBJECT, the value is nil. If OBJECT is a buffer, then overlay properties are considered as well as text properties. If OBJECT is a window, then that window's buffer is used, but window-specific overlays are considered only if they are associated with OBJECT." ) (defun next-single-char-property-change (position prop &optional object limit) "Return the position of next text property or overlay change for a specific property. Scans characters forward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. In a string, scan runs to the end of the string. In a buffer, it runs to (point-max), and the value cannot exceed that. The property values are compared with `eq'. If the property is constant all the way to the end of OBJECT, return the last valid position in OBJECT. If the optional fourth argument LIMIT is non-nil, don't search past position LIMIT; return LIMIT if nothing is found before LIMIT." ) (defun next-single-property-change (position prop &optional object limit) "Return the position of next property change for a specific property. Scans characters forward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. The property values are compared with `eq'. Return nil if the property is constant all the way to the end of OBJECT. If the value is non-nil, it is a position greater than POSITION, never equal. If the optional fourth argument LIMIT is non-nil, don't search past position LIMIT; return LIMIT if nothing is found before LIMIT." limit) (defun get-text-property (position prop &optional object) "Return the value of POSITION's property PROP, in OBJECT. OBJECT is optional and defaults to the current buffer. If POSITION is at the end of OBJECT, the value is nil." ) (defun text-properties-at (position &optional object) "Return the list of properties of the character at POSITION in OBJECT. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. If POSITION is at the end of OBJECT, the value is nil." ) (defun set-text-properties (start end properties &optional object) "Completely replace properties of text from START to END. The third argument PROPERTIES is the new property list. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. If PROPERTIES is nil, the effect is to remove all properties from the designated part of OBJECT." ) (defun previous-single-property-change (position prop &optional object limit) "Return the position of previous property change for a specific property. Scans characters backward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. The property values are compared with `eq'. Return nil if the property is constant all the way to the start of OBJECT. If the value is non-nil, it is a position less than POSITION, never equal. If the optional fourth argument LIMIT is non-nil, don't search back past position LIMIT; return LIMIT if nothing is found until LIMIT." ) (defun previous-property-change (position &optional object limit) "Return the position of previous property change. Scans characters backwards from POSITION in OBJECT till it finds a change in some text property, then returns the position of the change. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. Return nil if the property is constant all the way to the start of OBJECT. If the value is non-nil, it is a position less than POSITION, never equal. If the optional third argument LIMIT is non-nil, don't search back past position LIMIT; return LIMIT if nothing is found until LIMIT." )
null
https://raw.githubusercontent.com/hraberg/deuce/9d507adb6c68c0f5c19ad79fa6ded9593c082575/src/deuce/emacs/textprop.clj
clojure
return LIMIT if nothing is found before LIMIT. return LIMIT if nothing is found before LIMIT." return LIMIT if nothing is found before reaching LIMIT." return LIMIT if nothing is found before LIMIT. return LIMIT if nothing is found before LIMIT." return LIMIT if nothing is found before LIMIT." return LIMIT if nothing is found until LIMIT." return LIMIT if nothing is found until LIMIT."
(ns deuce.emacs.textprop (:use [deuce.emacs-lisp :only (defun defvar)]) (:require [clojure.core :as c]) (:refer-clojure :exclude [])) (defvar default-text-properties nil "Property-list used as default values. The value of a property in this list is seen as the value for every character that does not have its own value for that property.") (defvar text-property-default-nonsticky nil "Alist of properties vs the corresponding non-stickiness. Each element has the form (PROPERTY . NONSTICKINESS). If a character in a buffer has PROPERTY, new text inserted adjacent to the character doesn't inherit PROPERTY if NONSTICKINESS is non-nil, inherits it if NONSTICKINESS is nil. The `front-sticky' and `rear-nonsticky' properties of the character override NONSTICKINESS.") (defvar char-property-alias-alist nil "Alist of alternative properties for properties without a value. Each element should look like (PROPERTY ALTERNATIVE1 ALTERNATIVE2...). If a piece of text has no direct value for a particular property, then this alist is consulted. If that property appears in the alist, then the first non-nil value from the associated alternative properties is returned.") (defvar inhibit-point-motion-hooks nil "If non-nil, don't run `point-left' and `point-entered' text properties. This also inhibits the use of the `intangible' text property.") (defun next-char-property-change (position &optional limit) "Return the position of next text property or overlay change. This scans characters forward in the current buffer from POSITION till it finds a change in some text property, or the beginning or end of an overlay, and returns the position of that. If none is found up to (point-max), the function returns (point-max). If the optional second argument LIMIT is non-nil, don't search LIMIT is a no-op if it is greater than (point-max)." ) (defun remove-list-of-text-properties (start end list-of-properties &optional object) "Remove some properties from text from START to END. The third argument LIST-OF-PROPERTIES is a list of property names to remove. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property was actually removed, nil otherwise." ) (defun next-property-change (position &optional object limit) "Return the position of next property change. Scans characters forward from POSITION in OBJECT till it finds a change in some text property, then returns the position of the change. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. Return nil if the property is constant all the way to the end of OBJECT. If the value is non-nil, it is a position greater than POSITION, never equal. If the optional third argument LIMIT is non-nil, don't search ) (defun text-property-not-all (start end property value &optional object) "Check text from START to END for property PROPERTY not equaling VALUE. If so, return the position of the first character whose property PROPERTY is not `eq' to VALUE. Otherwise, return nil. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun add-text-properties (start end properties &optional object) "Add properties to the text from START to END. The third argument PROPERTIES is a property list specifying the property values to add. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property value actually changed, nil otherwise." ) (defun previous-single-char-property-change (position prop &optional object limit) "Return the position of previous text property or overlay change for a specific property. Scans characters backward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. In a string, scan runs to the start of the string. In a buffer, it runs to (point-min), and the value cannot be less than that. The property values are compared with `eq'. If the property is constant all the way to the start of OBJECT, return the first valid position in OBJECT. If the optional fourth argument LIMIT is non-nil, don't search back past ) (defun text-property-any (start end property value &optional object) "Check text from START to END for property PROPERTY equaling VALUE. If so, return the position of the first character whose property PROPERTY is `eq' to VALUE. Otherwise return nil. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun get-char-property-and-overlay (position prop &optional object) "Like `get-char-property', but with extra overlay information. The value is a cons cell. Its car is the return value of `get-char-property' with the same arguments--that is, the value of POSITION's property PROP in OBJECT. Its cdr is the overlay in which the property was found, or nil, if it was found as a text property or not found at all. OBJECT is optional and defaults to the current buffer. OBJECT may be a string, a buffer or a window. For strings, the cdr of the return value is always nil, since strings do not have overlays. If OBJECT is a window, then that window's buffer is used, but window-specific overlays are considered only if they are associated with OBJECT. If POSITION is at the end of OBJECT, both car and cdr are nil." ) (defun previous-char-property-change (position &optional limit) "Return the position of previous text property or overlay change. Scans characters backward in the current buffer from POSITION till it finds a change in some text property, or the beginning or end of an overlay, and returns the position of that. If none is found since (point-min), the function returns (point-min). If the optional second argument LIMIT is non-nil, don't search LIMIT is a no-op if it is less than (point-min)." ) (defun put-text-property (start end property value &optional object) "Set one property of the text from START to END. The third and fourth arguments PROPERTY and VALUE specify the property to add. If the optional fifth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it." ) (defun remove-text-properties (start end properties &optional object) "Remove some properties from text from START to END. The third argument PROPERTIES is a property list whose property names specify the properties to remove. (The values stored in PROPERTIES are ignored.) If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. Return t if any property was actually removed, nil otherwise. Use `set-text-properties' if you want to remove all text properties." ) (defun get-char-property (position prop &optional object) "Return the value of POSITION's property PROP, in OBJECT. Both overlay properties and text properties are checked. OBJECT is optional and defaults to the current buffer. If POSITION is at the end of OBJECT, the value is nil. If OBJECT is a buffer, then overlay properties are considered as well as text properties. If OBJECT is a window, then that window's buffer is used, but window-specific overlays are considered only if they are associated with OBJECT." ) (defun next-single-char-property-change (position prop &optional object limit) "Return the position of next text property or overlay change for a specific property. Scans characters forward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. In a string, scan runs to the end of the string. In a buffer, it runs to (point-max), and the value cannot exceed that. The property values are compared with `eq'. If the property is constant all the way to the end of OBJECT, return the last valid position in OBJECT. If the optional fourth argument LIMIT is non-nil, don't search ) (defun next-single-property-change (position prop &optional object limit) "Return the position of next property change for a specific property. Scans characters forward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. The property values are compared with `eq'. Return nil if the property is constant all the way to the end of OBJECT. If the value is non-nil, it is a position greater than POSITION, never equal. If the optional fourth argument LIMIT is non-nil, don't search limit) (defun get-text-property (position prop &optional object) "Return the value of POSITION's property PROP, in OBJECT. OBJECT is optional and defaults to the current buffer. If POSITION is at the end of OBJECT, the value is nil." ) (defun text-properties-at (position &optional object) "Return the list of properties of the character at POSITION in OBJECT. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. If POSITION is at the end of OBJECT, the value is nil." ) (defun set-text-properties (start end properties &optional object) "Completely replace properties of text from START to END. The third argument PROPERTIES is the new property list. If the optional fourth argument OBJECT is a buffer (or nil, which means the current buffer), START and END are buffer positions (integers or markers). If OBJECT is a string, START and END are 0-based indices into it. If PROPERTIES is nil, the effect is to remove all properties from the designated part of OBJECT." ) (defun previous-single-property-change (position prop &optional object limit) "Return the position of previous property change for a specific property. Scans characters backward from POSITION till it finds a change in the PROP property, then returns the position of the change. If the optional third argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. The property values are compared with `eq'. Return nil if the property is constant all the way to the start of OBJECT. If the value is non-nil, it is a position less than POSITION, never equal. If the optional fourth argument LIMIT is non-nil, don't search ) (defun previous-property-change (position &optional object limit) "Return the position of previous property change. Scans characters backwards from POSITION in OBJECT till it finds a change in some text property, then returns the position of the change. If the optional second argument OBJECT is a buffer (or nil, which means the current buffer), POSITION is a buffer position (integer or marker). If OBJECT is a string, POSITION is a 0-based index into it. Return nil if the property is constant all the way to the start of OBJECT. If the value is non-nil, it is a position less than POSITION, never equal. If the optional third argument LIMIT is non-nil, don't search )
99600a294fda279425023d90c8b04bcdef4b9bd7ca56d020789309899f1dfbf0
cheshire/onumerical
number_intf.mli
(** Number type: anything comparable which supports basic arithmetic *) type t with sexp, compare (* OK what does compare generate? *) (** Constructors *) val zero : t val one : t val of_int : int -> t val infinity : t (** Arithmetics *) val (+/) : t -> t -> t val (-/) : t -> t -> t val ( */) : t -> t -> t val ( //) : t -> t -> t val abs : t -> t (** Negation *) val (~/) : t -> t (** Comparison *) val compare : t -> t -> int val (<=/) : t -> t -> bool val (>=/) : t -> t -> bool val (=/) : t -> t -> bool val (</) : t -> t -> bool val (>/) : t -> t -> bool val max : t -> t -> t val min : t -> t -> t (** Pretty-printing *) val to_string : t -> string
null
https://raw.githubusercontent.com/cheshire/onumerical/2ebe77edb61c761f1e1397dc37369f2cdc8021f7/src/number_intf.mli
ocaml
* Number type: anything comparable which supports basic arithmetic OK what does compare generate? * Constructors * Arithmetics * Negation * Comparison * Pretty-printing
val zero : t val one : t val of_int : int -> t val infinity : t val (+/) : t -> t -> t val (-/) : t -> t -> t val ( */) : t -> t -> t val ( //) : t -> t -> t val abs : t -> t val (~/) : t -> t val compare : t -> t -> int val (<=/) : t -> t -> bool val (>=/) : t -> t -> bool val (=/) : t -> t -> bool val (</) : t -> t -> bool val (>/) : t -> t -> bool val max : t -> t -> t val min : t -> t -> t val to_string : t -> string
3b9690f9b714309d7dd3a0828bbfd10f68313a6f83209f00d41783947efb743a
borodust/bodge-nanovg
regen-spec.lisp
(bind-arguments build-directory system-name target &key (arch "x86_64") mode) (when (and (not (uiop:emptyp mode)) (string= (string-downcase mode) "gl2")) (pushnew :bodge-gl2 *features*)) (script "regen-local-spec-and-zip" "--arch" arch build-directory system-name target)
null
https://raw.githubusercontent.com/borodust/bodge-nanovg/fa9729747e1dcfb07fa49a4233d7da6bc879ee11/util/regen-spec.lisp
lisp
(bind-arguments build-directory system-name target &key (arch "x86_64") mode) (when (and (not (uiop:emptyp mode)) (string= (string-downcase mode) "gl2")) (pushnew :bodge-gl2 *features*)) (script "regen-local-spec-and-zip" "--arch" arch build-directory system-name target)
0fba8b3f102ef5cee23866b6e493ff91cd1c032dcfeb6b411074ffa28a6eacdd
zcaudate/hara
report.clj
(ns hara.print.base.report (:require [hara.core.base.result :as result] [hara.print.base.common :as common] [hara.string :as string] [hara.string.base.ansi :as ansi])) (defn pad "creates `n` number of spaces (pad 1) => \"\" (pad 5) => \"\"" {:added "3.0"} [len] (apply str (repeat len common/+pad+))) (defn pad-right "puts the content to the left, padding missing spaces (pad-right \"hello\" 10) => \"hello \"" {:added "3.0"} [content length] (str content (pad (- length (count content))))) (defn pad-center "puts the content at the center, padding missing spacing (pad-center \"hello\" 10) => \"hello \"" {:added "3.0"} [content length] (let [total (- length (count content)) half (long (/ total 2)) [left right] (cond (even? total) [half half] :else [half (inc half)])] (str (pad left) content (pad right)))) (defn pad-left "puts the content to the right, padding missing spaces (pad-left \"hello\" 10) => \"hello\"" {:added "3.0"} [content length] (str (pad (- length (count content))) content)) (defn pad-down "creates new lines of n spaces (pad-down [] 10 2) => [\" \" \" \"]" {:added "3.0"} [row length height] (let [line (apply str (repeat length common/+pad+))] (concat row (repeat (- height (count row)) line)))) (defn justify "justifies the content to a given alignment (justify :right \"hello\" 10) => \"hello\" (justify :left \"hello\" 10) => \"hello \"" {:added "3.0"} [align content length] (case align :center (pad-center content length) :right (pad-left content length) (pad-right content length))) (defn seq-elements "layout an array of elements as a series of rows of a given length (seq-elements [\"A\" \"BC\" \"DEF\" \"GHIJ\" \"KLMNO\"] {:align :left :length 9} 0 1) => {:rows [\"[A BC DEF\" \" GHIJ \" \" KLMNO] \"]}" {:added "3.0"} [arr {:keys [align length]} padding spacing] (let [pad (apply str (repeat padding common/+pad+)) space (apply str (repeat spacing common/+space+))] (if (empty? arr) {:rows [(justify align (str pad "[]" pad) length)]} (reduce (fn [{:keys [current rows] :as out} row-item] (let [s (str row-item) l (count s)] (cond (nil? current) {:rows rows :current (str pad "[" s)} (nil? row-item) {:rows (conj rows (justify align (str current "]") length))} (> (+ l spacing (count current)) length) {:rows (conj rows (justify align current length)) :current (str pad " " s)} :else {:rows rows :current (str current space s)}))) {:rows []} (conj arr nil))))) (defn row-elements "layout raw elements based on alignment and length properties (row-elements [\"hello\" :world [:a :b :c :d :e :f]] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) => [[\" hello\"] [\" :world \"] [\"[:a :b :c \" \" :d :e :f]\"]]" {:added "3.0"} [row {:keys [padding spacing columns] :as params}] (let [pad (apply str (repeat padding common/+pad+)) prep-fn (fn [row-item {:keys [format align length] :as column}] (let [row-item (if format (string/format format row-item) row-item)] (if (sequential? row-item) (:rows (seq-elements row-item column padding spacing)) [(justify align (str pad row-item) length)])))] (mapv (fn [row-item column] (let [data (if (result/result? row-item) (:data row-item) row-item)] (prep-fn data column))) row columns))) (defn prepare-elements "same as row-elements but allows for colors and results (prepare-elements [\"hello\" :world [:a :b :c :d]] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) => [[\" hello\" \" \"] [\" :world \" \" \"] [\"[:a :b :c \" \" :d] \"]]" {:added "3.0"} [row {:keys [padding columns] :as params}] (let [pad (apply str (repeat padding common/+pad+)) elements (row-elements row params) height (apply max (map count elements)) style (fn [lines color] (if color (map #(ansi/style % color) lines) lines)) lines (mapv (fn [s {:keys [align length color]} row-item] (let [color (if (result/result? row-item) #{(:status row-item)} color)] (-> (pad-down s length height) (style color)))) elements columns row)] lines)) (defn print-header "prints a header for the row (-> (print-header [:id :name :value] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) (with-out-str))" {:added "3.0"} [titles {:keys [padding columns] :as params}] (let [pad (pad padding) header (-> (apply str (mapv (fn [title {:keys [align length]}] (str pad (justify align (name title) length))) titles columns)) (ansi/style #{:bold}))] (println header) (print "\n"))) (defn print-row "prints a row to output (-> (print-row [\"hello\" :world (result/result {:data [:a :b :c :d :e :f] :status :info})] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) (with-out-str))" {:added "3.0"} [row params] (apply mapv println (prepare-elements row params))) (defn print-title "prints the title (-> (print-title \"Hello World\") (with-out-str))" {:added "3.0"} [title] (let [line (apply str (repeat (count title) \-))] (print (ansi/style (string/format "\n%s\n%s\n%s\n" line title line) #{:bold})))) (defn print-subtitle "prints the subtitle (-> (print-subtitle \"Hello Again\") (with-out-str))" {:added "3.0"} [text] (print (ansi/style text #{:bold}) "\n")) (defn print-column "prints the column (-> (print-column [[:id.a {:data 100}] [:id.b {:data 200}]] :data #{}) (with-out-str))" {:added "3.0"} [items name color] (let [ns-len (or (->> items (map (comp count str first)) sort last) 20) display {:padding 1 :spacing 1 :columns [{:id :key :length (inc ns-len) :align :left} {:id name :length 60 :color color}]}] (print-header [:key name] display) (doseq [[key m] items] (print-row [key (get m name)] display)) (print "\n"))) (defn print-compare "outputs a side by side comparison (-> (print-compare [['hara.code [[:a :b :c] [:d :e :f]]]]) (with-out-str))" {:added "3.0"} [output] (let [ns-len (or (->> output (map (comp count str first)) sort last) 20) item-params {:padding 1 :spacing 1 :columns [{:id :ns :length (inc ns-len) :align :left} {:id :data :length 50 :color #{:highlight}} {:id :data :length 50 :color #{:magenta}}]}] (doseq [[ns [src test]] output] (print-row [ns src (if (empty? test) :no-tests test)] item-params)) (print "\n"))) (defn print-summary "outputs the summary of results (-> (print-summary {:count 6 :files 2}) (with-out-str))" {:added "3.0"} [m] (let [ks (sort (keys m))] (print (ansi/style (str "SUMMARY " m "\n") #{:bold})))) (defn format-tree "returns a string representation of a tree (-> (format-tree '[{a \"1.1\"} [{b \"1.2\"} [{c \"1.3\"} {d \"1.4\"}]]]) (string/split-lines)) => [\"{a \\\"1.1\\\"}\" \" {b \\\"1.2\\\"}\" \" {c \\\"1.3\\\"}\" \" {d \\\"1.4\\\"}\" \"\"]" {:added "3.0"} ([tree] (apply str (map #(format-tree % "" nil?) tree))) ([tree prefix check] (if (and (vector? tree) (not (check tree))) (->> (map #(format-tree % (str prefix " ") check) tree) (apply str)) (str prefix tree "\n")))) (defn print-tree "outputs the result of `format-tree` (print-tree '[{a \"1.1\"} [{b \"1.2\"} [{c \"1.3\"} {d \"1.4\"}]]])" {:added "3.0"} ([tree] (print-tree tree "" nil?)) ([tree prefix check] (let [output (->> (format-tree tree prefix check) (string/split-lines)) min-spaces (apply min (map (fn [s] (-> (re-find #"^(\s*)" s) first count)) output)) output (->> output (map #(subs % min-spaces)) (map (fn [s] (if (.startsWith s " ") (ansi/green "" s) (ansi/bold "\n" s)))))] (println (string/join output "\n")))))
null
https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/src/hara/print/base/report.clj
clojure
(ns hara.print.base.report (:require [hara.core.base.result :as result] [hara.print.base.common :as common] [hara.string :as string] [hara.string.base.ansi :as ansi])) (defn pad "creates `n` number of spaces (pad 1) => \"\" (pad 5) => \"\"" {:added "3.0"} [len] (apply str (repeat len common/+pad+))) (defn pad-right "puts the content to the left, padding missing spaces (pad-right \"hello\" 10) => \"hello \"" {:added "3.0"} [content length] (str content (pad (- length (count content))))) (defn pad-center "puts the content at the center, padding missing spacing (pad-center \"hello\" 10) => \"hello \"" {:added "3.0"} [content length] (let [total (- length (count content)) half (long (/ total 2)) [left right] (cond (even? total) [half half] :else [half (inc half)])] (str (pad left) content (pad right)))) (defn pad-left "puts the content to the right, padding missing spaces (pad-left \"hello\" 10) => \"hello\"" {:added "3.0"} [content length] (str (pad (- length (count content))) content)) (defn pad-down "creates new lines of n spaces (pad-down [] 10 2) => [\" \" \" \"]" {:added "3.0"} [row length height] (let [line (apply str (repeat length common/+pad+))] (concat row (repeat (- height (count row)) line)))) (defn justify "justifies the content to a given alignment (justify :right \"hello\" 10) => \"hello\" (justify :left \"hello\" 10) => \"hello \"" {:added "3.0"} [align content length] (case align :center (pad-center content length) :right (pad-left content length) (pad-right content length))) (defn seq-elements "layout an array of elements as a series of rows of a given length (seq-elements [\"A\" \"BC\" \"DEF\" \"GHIJ\" \"KLMNO\"] {:align :left :length 9} 0 1) => {:rows [\"[A BC DEF\" \" GHIJ \" \" KLMNO] \"]}" {:added "3.0"} [arr {:keys [align length]} padding spacing] (let [pad (apply str (repeat padding common/+pad+)) space (apply str (repeat spacing common/+space+))] (if (empty? arr) {:rows [(justify align (str pad "[]" pad) length)]} (reduce (fn [{:keys [current rows] :as out} row-item] (let [s (str row-item) l (count s)] (cond (nil? current) {:rows rows :current (str pad "[" s)} (nil? row-item) {:rows (conj rows (justify align (str current "]") length))} (> (+ l spacing (count current)) length) {:rows (conj rows (justify align current length)) :current (str pad " " s)} :else {:rows rows :current (str current space s)}))) {:rows []} (conj arr nil))))) (defn row-elements "layout raw elements based on alignment and length properties (row-elements [\"hello\" :world [:a :b :c :d :e :f]] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) => [[\" hello\"] [\" :world \"] [\"[:a :b :c \" \" :d :e :f]\"]]" {:added "3.0"} [row {:keys [padding spacing columns] :as params}] (let [pad (apply str (repeat padding common/+pad+)) prep-fn (fn [row-item {:keys [format align length] :as column}] (let [row-item (if format (string/format format row-item) row-item)] (if (sequential? row-item) (:rows (seq-elements row-item column padding spacing)) [(justify align (str pad row-item) length)])))] (mapv (fn [row-item column] (let [data (if (result/result? row-item) (:data row-item) row-item)] (prep-fn data column))) row columns))) (defn prepare-elements "same as row-elements but allows for colors and results (prepare-elements [\"hello\" :world [:a :b :c :d]] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) => [[\" hello\" \" \"] [\" :world \" \" \"] [\"[:a :b :c \" \" :d] \"]]" {:added "3.0"} [row {:keys [padding columns] :as params}] (let [pad (apply str (repeat padding common/+pad+)) elements (row-elements row params) height (apply max (map count elements)) style (fn [lines color] (if color (map #(ansi/style % color) lines) lines)) lines (mapv (fn [s {:keys [align length color]} row-item] (let [color (if (result/result? row-item) #{(:status row-item)} color)] (-> (pad-down s length height) (style color)))) elements columns row)] lines)) (defn print-header "prints a header for the row (-> (print-header [:id :name :value] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) (with-out-str))" {:added "3.0"} [titles {:keys [padding columns] :as params}] (let [pad (pad padding) header (-> (apply str (mapv (fn [title {:keys [align length]}] (str pad (justify align (name title) length))) titles columns)) (ansi/style #{:bold}))] (println header) (print "\n"))) (defn print-row "prints a row to output (-> (print-row [\"hello\" :world (result/result {:data [:a :b :c :d :e :f] :status :info})] {:padding 0 :spacing 1 :columns [{:align :right :length 10} {:align :center :length 10} {:align :left :length 10}]}) (with-out-str))" {:added "3.0"} [row params] (apply mapv println (prepare-elements row params))) (defn print-title "prints the title (-> (print-title \"Hello World\") (with-out-str))" {:added "3.0"} [title] (let [line (apply str (repeat (count title) \-))] (print (ansi/style (string/format "\n%s\n%s\n%s\n" line title line) #{:bold})))) (defn print-subtitle "prints the subtitle (-> (print-subtitle \"Hello Again\") (with-out-str))" {:added "3.0"} [text] (print (ansi/style text #{:bold}) "\n")) (defn print-column "prints the column (-> (print-column [[:id.a {:data 100}] [:id.b {:data 200}]] :data #{}) (with-out-str))" {:added "3.0"} [items name color] (let [ns-len (or (->> items (map (comp count str first)) sort last) 20) display {:padding 1 :spacing 1 :columns [{:id :key :length (inc ns-len) :align :left} {:id name :length 60 :color color}]}] (print-header [:key name] display) (doseq [[key m] items] (print-row [key (get m name)] display)) (print "\n"))) (defn print-compare "outputs a side by side comparison (-> (print-compare [['hara.code [[:a :b :c] [:d :e :f]]]]) (with-out-str))" {:added "3.0"} [output] (let [ns-len (or (->> output (map (comp count str first)) sort last) 20) item-params {:padding 1 :spacing 1 :columns [{:id :ns :length (inc ns-len) :align :left} {:id :data :length 50 :color #{:highlight}} {:id :data :length 50 :color #{:magenta}}]}] (doseq [[ns [src test]] output] (print-row [ns src (if (empty? test) :no-tests test)] item-params)) (print "\n"))) (defn print-summary "outputs the summary of results (-> (print-summary {:count 6 :files 2}) (with-out-str))" {:added "3.0"} [m] (let [ks (sort (keys m))] (print (ansi/style (str "SUMMARY " m "\n") #{:bold})))) (defn format-tree "returns a string representation of a tree (-> (format-tree '[{a \"1.1\"} [{b \"1.2\"} [{c \"1.3\"} {d \"1.4\"}]]]) (string/split-lines)) => [\"{a \\\"1.1\\\"}\" \" {b \\\"1.2\\\"}\" \" {c \\\"1.3\\\"}\" \" {d \\\"1.4\\\"}\" \"\"]" {:added "3.0"} ([tree] (apply str (map #(format-tree % "" nil?) tree))) ([tree prefix check] (if (and (vector? tree) (not (check tree))) (->> (map #(format-tree % (str prefix " ") check) tree) (apply str)) (str prefix tree "\n")))) (defn print-tree "outputs the result of `format-tree` (print-tree '[{a \"1.1\"} [{b \"1.2\"} [{c \"1.3\"} {d \"1.4\"}]]])" {:added "3.0"} ([tree] (print-tree tree "" nil?)) ([tree prefix check] (let [output (->> (format-tree tree prefix check) (string/split-lines)) min-spaces (apply min (map (fn [s] (-> (re-find #"^(\s*)" s) first count)) output)) output (->> output (map #(subs % min-spaces)) (map (fn [s] (if (.startsWith s " ") (ansi/green "" s) (ansi/bold "\n" s)))))] (println (string/join output "\n")))))
83d28562e8685107cc967fe72be385d55fb9d91f87c3eaecc873f47e08d991b3
clj-kondo/clj-kondo
alt.clj
(ns core-async.alt (:require [clojure.core.async :as a] [clojure.string :as str])) (def c (a/chan)) (def t (a/timeout 10000)) (a/alt! [c t] ([v ch] [ch v]) ;; no unresolved symbol warnings x1 x2) ;; unresolved symbols ;; no unresolved symbol warnings ;; namespace clojure.string is loaded from cache, so invalid arity (a/alt!! [c t] ([v ch] (str/join "\n" [ch v] 1)) x3 x4) ;; unresolved symbols (loop [] (a/alt!! (a/timeout 1000) ([v _ch] (println "got" v) (recur)))) ;; no invalid arity for recur
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/626978461cbf113c376634cdf034d7262deb429f/corpus/core_async/alt.clj
clojure
no unresolved symbol warnings unresolved symbols no unresolved symbol warnings namespace clojure.string is loaded from cache, so invalid arity unresolved symbols no invalid arity for recur
(ns core-async.alt (:require [clojure.core.async :as a] [clojure.string :as str])) (def c (a/chan)) (def t (a/timeout 10000)) (a/alt!! [c t] ([v ch] (str/join "\n" [ch v] 1)) (loop [] (a/alt!! (a/timeout 1000) ([v _ch] (println "got" v)
c1ae65babb53b9021064c297f31873b83eb705a3d46fe58f619f40fb1ebb6088
acieroid/scala-am
phil.scm
Adapted from Savina benchmarks ( " Dining Philosophers benchmarks " , coming from Wikipedia ) ;; This is the -seq version (letrec ((N 3) (M 3) (rounds M) (num-forks N) (counter-actor (actor "counter" (n) (add (m) (become counter-actor (+ n m))) (finish () (display n) (terminate)))) (arbitrator-actor (actor "arbitrator" (forks num-exited) (hungry (p id) (let ((left id) (right (modulo (+ id 1) num-forks))) (if (or (vector-ref forks left) (vector-ref forks right)) (send p denied) (begin ;; Modeled as side effects, probably not the best thing to do... but since there is only one arbitrator , that should be fine (vector-set! forks left #t) (vector-set! forks right #t) (send p eat)))) (become arbitrator-actor forks num-exited)) (done (id) (let ((left id) (right (modulo (+ id 1) num-forks))) (vector-set! left #f) (vector-set! right #f)) (become arbitrator-actor forks num-exited)) (exit () (if (= (+ num-exited 1) num-forks) (terminate) (become arbitrator-actor forks (+ num-exited 1)))))) (philosopher-actor (actor "philosopher" (id rounds-so-far local-counter) (denied () (send arbitrator hungry self id) (become philosopher-actor id rounds-so-far (+ local-counter 1))) (eat () (send counter add local-counter) (if (< (+ rounds-so-far 1) rounds) (begin (send self start) (become philosopher-actor id (+ rounds-so-far 1) local-counter)) (begin (send arbitrator done id) (terminate)))) (start () (send arbitrator hungry self id) (become philosopher-actor id rounds-so-far local-counter)))) (counter (create counter-actor 0)) (arbitrator (create arbitrator-actor (vector #f #f #f) 0)) (phil1 (create philosopher-actor 0 0 0)) (phil2 (create philosopher-actor 0 0 0)) (phil3 (create philosopher-actor 0 0 0))) (send phil1 start) (send phil2 start) (send phil3 start))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/actors/savina/phil.scm
scheme
This is the -seq version Modeled as side effects, probably not the best thing to do...
Adapted from Savina benchmarks ( " Dining Philosophers benchmarks " , coming from Wikipedia ) (letrec ((N 3) (M 3) (rounds M) (num-forks N) (counter-actor (actor "counter" (n) (add (m) (become counter-actor (+ n m))) (finish () (display n) (terminate)))) (arbitrator-actor (actor "arbitrator" (forks num-exited) (hungry (p id) (let ((left id) (right (modulo (+ id 1) num-forks))) (if (or (vector-ref forks left) (vector-ref forks right)) (send p denied) (begin but since there is only one arbitrator , that should be fine (vector-set! forks left #t) (vector-set! forks right #t) (send p eat)))) (become arbitrator-actor forks num-exited)) (done (id) (let ((left id) (right (modulo (+ id 1) num-forks))) (vector-set! left #f) (vector-set! right #f)) (become arbitrator-actor forks num-exited)) (exit () (if (= (+ num-exited 1) num-forks) (terminate) (become arbitrator-actor forks (+ num-exited 1)))))) (philosopher-actor (actor "philosopher" (id rounds-so-far local-counter) (denied () (send arbitrator hungry self id) (become philosopher-actor id rounds-so-far (+ local-counter 1))) (eat () (send counter add local-counter) (if (< (+ rounds-so-far 1) rounds) (begin (send self start) (become philosopher-actor id (+ rounds-so-far 1) local-counter)) (begin (send arbitrator done id) (terminate)))) (start () (send arbitrator hungry self id) (become philosopher-actor id rounds-so-far local-counter)))) (counter (create counter-actor 0)) (arbitrator (create arbitrator-actor (vector #f #f #f) 0)) (phil1 (create philosopher-actor 0 0 0)) (phil2 (create philosopher-actor 0 0 0)) (phil3 (create philosopher-actor 0 0 0))) (send phil1 start) (send phil2 start) (send phil3 start))
e837ae3ac033beb04bb404618a5fd3de54d07ba2d8cd5a4c490c18e605a3745f
YoEight/lambda-database-experiment
Main.hs
-------------------------------------------------------------------------------- -- | -- Module : Main Copyright : ( C ) 2017 -- License : (see the file LICENSE) -- Maintainer : < > -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- import ClassyPrelude import qualified Test.Tasty import Test.Tasty.Hspec -------------------------------------------------------------------------------- import qualified Test.Serialize as Serialize -------------------------------------------------------------------------------- main :: IO () main = do tree <- sequence [ testSpec "Serialize" Serialize.spec ] let test = Test.Tasty.testGroup "protocol" tree Test.Tasty.defaultMain test
null
https://raw.githubusercontent.com/YoEight/lambda-database-experiment/da4fab8bd358fb8fb78412c805d6f5bc05854432/lambda-protocol/test-suite/Main.hs
haskell
------------------------------------------------------------------------------ | Module : Main License : (see the file LICENSE) Stability : provisional Portability : non-portable ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Copyright : ( C ) 2017 Maintainer : < > import ClassyPrelude import qualified Test.Tasty import Test.Tasty.Hspec import qualified Test.Serialize as Serialize main :: IO () main = do tree <- sequence [ testSpec "Serialize" Serialize.spec ] let test = Test.Tasty.testGroup "protocol" tree Test.Tasty.defaultMain test
20e27ac536fe5956a83ac041544ed9d2d7a15d28f7375c0e27a4159f7e54892d
input-output-hk/cardano-wallet
Properties.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLabels # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -fno - warn - unused - imports # module Cardano.Wallet.DB.Properties ( properties ) where import Prelude import Cardano.Wallet.DB ( DBLayer (..), ErrWalletAlreadyExists (..), cleanDB ) import Cardano.Wallet.DB.Arbitrary ( GenState , GenTxHistory (..) , InitialCheckpoint (..) , KeyValPairs (..) , MockChain (..) ) import Cardano.Wallet.DB.Pure.Implementation ( filterTxHistory ) import Cardano.Wallet.DB.WalletState ( ErrNoSuchWallet (..) ) import Cardano.Wallet.DummyTarget.Primitive.Types ( dummyGenesisParameters ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey (..) ) import Cardano.Wallet.Primitive.Model ( Wallet, applyBlock, currentTip ) import Cardano.Wallet.Primitive.Types ( BlockHeader (..) , ChainPoint (..) , GenesisParameters , ProtocolParameters , Slot , SlotId (..) , SlotNo (..) , SortOrder (..) , WalletId (..) , WalletMetadata (..) , WithOrigin (..) , chainPointFromBlockHeader , toSlot , wholeRange ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..) ) import Cardano.Wallet.Primitive.Types.Tx ( Direction (..) , TransactionInfo (..) , Tx (..) , TxMeta (..) , TxStatus (..) , isPending , toTxHistory ) import Cardano.Wallet.Unsafe ( unsafeRunExceptT ) import Cardano.Wallet.Util ( ShowFmt (..) ) import Control.Monad ( forM, forM_, void ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Class ( lift ) import Control.Monad.Trans.Except ( ExceptT, mapExceptT, runExceptT ) import Control.Monad.Trans.State.Strict ( evalStateT, get, modify' ) import Data.Bifunctor ( bimap ) import Data.Function ( (&) ) import Data.Functor.Identity ( Identity (..) ) import Data.Generics.Internal.VL.Lens ( view, (^.) ) import Data.Generics.Labels () import Data.List ( unfoldr ) import Data.Maybe ( catMaybes, isNothing, mapMaybe ) import Data.Quantity ( Quantity (..) ) import Data.Set ( Set ) import Data.Word ( Word32, Word64 ) import Fmt ( Buildable, blockListF, pretty ) import Test.Hspec ( SpecWith, describe, it, shouldBe, shouldReturn ) import Test.QuickCheck ( Arbitrary (..) , Gen , Property , checkCoverage , choose , conjoin , counterexample , cover , elements , forAll , label , property , suchThat , (.&&.) , (===) , (==>) ) import Test.QuickCheck.Monadic ( PropertyM, assert, monadicIO, monitor, pick, run ) import UnliftIO.Async ( forConcurrently_ ) import qualified Data.List as L import qualified Data.Map.Strict as Map import qualified Data.Set as Set properties :: (GenState s, Eq s) => SpecWith (DBLayer IO s ShelleyKey) properties = do describe "Extra Properties about DB initialization" $ do it "createWallet . listWallets yields expected results" (property . prop_createListWallet) it "creating same wallet twice yields an error" (property . prop_createWalletTwice) it "removing the same wallet twice yields an error" (property . prop_removeWalletTwice) describe "put . read yields a result" $ do it "Checkpoint" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) it "Wallet Metadata" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) it "Tx History" $ property . prop_readAfterPut putTxHistory_ readTxHistory_ it "Private Key" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) describe "getTx properties" $ do it "can read after putting tx history for valid tx id" $ property . prop_getTxAfterPutValidTxId it "cannot read after putting tx history for invalid tx id" $ property . prop_getTxAfterPutInvalidTxId it "cannot read after putting tx history for invalid wallet id" $ property . prop_getTxAfterPutInvalidWalletId describe "can't put before wallet exists" $ do it "Checkpoint" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) Nothing it "Wallet Metadata" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) Nothing it "Tx History" $ property . prop_putBeforeInit putTxHistory_ readTxHistory_ (pure mempty) it "Private Key" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) Nothing describe "put doesn't affect other resources" $ do it "Checkpoint vs Wallet Metadata & Tx History & Private Key" $ property . prop_isolation (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readWalletMeta) readTxHistory_ (\DBLayer{..} -> atomically . readPrivateKey) it "Wallet Metadata vs Tx History & Checkpoint & Private Key" $ property . prop_isolation (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) readTxHistory_ (\DBLayer{..} -> atomically . readCheckpoint) (\DBLayer{..} -> atomically . readPrivateKey) it "Tx History vs Checkpoint & Wallet Metadata & Private Key" $ property . prop_isolation putTxHistory_ (\DBLayer{..} -> atomically . readCheckpoint) (\DBLayer{..} -> atomically . readWalletMeta) (\DBLayer{..} -> atomically . readPrivateKey) describe "can't read after delete" $ do it "Checkpoint" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readCheckpoint) Nothing it "Wallet Metadata" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readWalletMeta) Nothing it "Tx History" $ property . prop_readAfterDelete readTxHistory_ (pure mempty) it "Private Key" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readPrivateKey) Nothing describe "sequential puts replace values in order" $ do it "Checkpoint" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) lrp it "Wallet Metadata" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) lrp it "Tx History" $ checkCoverage . prop_sequentialPut putTxHistory_ readTxHistory_ sortedUnions it "Private Key" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) lrp describe "parallel puts replace values in _any_ order" $ do it "Checkpoint" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) (length . lrp @Maybe) it "Wallet Metadata" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) (length . lrp @Maybe) it "Tx History" $ checkCoverage . prop_parallelPut putTxHistory_ readTxHistory_ (length . sortedUnions) it "Private Key" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) (length . lrp @Maybe) describe "rollback" $ do it "Can rollback to any arbitrary known checkpoint" (property . prop_rollbackCheckpoint) it "Correctly re-construct tx history on rollbacks" (checkCoverage . prop_rollbackTxHistory) -- | Wrap the result of 'readTransactions' in an arbitrary identity Applicative readTxHistory_ :: Functor m => DBLayer m s ShelleyKey -> WalletId -> m (Identity GenTxHistory) readTxHistory_ DBLayer{..} wid = (Identity . GenTxHistory . fmap toTxHistory) <$> atomically (readTransactions wid Nothing Descending wholeRange Nothing) putTxHistory_ :: DBLayer m s ShelleyKey -> WalletId -> GenTxHistory -> ExceptT ErrNoSuchWallet m () putTxHistory_ DBLayer{..} wid = mapExceptT atomically . putTxHistory wid . unGenTxHistory {------------------------------------------------------------------------------- Utils -------------------------------------------------------------------------------} -- | Keep only the ( L)ast ( R)ecently ( P)ut entry lrp :: (Applicative f, Ord k) => [(k, v)] -> [f v] lrp = fmap snd . L.sortOn fst . Map.toList . foldl (\m (k, v) -> Map.insert k (pure v) m) mempty -- | Keep the unions (right-biaised) of all entry unions :: (Monoid v, Ord k) => [(k, v)] -> [Identity v] unions = fmap Identity . Map.elems . foldl (\m (k, v) -> Map.unionWith (<>) (Map.fromList [(k, v)]) m) mempty -- | Keep the unions (right-biased) of all transactions, and sort them in the -- default order for readTransactions. sortedUnions :: Ord k => [(k, GenTxHistory)] -> [Identity GenTxHistory] sortedUnions = map (Identity . sort' . runIdentity) . unions where sort' = GenTxHistory . filterTxHistory Nothing Descending wholeRange . unGenTxHistory | Execute an action once per key @k@ present in the given list once :: (Ord k, Monad m) => [(k,v)] -> ((k,v) -> m a) -> m [a] once xs action = fmap catMaybes $ flip evalStateT mempty $ forM xs $ \(k, v) -> do s <- get modify' (Set.insert k) if Set.member k s then pure Nothing else Just <$> lift (action (k, v)) -- | Like 'once', but discards the result once_ :: (Ord k, Monad m) => [(k,v)] -> ((k,v) -> m a) -> m () once_ xs = void . once xs -- | Filter a transaction list according to the given predicate, returns their -- ids. filterTxs :: (TxMeta -> Bool) -> [(Tx, TxMeta)] -> [Hash "Tx"] filterTxs predicate = mapMaybe fn where fn (tx, meta) = if predicate meta then Just (txId tx) else Nothing -- | Pick an arbitrary element from a monadic property, and label it in the -- counterexample: -- > > > ShowFmt meta < - namedPick " Wallet Metadata " arbitrary -- -- If failing, the following line will be added to the counter example: -- -- @ Wallet Metadata : squirtle ( still restoring ( 94 % ) ) , created at 1963 - 10 - 09 06:50:11 UTC , not delegating -- @ namedPick :: Show a => String -> Gen a -> PropertyM IO a namedPick lbl gen = monitor (counterexample ("\n" <> lbl <> ":")) *> pick gen -- | Like 'assert', but allow giving a label / title before running a assertion assertWith :: String -> Bool -> PropertyM IO () assertWith lbl condition = do let flag = if condition then "✓" else "✗" monitor (counterexample $ lbl <> " " <> flag) assert condition {------------------------------------------------------------------------------- Properties -------------------------------------------------------------------------------} -- | Can list created wallets prop_createListWallet :: DBLayer IO s ShelleyKey -> KeyValPairs WalletId (InitialCheckpoint s, WalletMetadata) -> Property prop_createListWallet db@DBLayer{..} (KeyValPairs pairs) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do res <- once pairs $ \(k, (InitialCheckpoint cp0, meta)) -> atomically $ unsafeRunExceptT $ initializeWallet k cp0 meta mempty gp (length <$> atomically listWallets) `shouldReturn` length res -- | Trying to create a same wallet twice should yield an error prop_createWalletTwice :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> Property prop_createWalletTwice db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do let err = ErrWalletAlreadyExists wid atomically (runExceptT $ initializeWallet wid cp0 meta mempty gp) `shouldReturn` Right () atomically (runExceptT $ initializeWallet wid cp0 meta mempty gp) `shouldReturn` Left err -- | Trying to remove a same wallet twice should yield an error prop_removeWalletTwice :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> Property prop_removeWalletTwice db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) = monadicIO (setup >> prop) where setup = liftIO $ do cleanDB db atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do let err = ErrNoSuchWallet wid atomically (runExceptT $ removeWallet wid) `shouldReturn` Right () atomically (runExceptT $ removeWallet wid) `shouldReturn` Left err -- | Checks that a given resource can be read after having been inserted in DB. prop_readAfterPut :: ( Buildable (f a), Eq (f a), Applicative f, GenState s ) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () ) -- ^ Put Operation -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> DBLayer IO s ShelleyKey -> (WalletId, a) -- ^ Property arguments -> Property prop_readAfterPut putOp readOp db@DBLayer{..} (wid, a) = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do run $ unsafeRunExceptT $ putOp db wid a res <- run $ readOp db wid let fa = pure a monitor $ counterexample $ "\nInserted\n" <> pretty fa monitor $ counterexample $ "\nRead\n" <> pretty res assertWith "Inserted == Read" (res == fa) prop_getTxAfterPutValidTxId :: GenState s => DBLayer IO s ShelleyKey -> WalletId -> GenTxHistory -> Property prop_getTxAfterPutValidTxId db@DBLayer{..} wid txGen = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do let txs = unGenTxHistory txGen run $ unsafeRunExceptT $ mapExceptT atomically $ putTxHistory wid txs forM_ txs $ \(Tx {txId}, txMeta) -> do (Just (TransactionInfo {txInfoId, txInfoMeta})) <- run $ atomically $ unsafeRunExceptT $ getTx wid txId monitor $ counterexample $ "\nInserted\n" <> pretty txMeta <> " for txId: " <> pretty txId monitor $ counterexample $ "\nRead\n" <> pretty txInfoMeta <> " for txId: " <> pretty txInfoId assertWith "Inserted is included in Read" (txMeta == txInfoMeta && txId == txInfoId) prop_getTxAfterPutInvalidTxId :: GenState s => DBLayer IO s ShelleyKey -> WalletId -> GenTxHistory -> (Hash "Tx") -> Property prop_getTxAfterPutInvalidTxId db@DBLayer{..} wid txGen txId' = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do let txs = unGenTxHistory txGen run $ unsafeRunExceptT $ mapExceptT atomically $ putTxHistory wid txs res <- run $ atomically $ unsafeRunExceptT $ getTx wid txId' assertWith "Irrespective of Inserted, Read is Nothing for invalid tx id" (isNothing res) prop_getTxAfterPutInvalidWalletId :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> GenTxHistory -> WalletId -> Property prop_getTxAfterPutInvalidWalletId db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) txGen wid' = wid /= wid' ==> monadicIO (setup >> prop) where setup = liftIO $ do cleanDB db atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do let txs = unGenTxHistory txGen atomically (runExceptT $ putTxHistory wid txs) `shouldReturn` Right () forM_ txs $ \(Tx {txId}, _) -> do let err = ErrNoSuchWallet wid' atomically (runExceptT $ getTx wid' txId) `shouldReturn` Left err -- | Can't put resource before a wallet has been initialized prop_putBeforeInit :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () ) -- ^ Put Operation -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> f a -- ^ An 'empty' value for the 'Applicative' f -> DBLayer IO s ShelleyKey -> (WalletId, a) -- ^ Property arguments -> Property prop_putBeforeInit putOp readOp empty db (wid, a) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do runExceptT (putOp db wid a) >>= \case Right _ -> fail "expected put operation to fail but it succeeded!" Left err -> err `shouldBe` ErrNoSuchWallet wid (ShowFmt <$> readOp db wid) `shouldReturn` (ShowFmt empty) | Modifying one resource leaves the other untouched prop_isolation :: ( Buildable (f b), Eq (f b) , Buildable (g c), Eq (g c) , Buildable (h d), Eq (h d) , GenState s , Show s ) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () ) -- ^ Put Operation -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f b) ^ Read Operation for another resource -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (g c) ^ Read Operation for another resource -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (h d) ^ Read Operation for another resource -> DBLayer IO s ShelleyKey -> (ShowFmt WalletId, ShowFmt a) -- ^ Properties arguments -> Property prop_isolation putA readB readC readD db@DBLayer{..} (ShowFmt wid, ShowFmt a) = monadicIO (setup >>= prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary (GenTxHistory txs) <- pick arbitrary run $ atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ putTxHistory wid txs run $ (,,) <$> readB db wid <*> readC db wid <*> readD db wid prop (b, c, d) = liftIO $ do unsafeRunExceptT $ putA db wid a (ShowFmt <$> readB db wid) `shouldReturn` ShowFmt b (ShowFmt <$> readC db wid) `shouldReturn` ShowFmt c (ShowFmt <$> readD db wid) `shouldReturn` ShowFmt d -- | Can't read back data after delete prop_readAfterDelete :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> f a -- ^ An 'empty' value for the 'Applicative' f -> DBLayer IO s ShelleyKey -> ShowFmt WalletId -> Property prop_readAfterDelete readOp empty db@DBLayer{..} (ShowFmt wid) = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do atomically $ unsafeRunExceptT $ removeWallet wid (ShowFmt <$> readOp db wid) `shouldReturn` ShowFmt empty | Check that the DB supports multiple sequential puts for a given resource prop_sequentialPut :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () ) -- ^ Put Operation -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> (forall k. Ord k => [(k, a)] -> [f a]) -- ^ How do we expect operations to resolve -> DBLayer IO s ShelleyKey -> KeyValPairs (ShowFmt WalletId) (ShowFmt a) -- ^ Property arguments -> Property prop_sequentialPut putOp readOp resolve db@DBLayer{..} kv = cover 25 cond "conflicting db entries" $ monadicIO (setup >> prop) where pairs = (\(KeyValPairs xs) -> bimap unShowFmt unShowFmt <$> xs) kv -- Make sure that we have some conflicting insertion to actually test the -- semantic of the DB Layer. cond = L.length (L.nub ids) /= L.length ids where ids = map fst pairs setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ once_ pairs $ \(k, _) -> initializeWallet k cp0 meta mempty gp prop = do run $ unsafeRunExceptT $ forM_ pairs $ uncurry (putOp db) res <- run $ once pairs (readOp db . fst) let resolved = resolve pairs monitor $ counterexample $ "\nResolved\n" <> pretty resolved monitor $ counterexample $ "\nRead\n" <> pretty res assertWith "Resolved == Read" (res == resolved) | Check that the DB supports multiple sequential puts for a given resource prop_parallelPut :: (GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () ) -- ^ Put Operation -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> (forall k. Ord k => [(k, a)] -> Int) -- ^ How many entries to we expect in the end -> DBLayer IO s ShelleyKey -> KeyValPairs WalletId a -- ^ Property arguments -> Property prop_parallelPut putOp readOp resolve db@DBLayer{..} (KeyValPairs pairs) = cover 25 cond "conflicting db entries" $ monadicIO (setup >> prop) where -- Make sure that we have some conflicting insertion to actually test the -- semantic of the DB Layer. cond = L.length (L.nub ids) /= L.length ids where ids = map fst pairs setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ once_ pairs $ \(k, _) -> initializeWallet k cp0 meta mempty gp prop = liftIO $ do forConcurrently_ pairs $ unsafeRunExceptT . uncurry (putOp db) res <- once pairs (readOp db . fst) length res `shouldBe` resolve pairs -- | Can rollback to any particular checkpoint previously stored prop_rollbackCheckpoint :: forall s k. (GenState s, Eq s) => DBLayer IO s k -> InitialCheckpoint s -> MockChain -> Property prop_rollbackCheckpoint db@DBLayer{..} (InitialCheckpoint cp0) (MockChain chain) = do monadicIO $ do ShowFmt wid <- namedPick "Wallet ID" arbitrary ShowFmt meta <- namedPick "Wallet Metadata" arbitrary ShowFmt point <- namedPick "Rollback target" (elements $ ShowFmt <$> cps) setup wid meta >> prop wid point where cps :: [Wallet s] cps = flip unfoldr (chain, cp0) $ \case ([], _) -> Nothing (b:q, cp) -> let cp' = snd . snd $ applyBlock b cp in Just (cp', (q, cp')) setup wid meta = run $ do cleanDB db atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ forM_ cps (putCheckpoint wid) prop wid point = do let tip = currentTip point point' <- run $ atomically $ unsafeRunExceptT $ rollbackTo wid (toSlot $ chainPointFromBlockHeader tip) cp <- run $ atomically $ readCheckpoint wid let str = maybe "∅" pretty cp monitor $ counterexample ("Checkpoint after rollback: \n" <> str) assert (ShowFmt cp == ShowFmt (pure point)) assert (ShowFmt point' == ShowFmt (chainPointFromBlockHeader tip)) -- | Re-schedule pending transaction on rollback, i.e.: -- ( PoR = Point of Rollback ) -- - There 's no transaction beyond the PoR - Any transaction after the PoR is forgotten -- -- FIXME LATER: This function only tests slot numbers to roll back to, -- not Slot. See note [PointSlotNo] for the difference. -- The reason for this restriction is that the 'rollbackTo' function from the DBLayer currently does not roll the TxHistory back correctly -- if there is a rollback to genesis. prop_rollbackTxHistory :: forall s k. () => DBLayer IO s k -> InitialCheckpoint s -> GenTxHistory -> Property prop_rollbackTxHistory db@DBLayer{..} (InitialCheckpoint cp0) (GenTxHistory txs0) = do monadicIO $ do ShowFmt wid <- namedPick "Wallet ID" arbitrary ShowFmt meta <- namedPick "Wallet Metadata" arbitrary ShowFmt slot <- namedPick "Requested Rollback slot" arbitrary let ixs = forgotten slot monitor $ label ("Forgotten tx after point: " <> show (L.length ixs)) monitor $ cover 50 (not $ null ixs) "rolling back something" setup wid meta >> prop wid slot where setup wid meta = run $ do cleanDB db atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ putTxHistory wid txs0 prop wid requestedPoint = do point <- run $ unsafeRunExceptT $ mapExceptT atomically $ rollbackTo wid (At requestedPoint) txs <- run $ atomically $ fmap toTxHistory <$> readTransactions wid Nothing Descending wholeRange Nothing monitor $ counterexample $ "\n" <> "Actual Rollback Point:\n" <> (pretty point) monitor $ counterexample $ "\nOriginal tx history:\n" <> (txsF txs0) monitor $ counterexample $ "\nNew tx history:\n" <> (txsF txs) let slot = pseudoSlotNo point assertWith "All txs before are still known" $ L.sort (knownAfterRollback slot) == L.sort (txId . fst <$> txs) assertWith "All txs are now before the point of rollback" $ all (isBefore slot . snd) txs where txsF :: [(Tx, TxMeta)] -> String txsF = L.intercalate "\n" . map (\(tx, meta) -> unwords [ "- " , pretty (txId tx) , pretty (meta ^. #slotNo) , pretty (meta ^. #status) , pretty (meta ^. #direction) , pretty (meta ^. #amount) ]) pseudoSlotNo ChainPointAtGenesis = SlotNo 0 pseudoSlotNo (ChainPoint slot _) = slot isBefore :: SlotNo -> TxMeta -> Bool isBefore slot meta = (slotNo :: TxMeta -> SlotNo) meta <= slot forgotten :: SlotNo -> [Hash "Tx"] forgotten slot = let isAfter meta = meta ^. #slotNo > slot in filterTxs isAfter txs0 knownAfterRollback :: SlotNo -> [Hash "Tx"] knownAfterRollback slot = filterTxs (isBefore slot) txs0 gp :: GenesisParameters gp = dummyGenesisParameters
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/cfa4d812c7aae44c301a0b28752ea0b7e9476d4c/lib/wallet/test/unit/Cardano/Wallet/DB/Properties.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes # | Wrap the result of 'readTransactions' in an arbitrary identity Applicative ------------------------------------------------------------------------------ Utils ------------------------------------------------------------------------------ | Keep only the | Keep the unions (right-biaised) of all entry | Keep the unions (right-biased) of all transactions, and sort them in the default order for readTransactions. | Like 'once', but discards the result | Filter a transaction list according to the given predicate, returns their ids. | Pick an arbitrary element from a monadic property, and label it in the counterexample: If failing, the following line will be added to the counter example: @ @ | Like 'assert', but allow giving a label / title before running a assertion ------------------------------------------------------------------------------ Properties ------------------------------------------------------------------------------ | Can list created wallets | Trying to create a same wallet twice should yield an error | Trying to remove a same wallet twice should yield an error | Checks that a given resource can be read after having been inserted in DB. ^ Put Operation ^ Property arguments | Can't put resource before a wallet has been initialized ^ Put Operation ^ An 'empty' value for the 'Applicative' f ^ Property arguments ^ Put Operation ^ Properties arguments | Can't read back data after delete ^ An 'empty' value for the 'Applicative' f ^ Put Operation ^ How do we expect operations to resolve ^ Property arguments Make sure that we have some conflicting insertion to actually test the semantic of the DB Layer. ^ Put Operation ^ How many entries to we expect in the end ^ Property arguments Make sure that we have some conflicting insertion to actually test the semantic of the DB Layer. | Can rollback to any particular checkpoint previously stored | Re-schedule pending transaction on rollback, i.e.: FIXME LATER: This function only tests slot numbers to roll back to, not Slot. See note [PointSlotNo] for the difference. The reason for this restriction is that the 'rollbackTo' function if there is a rollback to genesis.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLabels # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -fno - warn - unused - imports # module Cardano.Wallet.DB.Properties ( properties ) where import Prelude import Cardano.Wallet.DB ( DBLayer (..), ErrWalletAlreadyExists (..), cleanDB ) import Cardano.Wallet.DB.Arbitrary ( GenState , GenTxHistory (..) , InitialCheckpoint (..) , KeyValPairs (..) , MockChain (..) ) import Cardano.Wallet.DB.Pure.Implementation ( filterTxHistory ) import Cardano.Wallet.DB.WalletState ( ErrNoSuchWallet (..) ) import Cardano.Wallet.DummyTarget.Primitive.Types ( dummyGenesisParameters ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey (..) ) import Cardano.Wallet.Primitive.Model ( Wallet, applyBlock, currentTip ) import Cardano.Wallet.Primitive.Types ( BlockHeader (..) , ChainPoint (..) , GenesisParameters , ProtocolParameters , Slot , SlotId (..) , SlotNo (..) , SortOrder (..) , WalletId (..) , WalletMetadata (..) , WithOrigin (..) , chainPointFromBlockHeader , toSlot , wholeRange ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..) ) import Cardano.Wallet.Primitive.Types.Tx ( Direction (..) , TransactionInfo (..) , Tx (..) , TxMeta (..) , TxStatus (..) , isPending , toTxHistory ) import Cardano.Wallet.Unsafe ( unsafeRunExceptT ) import Cardano.Wallet.Util ( ShowFmt (..) ) import Control.Monad ( forM, forM_, void ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Class ( lift ) import Control.Monad.Trans.Except ( ExceptT, mapExceptT, runExceptT ) import Control.Monad.Trans.State.Strict ( evalStateT, get, modify' ) import Data.Bifunctor ( bimap ) import Data.Function ( (&) ) import Data.Functor.Identity ( Identity (..) ) import Data.Generics.Internal.VL.Lens ( view, (^.) ) import Data.Generics.Labels () import Data.List ( unfoldr ) import Data.Maybe ( catMaybes, isNothing, mapMaybe ) import Data.Quantity ( Quantity (..) ) import Data.Set ( Set ) import Data.Word ( Word32, Word64 ) import Fmt ( Buildable, blockListF, pretty ) import Test.Hspec ( SpecWith, describe, it, shouldBe, shouldReturn ) import Test.QuickCheck ( Arbitrary (..) , Gen , Property , checkCoverage , choose , conjoin , counterexample , cover , elements , forAll , label , property , suchThat , (.&&.) , (===) , (==>) ) import Test.QuickCheck.Monadic ( PropertyM, assert, monadicIO, monitor, pick, run ) import UnliftIO.Async ( forConcurrently_ ) import qualified Data.List as L import qualified Data.Map.Strict as Map import qualified Data.Set as Set properties :: (GenState s, Eq s) => SpecWith (DBLayer IO s ShelleyKey) properties = do describe "Extra Properties about DB initialization" $ do it "createWallet . listWallets yields expected results" (property . prop_createListWallet) it "creating same wallet twice yields an error" (property . prop_createWalletTwice) it "removing the same wallet twice yields an error" (property . prop_removeWalletTwice) describe "put . read yields a result" $ do it "Checkpoint" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) it "Wallet Metadata" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) it "Tx History" $ property . prop_readAfterPut putTxHistory_ readTxHistory_ it "Private Key" $ property . prop_readAfterPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) describe "getTx properties" $ do it "can read after putting tx history for valid tx id" $ property . prop_getTxAfterPutValidTxId it "cannot read after putting tx history for invalid tx id" $ property . prop_getTxAfterPutInvalidTxId it "cannot read after putting tx history for invalid wallet id" $ property . prop_getTxAfterPutInvalidWalletId describe "can't put before wallet exists" $ do it "Checkpoint" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) Nothing it "Wallet Metadata" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) Nothing it "Tx History" $ property . prop_putBeforeInit putTxHistory_ readTxHistory_ (pure mempty) it "Private Key" $ property . prop_putBeforeInit (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) Nothing describe "put doesn't affect other resources" $ do it "Checkpoint vs Wallet Metadata & Tx History & Private Key" $ property . prop_isolation (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readWalletMeta) readTxHistory_ (\DBLayer{..} -> atomically . readPrivateKey) it "Wallet Metadata vs Tx History & Checkpoint & Private Key" $ property . prop_isolation (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) readTxHistory_ (\DBLayer{..} -> atomically . readCheckpoint) (\DBLayer{..} -> atomically . readPrivateKey) it "Tx History vs Checkpoint & Wallet Metadata & Private Key" $ property . prop_isolation putTxHistory_ (\DBLayer{..} -> atomically . readCheckpoint) (\DBLayer{..} -> atomically . readWalletMeta) (\DBLayer{..} -> atomically . readPrivateKey) describe "can't read after delete" $ do it "Checkpoint" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readCheckpoint) Nothing it "Wallet Metadata" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readWalletMeta) Nothing it "Tx History" $ property . prop_readAfterDelete readTxHistory_ (pure mempty) it "Private Key" $ property . prop_readAfterDelete (\DBLayer{..} -> atomically . readPrivateKey) Nothing describe "sequential puts replace values in order" $ do it "Checkpoint" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) lrp it "Wallet Metadata" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) lrp it "Tx History" $ checkCoverage . prop_sequentialPut putTxHistory_ readTxHistory_ sortedUnions it "Private Key" $ checkCoverage . prop_sequentialPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) lrp describe "parallel puts replace values in _any_ order" $ do it "Checkpoint" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putCheckpoint a0) (\DBLayer{..} -> atomically . readCheckpoint) (length . lrp @Maybe) it "Wallet Metadata" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putWalletMeta a0) (\DBLayer{..} -> atomically . fmap (fmap fst) . readWalletMeta) (length . lrp @Maybe) it "Tx History" $ checkCoverage . prop_parallelPut putTxHistory_ readTxHistory_ (length . sortedUnions) it "Private Key" $ checkCoverage . prop_parallelPut (\DBLayer{..} a0 -> mapExceptT atomically . putPrivateKey a0) (\DBLayer{..} -> atomically . readPrivateKey) (length . lrp @Maybe) describe "rollback" $ do it "Can rollback to any arbitrary known checkpoint" (property . prop_rollbackCheckpoint) it "Correctly re-construct tx history on rollbacks" (checkCoverage . prop_rollbackTxHistory) readTxHistory_ :: Functor m => DBLayer m s ShelleyKey -> WalletId -> m (Identity GenTxHistory) readTxHistory_ DBLayer{..} wid = (Identity . GenTxHistory . fmap toTxHistory) <$> atomically (readTransactions wid Nothing Descending wholeRange Nothing) putTxHistory_ :: DBLayer m s ShelleyKey -> WalletId -> GenTxHistory -> ExceptT ErrNoSuchWallet m () putTxHistory_ DBLayer{..} wid = mapExceptT atomically . putTxHistory wid . unGenTxHistory ( L)ast ( R)ecently ( P)ut entry lrp :: (Applicative f, Ord k) => [(k, v)] -> [f v] lrp = fmap snd . L.sortOn fst . Map.toList . foldl (\m (k, v) -> Map.insert k (pure v) m) mempty unions :: (Monoid v, Ord k) => [(k, v)] -> [Identity v] unions = fmap Identity . Map.elems . foldl (\m (k, v) -> Map.unionWith (<>) (Map.fromList [(k, v)]) m) mempty sortedUnions :: Ord k => [(k, GenTxHistory)] -> [Identity GenTxHistory] sortedUnions = map (Identity . sort' . runIdentity) . unions where sort' = GenTxHistory . filterTxHistory Nothing Descending wholeRange . unGenTxHistory | Execute an action once per key @k@ present in the given list once :: (Ord k, Monad m) => [(k,v)] -> ((k,v) -> m a) -> m [a] once xs action = fmap catMaybes $ flip evalStateT mempty $ forM xs $ \(k, v) -> do s <- get modify' (Set.insert k) if Set.member k s then pure Nothing else Just <$> lift (action (k, v)) once_ :: (Ord k, Monad m) => [(k,v)] -> ((k,v) -> m a) -> m () once_ xs = void . once xs filterTxs :: (TxMeta -> Bool) -> [(Tx, TxMeta)] -> [Hash "Tx"] filterTxs predicate = mapMaybe fn where fn (tx, meta) = if predicate meta then Just (txId tx) else Nothing > > > ShowFmt meta < - namedPick " Wallet Metadata " arbitrary Wallet Metadata : squirtle ( still restoring ( 94 % ) ) , created at 1963 - 10 - 09 06:50:11 UTC , not delegating namedPick :: Show a => String -> Gen a -> PropertyM IO a namedPick lbl gen = monitor (counterexample ("\n" <> lbl <> ":")) *> pick gen assertWith :: String -> Bool -> PropertyM IO () assertWith lbl condition = do let flag = if condition then "✓" else "✗" monitor (counterexample $ lbl <> " " <> flag) assert condition prop_createListWallet :: DBLayer IO s ShelleyKey -> KeyValPairs WalletId (InitialCheckpoint s, WalletMetadata) -> Property prop_createListWallet db@DBLayer{..} (KeyValPairs pairs) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do res <- once pairs $ \(k, (InitialCheckpoint cp0, meta)) -> atomically $ unsafeRunExceptT $ initializeWallet k cp0 meta mempty gp (length <$> atomically listWallets) `shouldReturn` length res prop_createWalletTwice :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> Property prop_createWalletTwice db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do let err = ErrWalletAlreadyExists wid atomically (runExceptT $ initializeWallet wid cp0 meta mempty gp) `shouldReturn` Right () atomically (runExceptT $ initializeWallet wid cp0 meta mempty gp) `shouldReturn` Left err prop_removeWalletTwice :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> Property prop_removeWalletTwice db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) = monadicIO (setup >> prop) where setup = liftIO $ do cleanDB db atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do let err = ErrNoSuchWallet wid atomically (runExceptT $ removeWallet wid) `shouldReturn` Right () atomically (runExceptT $ removeWallet wid) `shouldReturn` Left err prop_readAfterPut :: ( Buildable (f a), Eq (f a), Applicative f, GenState s ) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> DBLayer IO s ShelleyKey -> (WalletId, a) -> Property prop_readAfterPut putOp readOp db@DBLayer{..} (wid, a) = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do run $ unsafeRunExceptT $ putOp db wid a res <- run $ readOp db wid let fa = pure a monitor $ counterexample $ "\nInserted\n" <> pretty fa monitor $ counterexample $ "\nRead\n" <> pretty res assertWith "Inserted == Read" (res == fa) prop_getTxAfterPutValidTxId :: GenState s => DBLayer IO s ShelleyKey -> WalletId -> GenTxHistory -> Property prop_getTxAfterPutValidTxId db@DBLayer{..} wid txGen = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do let txs = unGenTxHistory txGen run $ unsafeRunExceptT $ mapExceptT atomically $ putTxHistory wid txs forM_ txs $ \(Tx {txId}, txMeta) -> do (Just (TransactionInfo {txInfoId, txInfoMeta})) <- run $ atomically $ unsafeRunExceptT $ getTx wid txId monitor $ counterexample $ "\nInserted\n" <> pretty txMeta <> " for txId: " <> pretty txId monitor $ counterexample $ "\nRead\n" <> pretty txInfoMeta <> " for txId: " <> pretty txInfoId assertWith "Inserted is included in Read" (txMeta == txInfoMeta && txId == txInfoId) prop_getTxAfterPutInvalidTxId :: GenState s => DBLayer IO s ShelleyKey -> WalletId -> GenTxHistory -> (Hash "Tx") -> Property prop_getTxAfterPutInvalidTxId db@DBLayer{..} wid txGen txId' = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = do let txs = unGenTxHistory txGen run $ unsafeRunExceptT $ mapExceptT atomically $ putTxHistory wid txs res <- run $ atomically $ unsafeRunExceptT $ getTx wid txId' assertWith "Irrespective of Inserted, Read is Nothing for invalid tx id" (isNothing res) prop_getTxAfterPutInvalidWalletId :: DBLayer IO s ShelleyKey -> ( WalletId , InitialCheckpoint s , WalletMetadata ) -> GenTxHistory -> WalletId -> Property prop_getTxAfterPutInvalidWalletId db@DBLayer{..} (wid, InitialCheckpoint cp0, meta) txGen wid' = wid /= wid' ==> monadicIO (setup >> prop) where setup = liftIO $ do cleanDB db atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do let txs = unGenTxHistory txGen atomically (runExceptT $ putTxHistory wid txs) `shouldReturn` Right () forM_ txs $ \(Tx {txId}, _) -> do let err = ErrNoSuchWallet wid' atomically (runExceptT $ getTx wid' txId) `shouldReturn` Left err prop_putBeforeInit :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> f a -> DBLayer IO s ShelleyKey -> (WalletId, a) -> Property prop_putBeforeInit putOp readOp empty db (wid, a) = monadicIO (setup >> prop) where setup = liftIO (cleanDB db) prop = liftIO $ do runExceptT (putOp db wid a) >>= \case Right _ -> fail "expected put operation to fail but it succeeded!" Left err -> err `shouldBe` ErrNoSuchWallet wid (ShowFmt <$> readOp db wid) `shouldReturn` (ShowFmt empty) | Modifying one resource leaves the other untouched prop_isolation :: ( Buildable (f b), Eq (f b) , Buildable (g c), Eq (g c) , Buildable (h d), Eq (h d) , GenState s , Show s ) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f b) ^ Read Operation for another resource -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (g c) ^ Read Operation for another resource -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (h d) ^ Read Operation for another resource -> DBLayer IO s ShelleyKey -> (ShowFmt WalletId, ShowFmt a) -> Property prop_isolation putA readB readC readD db@DBLayer{..} (ShowFmt wid, ShowFmt a) = monadicIO (setup >>= prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary (GenTxHistory txs) <- pick arbitrary run $ atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ putTxHistory wid txs run $ (,,) <$> readB db wid <*> readC db wid <*> readD db wid prop (b, c, d) = liftIO $ do unsafeRunExceptT $ putA db wid a (ShowFmt <$> readB db wid) `shouldReturn` ShowFmt b (ShowFmt <$> readC db wid) `shouldReturn` ShowFmt c (ShowFmt <$> readD db wid) `shouldReturn` ShowFmt d prop_readAfterDelete :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> f a -> DBLayer IO s ShelleyKey -> ShowFmt WalletId -> Property prop_readAfterDelete readOp empty db@DBLayer{..} (ShowFmt wid) = monadicIO (setup >> prop) where setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp prop = liftIO $ do atomically $ unsafeRunExceptT $ removeWallet wid (ShowFmt <$> readOp db wid) `shouldReturn` ShowFmt empty | Check that the DB supports multiple sequential puts for a given resource prop_sequentialPut :: (Buildable (f a), Eq (f a), GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> (forall k. Ord k => [(k, a)] -> [f a]) -> DBLayer IO s ShelleyKey -> KeyValPairs (ShowFmt WalletId) (ShowFmt a) -> Property prop_sequentialPut putOp readOp resolve db@DBLayer{..} kv = cover 25 cond "conflicting db entries" $ monadicIO (setup >> prop) where pairs = (\(KeyValPairs xs) -> bimap unShowFmt unShowFmt <$> xs) kv cond = L.length (L.nub ids) /= L.length ids where ids = map fst pairs setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ once_ pairs $ \(k, _) -> initializeWallet k cp0 meta mempty gp prop = do run $ unsafeRunExceptT $ forM_ pairs $ uncurry (putOp db) res <- run $ once pairs (readOp db . fst) let resolved = resolve pairs monitor $ counterexample $ "\nResolved\n" <> pretty resolved monitor $ counterexample $ "\nRead\n" <> pretty res assertWith "Resolved == Read" (res == resolved) | Check that the DB supports multiple sequential puts for a given resource prop_parallelPut :: (GenState s) => ( DBLayer IO s ShelleyKey -> WalletId -> a -> ExceptT ErrNoSuchWallet IO () -> ( DBLayer IO s ShelleyKey -> WalletId -> IO (f a) ^ Read Operation -> (forall k. Ord k => [(k, a)] -> Int) -> DBLayer IO s ShelleyKey -> KeyValPairs WalletId a -> Property prop_parallelPut putOp readOp resolve db@DBLayer{..} (KeyValPairs pairs) = cover 25 cond "conflicting db entries" $ monadicIO (setup >> prop) where cond = L.length (L.nub ids) /= L.length ids where ids = map fst pairs setup = do run $ cleanDB db (InitialCheckpoint cp0, meta) <- pick arbitrary run $ atomically $ unsafeRunExceptT $ once_ pairs $ \(k, _) -> initializeWallet k cp0 meta mempty gp prop = liftIO $ do forConcurrently_ pairs $ unsafeRunExceptT . uncurry (putOp db) res <- once pairs (readOp db . fst) length res `shouldBe` resolve pairs prop_rollbackCheckpoint :: forall s k. (GenState s, Eq s) => DBLayer IO s k -> InitialCheckpoint s -> MockChain -> Property prop_rollbackCheckpoint db@DBLayer{..} (InitialCheckpoint cp0) (MockChain chain) = do monadicIO $ do ShowFmt wid <- namedPick "Wallet ID" arbitrary ShowFmt meta <- namedPick "Wallet Metadata" arbitrary ShowFmt point <- namedPick "Rollback target" (elements $ ShowFmt <$> cps) setup wid meta >> prop wid point where cps :: [Wallet s] cps = flip unfoldr (chain, cp0) $ \case ([], _) -> Nothing (b:q, cp) -> let cp' = snd . snd $ applyBlock b cp in Just (cp', (q, cp')) setup wid meta = run $ do cleanDB db atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ forM_ cps (putCheckpoint wid) prop wid point = do let tip = currentTip point point' <- run $ atomically $ unsafeRunExceptT $ rollbackTo wid (toSlot $ chainPointFromBlockHeader tip) cp <- run $ atomically $ readCheckpoint wid let str = maybe "∅" pretty cp monitor $ counterexample ("Checkpoint after rollback: \n" <> str) assert (ShowFmt cp == ShowFmt (pure point)) assert (ShowFmt point' == ShowFmt (chainPointFromBlockHeader tip)) ( PoR = Point of Rollback ) - There 's no transaction beyond the PoR - Any transaction after the PoR is forgotten from the DBLayer currently does not roll the TxHistory back correctly prop_rollbackTxHistory :: forall s k. () => DBLayer IO s k -> InitialCheckpoint s -> GenTxHistory -> Property prop_rollbackTxHistory db@DBLayer{..} (InitialCheckpoint cp0) (GenTxHistory txs0) = do monadicIO $ do ShowFmt wid <- namedPick "Wallet ID" arbitrary ShowFmt meta <- namedPick "Wallet Metadata" arbitrary ShowFmt slot <- namedPick "Requested Rollback slot" arbitrary let ixs = forgotten slot monitor $ label ("Forgotten tx after point: " <> show (L.length ixs)) monitor $ cover 50 (not $ null ixs) "rolling back something" setup wid meta >> prop wid slot where setup wid meta = run $ do cleanDB db atomically $ do unsafeRunExceptT $ initializeWallet wid cp0 meta mempty gp unsafeRunExceptT $ putTxHistory wid txs0 prop wid requestedPoint = do point <- run $ unsafeRunExceptT $ mapExceptT atomically $ rollbackTo wid (At requestedPoint) txs <- run $ atomically $ fmap toTxHistory <$> readTransactions wid Nothing Descending wholeRange Nothing monitor $ counterexample $ "\n" <> "Actual Rollback Point:\n" <> (pretty point) monitor $ counterexample $ "\nOriginal tx history:\n" <> (txsF txs0) monitor $ counterexample $ "\nNew tx history:\n" <> (txsF txs) let slot = pseudoSlotNo point assertWith "All txs before are still known" $ L.sort (knownAfterRollback slot) == L.sort (txId . fst <$> txs) assertWith "All txs are now before the point of rollback" $ all (isBefore slot . snd) txs where txsF :: [(Tx, TxMeta)] -> String txsF = L.intercalate "\n" . map (\(tx, meta) -> unwords [ "- " , pretty (txId tx) , pretty (meta ^. #slotNo) , pretty (meta ^. #status) , pretty (meta ^. #direction) , pretty (meta ^. #amount) ]) pseudoSlotNo ChainPointAtGenesis = SlotNo 0 pseudoSlotNo (ChainPoint slot _) = slot isBefore :: SlotNo -> TxMeta -> Bool isBefore slot meta = (slotNo :: TxMeta -> SlotNo) meta <= slot forgotten :: SlotNo -> [Hash "Tx"] forgotten slot = let isAfter meta = meta ^. #slotNo > slot in filterTxs isAfter txs0 knownAfterRollback :: SlotNo -> [Hash "Tx"] knownAfterRollback slot = filterTxs (isBefore slot) txs0 gp :: GenesisParameters gp = dummyGenesisParameters
cdad968c6ab3f2194e23fda6dfe34f93e4efc3c5a1eaa5bb629088b0743920c2
disteph/cdsat
hCons.mli
(**********************************************************) (* This file contains the implementation of HConsed types *) (**********************************************************) module type OptionValue = sig type t type index val value: (t,index) Opt.gadt end module BackIndex: OptionValue with type index = Opt.some module NoBackIndex: OptionValue with type index = Opt.none module EmptyData : sig type t val build : int -> 'a -> t end module type PolyS = sig type ('t,'a) initial type ('a,'data) generic type ('a,'data) g_revealed = (('a,'data) generic,'a) initial val reveal : ('a,'data) generic -> ('a,'data) g_revealed val id : ('a,'data) generic -> int val data : ('a,'data) generic -> 'data val compare: ('a,'data) generic -> ('a,'data) generic -> int end module MakePoly(M: sig type ('t,'a) t [@@deriving eq, hash] val name : string end) : sig include PolyS with type ('t,'a) initial = ('t,'a) M.t module InitData(B:OptionValue) (Par: sig type t [@@deriving eq, hash] end) (Data: sig type t val build : int -> (Par.t,t) g_revealed -> t end) : sig type t = (Par.t,Data.t) generic [@@deriving eq,hash] type revealed = (Par.t,Data.t) g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end module Init(B:OptionValue)(Par: sig type t [@@deriving eq, hash] end) : sig type t = (Par.t,unit) generic [@@deriving eq,hash] type revealed = (Par.t,unit) g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end end module type S = sig type 't initial type 'data generic type 'data g_revealed = 'data generic initial val reveal : 'data generic -> 'data g_revealed val id : 'data generic -> int val data : 'data generic -> 'data val compare: 'data generic -> 'data generic -> int end module Make(M: sig type 't t [@@deriving eq, hash] val name : string end) : sig include S with type 't initial = 't M.t module InitData(B:OptionValue) (Data: sig type t val build : int -> t g_revealed -> t end) : sig type t = Data.t generic [@@deriving eq,hash] type revealed = Data.t g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end module Init(B:OptionValue) : sig type t = unit generic [@@deriving eq,hash] type revealed = unit g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end end
null
https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/lib/general.mld/hCons.mli
ocaml
******************************************************** This file contains the implementation of HConsed types ********************************************************
module type OptionValue = sig type t type index val value: (t,index) Opt.gadt end module BackIndex: OptionValue with type index = Opt.some module NoBackIndex: OptionValue with type index = Opt.none module EmptyData : sig type t val build : int -> 'a -> t end module type PolyS = sig type ('t,'a) initial type ('a,'data) generic type ('a,'data) g_revealed = (('a,'data) generic,'a) initial val reveal : ('a,'data) generic -> ('a,'data) g_revealed val id : ('a,'data) generic -> int val data : ('a,'data) generic -> 'data val compare: ('a,'data) generic -> ('a,'data) generic -> int end module MakePoly(M: sig type ('t,'a) t [@@deriving eq, hash] val name : string end) : sig include PolyS with type ('t,'a) initial = ('t,'a) M.t module InitData(B:OptionValue) (Par: sig type t [@@deriving eq, hash] end) (Data: sig type t val build : int -> (Par.t,t) g_revealed -> t end) : sig type t = (Par.t,Data.t) generic [@@deriving eq,hash] type revealed = (Par.t,Data.t) g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end module Init(B:OptionValue)(Par: sig type t [@@deriving eq, hash] end) : sig type t = (Par.t,unit) generic [@@deriving eq,hash] type revealed = (Par.t,unit) g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end end module type S = sig type 't initial type 'data generic type 'data g_revealed = 'data generic initial val reveal : 'data generic -> 'data g_revealed val id : 'data generic -> int val data : 'data generic -> 'data val compare: 'data generic -> 'data generic -> int end module Make(M: sig type 't t [@@deriving eq, hash] val name : string end) : sig include S with type 't initial = 't M.t module InitData(B:OptionValue) (Data: sig type t val build : int -> t g_revealed -> t end) : sig type t = Data.t generic [@@deriving eq,hash] type revealed = Data.t g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end module Init(B:OptionValue) : sig type t = unit generic [@@deriving eq,hash] type revealed = unit g_revealed val build : revealed -> t val clear : unit -> unit val backindex: (int -> t,B.index) Opt.gadt end end
ccd63ab1921f56182c4f240b38c3bf935fb98c9a967a6d7bfb099c8582751a81
MarcosPividori/push-notify
Constants.hs
-- GSoC 2013 - Communicating with mobile devices. {-# LANGUAGE OverloadedStrings #-} -- | This Module define the main constants for sending Push Notifications through Cloud Connection Server (GCM). module Network.PushNotify.Ccs.Constants where import Data.Text cCCS_URL :: Text cCCS_URL = "gcm.googleapis.com" cCCS_PORT :: Integer cCCS_PORT = 5235 cREGISTRATION_IDS :: Text cREGISTRATION_IDS = "registration_ids" cMessageId :: Text cMessageId = "message_id" cTo :: Text cTo = "to" cMessageType :: Text cMessageType = "message_type" cAck :: Text cAck = "ack" cFrom :: Text cFrom = "from" cData :: Text cData = "data" cError :: Text cError = "error" cBadRegistration :: Text cBadRegistration = "BAD_REGISTRATION" cDeviceUnregistered :: Text cDeviceUnregistered = "DEVICE_UNREGISTERED" cInternalServerError :: Text cInternalServerError = "INTERNAL_SERVER_ERROR" cServiceUnAvailable :: Text cServiceUnAvailable = "SERVICE_UNAVAILABLE"
null
https://raw.githubusercontent.com/MarcosPividori/push-notify/4c023c3fd731178d1d114774993a5e337225baa1/push-notify-ccs/Network/PushNotify/Ccs/Constants.hs
haskell
GSoC 2013 - Communicating with mobile devices. # LANGUAGE OverloadedStrings # | This Module define the main constants for sending Push Notifications through Cloud Connection Server (GCM).
module Network.PushNotify.Ccs.Constants where import Data.Text cCCS_URL :: Text cCCS_URL = "gcm.googleapis.com" cCCS_PORT :: Integer cCCS_PORT = 5235 cREGISTRATION_IDS :: Text cREGISTRATION_IDS = "registration_ids" cMessageId :: Text cMessageId = "message_id" cTo :: Text cTo = "to" cMessageType :: Text cMessageType = "message_type" cAck :: Text cAck = "ack" cFrom :: Text cFrom = "from" cData :: Text cData = "data" cError :: Text cError = "error" cBadRegistration :: Text cBadRegistration = "BAD_REGISTRATION" cDeviceUnregistered :: Text cDeviceUnregistered = "DEVICE_UNREGISTERED" cInternalServerError :: Text cInternalServerError = "INTERNAL_SERVER_ERROR" cServiceUnAvailable :: Text cServiceUnAvailable = "SERVICE_UNAVAILABLE"
bb6b2fc56f520ef03d2dcb30317e6ecb4598b372d3a4c0d6f41a780bd84dd5cd
bgusach/exercises-htdp2e
ex-462-to-470.rkt
#lang htdp/isl+ (require test-engine/racket-tests) (require 2htdp/abstraction) An SOE is a non - empty Matrix . constraint for ( list r1 ... rn ) , ( length ri ) is ( + n 1 ) ; interpretation represents a system of linear equations ; An Equation is a [List-of Number]. constraint an Equation contains at least two numbers . ; interpretation if (list a1 ... an b) is an Equation, ; a1, ..., an are the left-hand-side variable coefficients ; and b is the right-hand side ; A Solution is a [List-of Number] an SOE '((2 2 3 10) ; an Equation (2 5 12 31) (4 1 -2 1) )) (define S '(1 1 2)) ; a Solution ; Equation -> [List-of Number] ; extracts the left-hand side from a row in a matrix (check-expect (lhs (first M)) '(2 2 3)) (define (lhs e) (reverse (rest (reverse e))) ) ; Equation -> Number ; extracts the right-hand side from a row in a matrix (check-expect (rhs (first M)) 10) (define (rhs e) (first (reverse e)) ) = = = = = = = = = = = = = = = = = = = = Exercise 462 = = = = = = = = = = = = = = = = = = = = ; [List-of Number] Solution -> Number Returns the result of applying a solution to the LHS ; of an Equation (check-expect (plug-in '(1 4 -1) '(3 0 10)) -7) (define (plug-in lhs sol) (for/sum [(i lhs) (j sol)] (* i j) )) ; SOE Solution -> Boolean Given a SOE and a solution , checks whether the solution satisfies all the equations of the SOE (check-expect (check-solution M S) #t) (check-expect (check-solution M '(1 2 3)) #f) (define (check-solution soe sol) (local ((define (equation-satisfied? eq) (= (plug-in (lhs eq) sol) (rhs eq) ))) ; -- IN -- (andmap equation-satisfied? soe) )) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 463 = = = = = = = = = = = = = = = = = = = = (define SOE-2 '((2 2 3 10) (0 3 9 21) (0 0 1 2) )) (check-expect (check-solution SOE-2 S) #t) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 464 = = = = = = = = = = = = = = = = = = = = (define SOE-3 '((2 2 3 10) (0 3 9 21) (0 -3 -8 -19) )) (check-expect (check-solution SOE-3 S) #t) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 465 = = = = = = = = = = = = = = = = = = = = ; Equation Equation -> Equation Subtracts a multiple of eq-1 from eq-2 , so that the first coefficient of the result is zero . ; Then, the equation is dropped after dropping the leading zero . (check-expect (subtract (first M) (second M)) '(3 9 21)) (check-expect (subtract '(2 4 8 2) '(6 9 21 3)) '(-3 -3 -3)) (define (subtract eq-1 eq-2) (local ((define factor (/ (first eq-2) (first eq-1)))) ; -- IN -- (for/list [(a (rest eq-1)) (b (rest eq-2))] (- b (* a factor)) ))) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 466 = = = = = = = = = = = = = = = = = = = = A TM is an [ NEList - of Equation ] ; such that the Equations are of decreasing length: n + 1 , n , n - 1 , ... , 2 . ; interpretation represents a triangular matrix ; SOE -> TM ; triangulates the given system of equations (check-expect (triangulate M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-error (triangulate '((2 3 3 8) (2 3 -2 3) (4 -2 2 4) ))) (define (triangulate M) (match M [(cons eq '()) M] [(cons head tail) (cons head (triangulate (for/list [(eq tail)] (subtract head eq) )))])) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 467 = = = = = = = = = = = = = = = = = = = = (define SOE-4 '((2 3 3 8) (2 3 -2 3) (4 -2 2 4) )) ; SOE -> TM ; triangulates the given system of equations Termination : as long as the SOE has a solution , the function returns . (check-expect (triangulate.v2 M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-expect (triangulate.v2 SOE-4) '((2 3 3 8) ( -8 -4 -12) ( -5 -5)) ) (define (triangulate.v2 M) (match (rotate-till-non-zero M) [(cons eq '()) M] [(cons head tail) (cons head (triangulate.v2 (for/list [(eq tail)] (subtract head eq) )))])) Check that original SOE and the triangulated one ; are equivalent (check-expect (check-solution SOE-4 '(1 1 1) ) #t ) (check-expect (check-solution (triangulate.v2 SOE-4) '(1 1 1) ) #t ) ; SOE -> SOE Rotates the matrix until one equation starts with non - zero value Termination : function returns if at least one equation starts with non - zero value . Otherwise ¯\_(ツ)_/¯ (check-expect (rotate-till-non-zero '((0 3 4) (5 4 2) )) '((5 4 2) (0 3 4) )) (define (rotate-till-non-zero M) (if (zero? (first (first M))) (rotate-till-non-zero (append (rest M) (cons (first M) '())) ) M )) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 468 = = = = = = = = = = = = = = = = = = = = ; SOE -> TM ; triangulates the given system of equations Termination : as long as the SOE has a solution , the function returns . (check-expect (triangulate.v3 M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-expect (triangulate.v3 SOE-4) '((2 3 3 8) ( -8 -4 -12) ( -5 -5)) ) (check-error (triangulate.v3 '((0 0 0) (0 0))) ) (define (triangulate.v3 M) (match (rotate-till-non-zero.v2 M) [(cons eq '()) M] [(cons head tail) (cons head (triangulate.v3 (for/list [(eq tail)] (subtract head eq) )))])) ; SOE -> SOE Rotates the matrix until one equation starts with non - zero value ; Termination: function returns always. If no equation starts with ; non-zero value, an error is signaled. (check-expect (rotate-till-non-zero.v2 '((0 3 4) (5 4 2) )) '((5 4 2) (0 3 4) )) (define (rotate-till-non-zero.v2 M) (local (; SOE SOE -> SOE (define (rotate acc matrix-rest) (cond [(empty? matrix-rest) (error "No equation start with non-zero") ] [(zero? (first (first matrix-rest))) (rotate (cons (first matrix-rest) acc) (rest matrix-rest) )] [else (cons (first matrix-rest) (append (rest matrix-rest) acc) )]))) ; -- IN -- (rotate '() M) )) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 469 = = = = = = = = = = = = = = = = = = = = (define TM '((2 2 3 10) ( 3 9 21) ( 1 2) )) (define TM-SOL '(1 1 2) ) TM - > Solution ; Given a triangular matrix, returns a solution (check-expect (solve TM) TM-SOL) (define (solve M) (local ((define (reduce eq sol) (local ((define eq-lhs (lhs eq)) (define first-coeff (first eq-lhs)) (define eq-rhs (rhs eq)) (define partial (plug-in (rest eq-lhs) sol)) ) ; -- IN -- (cons (/ (- eq-rhs partial) first-coeff) sol )))) ; -- IN -- (foldr reduce '() M) )) ; =================== End of exercise ================== = = = = = = = = = = = = = = = = = = = = Exercise 470 = = = = = = = = = = = = = = = = = = = = ; SOE -> Solution Resolves a SOE (check-expect (gauss M) S) (define (gauss M) (solve (triangulate M)) ) ; =================== End of exercise ================== (test)
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/5-generative-recursion/ex-462-to-470.rkt
racket
interpretation represents a system of linear equations An Equation is a [List-of Number]. interpretation if (list a1 ... an b) is an Equation, a1, ..., an are the left-hand-side variable coefficients and b is the right-hand side A Solution is a [List-of Number] an Equation a Solution Equation -> [List-of Number] extracts the left-hand side from a row in a matrix Equation -> Number extracts the right-hand side from a row in a matrix [List-of Number] Solution -> Number of an Equation SOE Solution -> Boolean -- IN -- =================== End of exercise ================== =================== End of exercise ================== =================== End of exercise ================== Equation Equation -> Equation Then, the equation is dropped after dropping the leading -- IN -- =================== End of exercise ================== such that the Equations are of decreasing length: interpretation represents a triangular matrix SOE -> TM triangulates the given system of equations =================== End of exercise ================== SOE -> TM triangulates the given system of equations are equivalent SOE -> SOE =================== End of exercise ================== SOE -> TM triangulates the given system of equations SOE -> SOE Termination: function returns always. If no equation starts with non-zero value, an error is signaled. SOE SOE -> SOE -- IN -- =================== End of exercise ================== Given a triangular matrix, returns a solution -- IN -- -- IN -- =================== End of exercise ================== SOE -> Solution =================== End of exercise ==================
#lang htdp/isl+ (require test-engine/racket-tests) (require 2htdp/abstraction) An SOE is a non - empty Matrix . constraint for ( list r1 ... rn ) , ( length ri ) is ( + n 1 ) constraint an Equation contains at least two numbers . an SOE (2 5 12 31) (4 1 -2 1) )) (check-expect (lhs (first M)) '(2 2 3)) (define (lhs e) (reverse (rest (reverse e))) ) (check-expect (rhs (first M)) 10) (define (rhs e) (first (reverse e)) ) = = = = = = = = = = = = = = = = = = = = Exercise 462 = = = = = = = = = = = = = = = = = = = = Returns the result of applying a solution to the LHS (check-expect (plug-in '(1 4 -1) '(3 0 10)) -7) (define (plug-in lhs sol) (for/sum [(i lhs) (j sol)] (* i j) )) Given a SOE and a solution , checks whether the solution satisfies all the equations of the SOE (check-expect (check-solution M S) #t) (check-expect (check-solution M '(1 2 3)) #f) (define (check-solution soe sol) (local ((define (equation-satisfied? eq) (= (plug-in (lhs eq) sol) (rhs eq) ))) (andmap equation-satisfied? soe) )) = = = = = = = = = = = = = = = = = = = = Exercise 463 = = = = = = = = = = = = = = = = = = = = (define SOE-2 '((2 2 3 10) (0 3 9 21) (0 0 1 2) )) (check-expect (check-solution SOE-2 S) #t) = = = = = = = = = = = = = = = = = = = = Exercise 464 = = = = = = = = = = = = = = = = = = = = (define SOE-3 '((2 2 3 10) (0 3 9 21) (0 -3 -8 -19) )) (check-expect (check-solution SOE-3 S) #t) = = = = = = = = = = = = = = = = = = = = Exercise 465 = = = = = = = = = = = = = = = = = = = = Subtracts a multiple of eq-1 from eq-2 , so that the first coefficient of the result is zero . zero . (check-expect (subtract (first M) (second M)) '(3 9 21)) (check-expect (subtract '(2 4 8 2) '(6 9 21 3)) '(-3 -3 -3)) (define (subtract eq-1 eq-2) (local ((define factor (/ (first eq-2) (first eq-1)))) (for/list [(a (rest eq-1)) (b (rest eq-2))] (- b (* a factor)) ))) = = = = = = = = = = = = = = = = = = = = Exercise 466 = = = = = = = = = = = = = = = = = = = = A TM is an [ NEList - of Equation ] n + 1 , n , n - 1 , ... , 2 . (check-expect (triangulate M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-error (triangulate '((2 3 3 8) (2 3 -2 3) (4 -2 2 4) ))) (define (triangulate M) (match M [(cons eq '()) M] [(cons head tail) (cons head (triangulate (for/list [(eq tail)] (subtract head eq) )))])) = = = = = = = = = = = = = = = = = = = = Exercise 467 = = = = = = = = = = = = = = = = = = = = (define SOE-4 '((2 3 3 8) (2 3 -2 3) (4 -2 2 4) )) Termination : as long as the SOE has a solution , the function returns . (check-expect (triangulate.v2 M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-expect (triangulate.v2 SOE-4) '((2 3 3 8) ( -8 -4 -12) ( -5 -5)) ) (define (triangulate.v2 M) (match (rotate-till-non-zero M) [(cons eq '()) M] [(cons head tail) (cons head (triangulate.v2 (for/list [(eq tail)] (subtract head eq) )))])) Check that original SOE and the triangulated one (check-expect (check-solution SOE-4 '(1 1 1) ) #t ) (check-expect (check-solution (triangulate.v2 SOE-4) '(1 1 1) ) #t ) Rotates the matrix until one equation starts with non - zero value Termination : function returns if at least one equation starts with non - zero value . Otherwise ¯\_(ツ)_/¯ (check-expect (rotate-till-non-zero '((0 3 4) (5 4 2) )) '((5 4 2) (0 3 4) )) (define (rotate-till-non-zero M) (if (zero? (first (first M))) (rotate-till-non-zero (append (rest M) (cons (first M) '())) ) M )) = = = = = = = = = = = = = = = = = = = = Exercise 468 = = = = = = = = = = = = = = = = = = = = Termination : as long as the SOE has a solution , the function returns . (check-expect (triangulate.v3 M) '((2 2 3 10) ( 3 9 21) ( 1 2) )) (check-expect (triangulate.v3 SOE-4) '((2 3 3 8) ( -8 -4 -12) ( -5 -5)) ) (check-error (triangulate.v3 '((0 0 0) (0 0))) ) (define (triangulate.v3 M) (match (rotate-till-non-zero.v2 M) [(cons eq '()) M] [(cons head tail) (cons head (triangulate.v3 (for/list [(eq tail)] (subtract head eq) )))])) Rotates the matrix until one equation starts with non - zero value (check-expect (rotate-till-non-zero.v2 '((0 3 4) (5 4 2) )) '((5 4 2) (0 3 4) )) (define (rotate-till-non-zero.v2 M) (local (define (rotate acc matrix-rest) (cond [(empty? matrix-rest) (error "No equation start with non-zero") ] [(zero? (first (first matrix-rest))) (rotate (cons (first matrix-rest) acc) (rest matrix-rest) )] [else (cons (first matrix-rest) (append (rest matrix-rest) acc) )]))) (rotate '() M) )) = = = = = = = = = = = = = = = = = = = = Exercise 469 = = = = = = = = = = = = = = = = = = = = (define TM '((2 2 3 10) ( 3 9 21) ( 1 2) )) (define TM-SOL '(1 1 2) ) TM - > Solution (check-expect (solve TM) TM-SOL) (define (solve M) (local ((define (reduce eq sol) (local ((define eq-lhs (lhs eq)) (define first-coeff (first eq-lhs)) (define eq-rhs (rhs eq)) (define partial (plug-in (rest eq-lhs) sol)) ) (cons (/ (- eq-rhs partial) first-coeff) sol )))) (foldr reduce '() M) )) = = = = = = = = = = = = = = = = = = = = Exercise 470 = = = = = = = = = = = = = = = = = = = = Resolves a SOE (check-expect (gauss M) S) (define (gauss M) (solve (triangulate M)) ) (test)
35035d530d0f9419ae90dbc53b2df3b137934d22f482a3edaf1b4f1ca3091e7a
tautologico/progfun
metacirc.rkt
#lang racket ;; --- ambiente com valores das variáveis ------------------ (define env '()) o valor de um símbolo no ambiente , existir (define (symbol-value fn) (define val (assoc fn env)) (if val (second val) (error (format "Nome nao definido: ~a" fn)))) avalia uma expressão condicional ( if ) (define (eval-if args) (define cnd (eval (first args))) (define etrue (second args)) (define efalse (third args)) (cond [(not (boolean? cnd)) (error (format "Expressão nao booleana em if: ~a" (first args)))] [cnd (eval etrue)] [else (eval efalse)])) avalia uma definição ( define ) (define (eval-define args) (define name (first args)) (define val (eval (second args))) (set! env (cons (list name val) env))) avalia uma expressão de função anônima ( lambda ) (define (eval-lambda args) (define params (first args)) (define body (second args)) (list 'fun params body)) verifica se um valor é uma função (define (funcao? v) (and (list? v) (not (empty? v)) (eq? (first v) 'fun))) (define (cria-assoc-params pnames pvals) (cond [(empty? pnames) '()] [else (cons (list (first pnames) (first pvals)) (cria-assoc-params (rest pnames) (rest pvals)))])) aplica a função f aos argumentos args (define (apply-fun f args) (define param-names (second f)) (define body (third f)) (eval-temp-env (cria-assoc-params param-names args) body)) verifica se um valor é uma primitiva ( função ) (define (prim? f) (and (list? f) (not (empty? f)) (eq? (first f) 'prim))) ;; aplica a primitiva f aos argumentos args (define (apply-prim f args) (define fval (second f)) (apply fval args)) avalia uma aplicação de função ou primitiva ( identificada fname ) ;; aos argumentos args (define (eval-fun fname args) (define fval (symbol-value fname)) (cond [(funcao? fval) (apply-fun fval (map eval args))] [(prim? fval) (apply-prim fval (map eval args))] [else (error (format "Valor nao funcional em posicao de funcao: ~a" fval))])) avalia uma lista (define (eval-list lst) (define prim (first lst)) (define args (rest lst)) (cond [(symbol? prim) (cond [(eq? prim 'if) (eval-if args)] [(eq? prim 'define) (eval-define args)] [(eq? prim 'lambda) (eval-lambda args)] [else (eval-fun prim args)])] [(or (number? prim) (boolean? prim)) (error (format "Nao é uma funcao: ~a" prim))] [(list? prim) (error "*** nao implementado")] [else (error (format "Expressao nao reconhecida em posicao de funcao: ~a" prim))])) ;; avalia a expressão exp de acordo com o ambiente (global) env (define (eval exp) (cond [(number? exp) exp] [(boolean? exp) exp] [(symbol? exp) (symbol-value exp)] [(list? exp) (eval-list exp)] [else (error (format "Expressao de tipo nao reconhecido: ~a" exp))])) ;; eval - temp - env avalia a expressão exp em um ambiente ( environment ) . A função salva o ambiente ( environment ) atual , adiciona as variaveis em newvars ao ambiente , avalia a expressão exp no novo ambiente , restaura o ambiente anterior , e o valor a expressão exp . Isso é usado ( o ambiente local ) e ;; em testes. ;; (define (eval-temp-env newvars exp) (define old-env env) (set! env (append newvars env)) (define val (eval exp)) (set! env old-env) val) ;; --- primitivas do interpretador ------------------------- adiciona uma primitiva de nome nome , que executa a função em Racket dada pela função fun . Ver exemplos abaixo (define (adiciona-primitiva nome fun) (set! env (cons (list nome (list 'prim fun)) env))) --- primitivas aritméticas ------------------------- a expressão a seguir adiciona a adição como primitiva do interpretador . o nome da primitiva é dada ( veja que usamos o quote antes do ) , e a função da primitiva é a função + da linguagem Racket (adiciona-primitiva '+ +) da mesma forma podemos adicionar multiplicação (adiciona-primitiva '* *) a função que implementa a primitiva não precisa em Racket : podemos usar qualquer função válida . como exemplo , vamos adicionar uma primitiva para multiplicar um por 2 . o nome da primitiva é " * 2 " , e a função ligada a que multiplica o por 2 : (adiciona-primitiva '*2 (lambda (x) (* x 2))) dessa forma , ( eval ' ( * 2 7 ) ) tem valor 14 ( veja no REPL ou no teste abaixo ) ;; --- testes ---------------------------------------------- (module+ test (require rackunit rackunit/text-ui) (define-test-suite test-eval (test-equal? "constante inteira" (eval 2) 2) (test-equal? "constante de ponto flutuante" (eval 3.14) 3.14) (test-equal? "booleano #t" (eval #t) #t) (test-equal? "booleano #f" (eval #f) #f) (test-equal? "primitiva +" (eval '(+ 2 3)) 5) (test-equal? "primitiva *" (eval '(* 2 3)) 6) (test-equal? "referência a uma variável" (eval-temp-env '((x 2)) '(+ x 7)) 9) (test-equal? "referência a uma variável com valor de função" (eval-temp-env '((f (fun (n) (* n 7)))) '(f (+ 3 2))) 35) (test-equal? "primitiva *2" (eval '(*2 7)) 14)) (run-tests test-eval))
null
https://raw.githubusercontent.com/tautologico/progfun/0e8b2985e48445d289fa96f27c2485710c356709/codigo/metacirc.rkt
racket
--- ambiente com valores das variáveis ------------------ aplica a primitiva f aos argumentos args aos argumentos args avalia a expressão exp de acordo com o ambiente (global) env em testes. --- primitivas do interpretador ------------------------- --- testes ----------------------------------------------
#lang racket (define env '()) o valor de um símbolo no ambiente , existir (define (symbol-value fn) (define val (assoc fn env)) (if val (second val) (error (format "Nome nao definido: ~a" fn)))) avalia uma expressão condicional ( if ) (define (eval-if args) (define cnd (eval (first args))) (define etrue (second args)) (define efalse (third args)) (cond [(not (boolean? cnd)) (error (format "Expressão nao booleana em if: ~a" (first args)))] [cnd (eval etrue)] [else (eval efalse)])) avalia uma definição ( define ) (define (eval-define args) (define name (first args)) (define val (eval (second args))) (set! env (cons (list name val) env))) avalia uma expressão de função anônima ( lambda ) (define (eval-lambda args) (define params (first args)) (define body (second args)) (list 'fun params body)) verifica se um valor é uma função (define (funcao? v) (and (list? v) (not (empty? v)) (eq? (first v) 'fun))) (define (cria-assoc-params pnames pvals) (cond [(empty? pnames) '()] [else (cons (list (first pnames) (first pvals)) (cria-assoc-params (rest pnames) (rest pvals)))])) aplica a função f aos argumentos args (define (apply-fun f args) (define param-names (second f)) (define body (third f)) (eval-temp-env (cria-assoc-params param-names args) body)) verifica se um valor é uma primitiva ( função ) (define (prim? f) (and (list? f) (not (empty? f)) (eq? (first f) 'prim))) (define (apply-prim f args) (define fval (second f)) (apply fval args)) avalia uma aplicação de função ou primitiva ( identificada fname ) (define (eval-fun fname args) (define fval (symbol-value fname)) (cond [(funcao? fval) (apply-fun fval (map eval args))] [(prim? fval) (apply-prim fval (map eval args))] [else (error (format "Valor nao funcional em posicao de funcao: ~a" fval))])) avalia uma lista (define (eval-list lst) (define prim (first lst)) (define args (rest lst)) (cond [(symbol? prim) (cond [(eq? prim 'if) (eval-if args)] [(eq? prim 'define) (eval-define args)] [(eq? prim 'lambda) (eval-lambda args)] [else (eval-fun prim args)])] [(or (number? prim) (boolean? prim)) (error (format "Nao é uma funcao: ~a" prim))] [(list? prim) (error "*** nao implementado")] [else (error (format "Expressao nao reconhecida em posicao de funcao: ~a" prim))])) (define (eval exp) (cond [(number? exp) exp] [(boolean? exp) exp] [(symbol? exp) (symbol-value exp)] [(list? exp) (eval-list exp)] [else (error (format "Expressao de tipo nao reconhecido: ~a" exp))])) eval - temp - env avalia a expressão exp em um ambiente ( environment ) . A função salva o ambiente ( environment ) atual , adiciona as variaveis em newvars ao ambiente , avalia a expressão exp no novo ambiente , restaura o ambiente anterior , e o valor a expressão exp . Isso é usado ( o ambiente local ) e (define (eval-temp-env newvars exp) (define old-env env) (set! env (append newvars env)) (define val (eval exp)) (set! env old-env) val) adiciona uma primitiva de nome nome , que executa a função em Racket dada pela função fun . Ver exemplos abaixo (define (adiciona-primitiva nome fun) (set! env (cons (list nome (list 'prim fun)) env))) --- primitivas aritméticas ------------------------- a expressão a seguir adiciona a adição como primitiva do interpretador . o nome da primitiva é dada ( veja que usamos o quote antes do ) , e a função da primitiva é a função + da linguagem Racket (adiciona-primitiva '+ +) da mesma forma podemos adicionar multiplicação (adiciona-primitiva '* *) a função que implementa a primitiva não precisa em Racket : podemos usar qualquer função válida . como exemplo , vamos adicionar uma primitiva para multiplicar um por 2 . o nome da primitiva é " * 2 " , e a função ligada a que multiplica o por 2 : (adiciona-primitiva '*2 (lambda (x) (* x 2))) dessa forma , ( eval ' ( * 2 7 ) ) tem valor 14 ( veja no REPL ou no teste abaixo ) (module+ test (require rackunit rackunit/text-ui) (define-test-suite test-eval (test-equal? "constante inteira" (eval 2) 2) (test-equal? "constante de ponto flutuante" (eval 3.14) 3.14) (test-equal? "booleano #t" (eval #t) #t) (test-equal? "booleano #f" (eval #f) #f) (test-equal? "primitiva +" (eval '(+ 2 3)) 5) (test-equal? "primitiva *" (eval '(* 2 3)) 6) (test-equal? "referência a uma variável" (eval-temp-env '((x 2)) '(+ x 7)) 9) (test-equal? "referência a uma variável com valor de função" (eval-temp-env '((f (fun (n) (* n 7)))) '(f (+ 3 2))) 35) (test-equal? "primitiva *2" (eval '(*2 7)) 14)) (run-tests test-eval))
b214f23d26545bc74256f4c73f151202d0e92ed18031f9ace4820b197fd99f64
LeventErkok/sbv
Kind.hs
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.Core.Kind Copyright : ( c ) -- License : BSD3 -- Maintainer: -- Stability : experimental -- Internal data - structures for the sbv library ----------------------------------------------------------------------------- {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -Wall -Werror -fno - warn - orphans # module Data.SBV.Core.Kind ( Kind(..), HasKind(..), constructUKind, smtType, hasUninterpretedSorts , BVIsNonZero, ValidFloat, intOfProxy , showBaseKind, needsFlattening, RoundingMode(..), smtRoundingMode ) where import qualified Data.Generics as G (Data(..), DataType, dataTypeName, dataTypeOf, tyconUQname, dataTypeConstrs, constrFields) import Data.Char (isSpace) import Data.Int import Data.Word import Data.SBV.Core.AlgReals import Data.Proxy import Data.Kind import Data.List (isPrefixOf, intercalate) import Data.Typeable (Typeable) import Data.Type.Bool import Data.Type.Equality import GHC.TypeLits import Data.SBV.Utils.Lib (isKString) -- | Kind of symbolic value data Kind = KBool | KBounded !Bool !Int | KUnbounded | KReal name . Uninterpreted , or enumeration constants . | KFloat | KDouble | KFP !Int !Int | KChar | KString | KList Kind | KSet Kind | KTuple [Kind] | KMaybe Kind | KRational | KEither Kind Kind deriving (Eq, Ord, G.Data) | The interesting about the show instance is that it can tell apart two kinds nicely ; since it conveniently ignores the enumeration constructors . Also , when we construct a ' KUserSort ' , we make sure we do n't use any of -- the reserved names; see 'constructUKind' for details. instance Show Kind where show KBool = "SBool" show (KBounded False n) = pickType n "SWord" "SWord " ++ show n show (KBounded True n) = pickType n "SInt" "SInt " ++ show n show KUnbounded = "SInteger" show KReal = "SReal" show (KUserSort s _) = s show KFloat = "SFloat" show KDouble = "SDouble" show (KFP eb sb) = "SFloatingPoint " ++ show eb ++ " " ++ show sb show KString = "SString" show KChar = "SChar" show (KList e) = "[" ++ show e ++ "]" show (KSet e) = "{" ++ show e ++ "}" show (KTuple m) = "(" ++ intercalate ", " (show <$> m) ++ ")" show (KMaybe k) = "SMaybe " ++ kindParen (showBaseKind k) show (KEither k1 k2) = "SEither " ++ kindParen (showBaseKind k1) ++ " " ++ kindParen (showBaseKind k2) show KRational = "SRational" | A version of show for kinds that says instead of SBool showBaseKind :: Kind -> String showBaseKind = sh where sh k@KBool = noS (show k) sh (KBounded False n) = pickType n "Word" "WordN " ++ show n sh (KBounded True n) = pickType n "Int" "IntN " ++ show n sh k@KUnbounded = noS (show k) sh k@KReal = noS (show k) sh k@KUserSort{} = show k -- Leave user-sorts untouched! sh k@KFloat = noS (show k) sh k@KDouble = noS (show k) sh k@KFP{} = noS (show k) sh k@KChar = noS (show k) sh k@KString = noS (show k) sh KRational = "Rational" sh (KList k) = "[" ++ sh k ++ "]" sh (KSet k) = "{" ++ sh k ++ "}" sh (KTuple ks) = "(" ++ intercalate ", " (map sh ks) ++ ")" sh (KMaybe k) = "Maybe " ++ kindParen (sh k) sh (KEither k1 k2) = "Either " ++ kindParen (sh k1) ++ " " ++ kindParen (sh k2) -- Drop the initial S if it's there noS ('S':s) = s noS s = s For historical reasons , we show 8 - 16 - 32 - 64 bit values with no space ; others with a space . pickType :: Int -> String -> String -> String pickType i standard other | i `elem` [8, 16, 32, 64] = standard | True = other -- | Put parens if necessary. This test is rather crummy, but seems to work ok kindParen :: String -> String kindParen s@('[':_) = s kindParen s@('(':_) = s kindParen s | any isSpace s = '(' : s ++ ")" | True = s | How the type maps to SMT land smtType :: Kind -> String smtType KBool = "Bool" smtType (KBounded _ sz) = "(_ BitVec " ++ show sz ++ ")" smtType KUnbounded = "Int" smtType KReal = "Real" smtType KFloat = "(_ FloatingPoint 8 24)" smtType KDouble = "(_ FloatingPoint 11 53)" smtType (KFP eb sb) = "(_ FloatingPoint " ++ show eb ++ " " ++ show sb ++ ")" smtType KString = "String" smtType KChar = "String" smtType (KList k) = "(Seq " ++ smtType k ++ ")" smtType (KSet k) = "(Array " ++ smtType k ++ " Bool)" smtType (KUserSort s _) = s smtType (KTuple []) = "SBVTuple0" smtType (KTuple kinds) = "(SBVTuple" ++ show (length kinds) ++ " " ++ unwords (smtType <$> kinds) ++ ")" smtType KRational = "SBVRational" smtType (KMaybe k) = "(SBVMaybe " ++ smtType k ++ ")" smtType (KEither k1 k2) = "(SBVEither " ++ smtType k1 ++ " " ++ smtType k2 ++ ")" instance Eq G.DataType where a == b = G.tyconUQname (G.dataTypeName a) == G.tyconUQname (G.dataTypeName b) instance Ord G.DataType where a `compare` b = G.tyconUQname (G.dataTypeName a) `compare` G.tyconUQname (G.dataTypeName b) -- | Does this kind represent a signed quantity? kindHasSign :: Kind -> Bool kindHasSign = \case KBool -> False KBounded b _ -> b KUnbounded -> True KReal -> True KFloat -> True KDouble -> True KFP{} -> True KRational -> True KUserSort{} -> False KString -> False KChar -> False KList{} -> False KSet{} -> False KTuple{} -> False KMaybe{} -> False KEither{} -> False -- | Construct an uninterpreted/enumerated kind from a piece of data; we distinguish simple enumerations as those are mapped to proper SMT - Lib2 data - types ; while others go completely uninterpreted constructUKind :: forall a. (Read a, G.Data a) => a -> Kind constructUKind a | any (`isPrefixOf` sortName) badPrefixes = error $ unlines [ "*** Data.SBV: Cannot construct user-sort with name: " ++ show sortName , "***" , "*** Must not start with any of: " ++ intercalate ", " badPrefixes ] | True = case (constrs, concatMap G.constrFields constrs) of ([], _) -> KUserSort sortName Nothing (cs, []) -> KUserSort sortName $ Just (map show cs) _ -> error $ unlines [ "*** Data.SBV: " ++ sortName ++ " is not an enumeration." , "***" , "*** To declare an enumeration, constructors should not have any fields." , "*** To declare an uninterpreted sort, use a datatype with no constructors." ] where -- make sure we don't step on ourselves: NB . The sort " RoundingMode " is special . It 's treated by SBV as a user - defined -- sort, even though it's internally handled differently. So, that name doesn't appear -- below. badPrefixes = [ "SBool", "SWord", "SInt", "SInteger", "SReal", "SFloat", "SDouble" , "SString", "SChar", "[", "SSet", "STuple", "SMaybe", "SEither" , "SRational" ] dataType = G.dataTypeOf a sortName = G.tyconUQname . G.dataTypeName $ dataType constrs = G.dataTypeConstrs dataType -- | A class for capturing values that have a sign and a size (finite or infinite) minimal complete definition : , unless you can take advantage of the default -- signature: This class can be automatically derived for data-types that have -- a 'G.Data' instance; this is useful for creating uninterpreted sorts. So, in -- reality, end users should almost never need to define any methods. class HasKind a where kindOf :: a -> Kind hasSign :: a -> Bool intSizeOf :: a -> Int isBoolean :: a -> Bool NB . This really means word / int ; i.e. , Real / Float will test False isReal :: a -> Bool isFloat :: a -> Bool isDouble :: a -> Bool isRational :: a -> Bool isFP :: a -> Bool isUnbounded :: a -> Bool isUserSort :: a -> Bool isChar :: a -> Bool isString :: a -> Bool isList :: a -> Bool isSet :: a -> Bool isTuple :: a -> Bool isMaybe :: a -> Bool isEither :: a -> Bool showType :: a -> String -- defaults hasSign x = kindHasSign (kindOf x) intSizeOf x = case kindOf x of KBool -> error "SBV.HasKind.intSizeOf((S)Bool)" KBounded _ s -> s KUnbounded -> error "SBV.HasKind.intSizeOf((S)Integer)" KReal -> error "SBV.HasKind.intSizeOf((S)Real)" KFloat -> 32 KDouble -> 64 KFP i j -> i + j KRational -> error "SBV.HasKind.intSizeOf((S)Rational)" KUserSort s _ -> error $ "SBV.HasKind.intSizeOf: Uninterpreted sort: " ++ s KString -> error "SBV.HasKind.intSizeOf((S)Double)" KChar -> error "SBV.HasKind.intSizeOf((S)Char)" KList ek -> error $ "SBV.HasKind.intSizeOf((S)List)" ++ show ek KSet ek -> error $ "SBV.HasKind.intSizeOf((S)Set)" ++ show ek KTuple tys -> error $ "SBV.HasKind.intSizeOf((S)Tuple)" ++ show tys KMaybe k -> error $ "SBV.HasKind.intSizeOf((S)Maybe)" ++ show k KEither k1 k2 -> error $ "SBV.HasKind.intSizeOf((S)Either)" ++ show (k1, k2) isBoolean (kindOf -> KBool{}) = True isBoolean _ = False isBounded (kindOf -> KBounded{}) = True isBounded _ = False isReal (kindOf -> KReal{}) = True isReal _ = False isFloat (kindOf -> KFloat{}) = True isFloat _ = False isDouble (kindOf -> KDouble{}) = True isDouble _ = False isFP (kindOf -> KFP{}) = True isFP _ = False isRational (kindOf -> KRational{}) = True isRational _ = False isUnbounded (kindOf -> KUnbounded{}) = True isUnbounded _ = False isUserSort (kindOf -> KUserSort{}) = True isUserSort _ = False isChar (kindOf -> KChar{}) = True isChar _ = False isString (kindOf -> KString{}) = True isString _ = False isList (kindOf -> KList{}) = True isList _ = False isSet (kindOf -> KSet{}) = True isSet _ = False isTuple (kindOf -> KTuple{}) = True isTuple _ = False isMaybe (kindOf -> KMaybe{}) = True isMaybe _ = False isEither (kindOf -> KEither{}) = True isEither _ = False showType = show . kindOf -- default signature for uninterpreted/enumerated kinds default kindOf :: (Read a, G.Data a) => a -> Kind kindOf = constructUKind -- | This instance allows us to use the `kindOf (Proxy @a)` idiom instead of the ` kindOf ( undefined : : a ) ` , which is safer and looks more idiomatic . instance HasKind a => HasKind (Proxy a) where kindOf _ = kindOf (undefined :: a) instance HasKind Bool where kindOf _ = KBool instance HasKind Int8 where kindOf _ = KBounded True 8 instance HasKind Word8 where kindOf _ = KBounded False 8 instance HasKind Int16 where kindOf _ = KBounded True 16 instance HasKind Word16 where kindOf _ = KBounded False 16 instance HasKind Int32 where kindOf _ = KBounded True 32 instance HasKind Word32 where kindOf _ = KBounded False 32 instance HasKind Int64 where kindOf _ = KBounded True 64 instance HasKind Word64 where kindOf _ = KBounded False 64 instance HasKind Integer where kindOf _ = KUnbounded instance HasKind AlgReal where kindOf _ = KReal instance HasKind Rational where kindOf _ = KRational instance HasKind Float where kindOf _ = KFloat instance HasKind Double where kindOf _ = KDouble instance HasKind Char where kindOf _ = KChar | Grab the bit - size from the proxy . If the nat is too large to fit in an int , -- we throw an error. (This would mean too big of a bit-size, that we can't -- really deal with in any practical realm.) In fact, even the range allowed by this conversion ( i.e. , the entire range of a 64 - bit int ) is just impractical , -- but it's hard to come up with a better bound. intOfProxy :: KnownNat n => Proxy n -> Int intOfProxy p | iv == fromIntegral r = r | True = error $ unlines [ "Data.SBV: Too large bit-vector size: " ++ show iv , "" , "No reasonable proof can be performed with such large bit vectors involved," , "So, cowardly refusing to proceed any further! Please file this as a" , "feature request." ] where iv :: Integer iv = natVal p r :: Int r = fromEnum iv -- | Do we have a completely uninterpreted sort lying around anywhere? hasUninterpretedSorts :: Kind -> Bool hasUninterpretedSorts KBool = False hasUninterpretedSorts KBounded{} = False hasUninterpretedSorts KUnbounded = False hasUninterpretedSorts KReal = False hasUninterpretedSorts (KUserSort _ (Just _)) = False -- These are the enumerated sorts, and they are perfectly fine hasUninterpretedSorts (KUserSort _ Nothing) = True -- These are the completely uninterpreted sorts, which we are looking for here hasUninterpretedSorts KFloat = False hasUninterpretedSorts KDouble = False hasUninterpretedSorts KFP{} = False hasUninterpretedSorts KRational = False hasUninterpretedSorts KChar = False hasUninterpretedSorts KString = False hasUninterpretedSorts (KList k) = hasUninterpretedSorts k hasUninterpretedSorts (KSet k) = hasUninterpretedSorts k hasUninterpretedSorts (KTuple ks) = any hasUninterpretedSorts ks hasUninterpretedSorts (KMaybe k) = hasUninterpretedSorts k hasUninterpretedSorts (KEither k1 k2) = any hasUninterpretedSorts [k1, k2] instance (Typeable a, HasKind a) => HasKind [a] where kindOf x | isKString @[a] x = KString | True = KList (kindOf (Proxy @a)) instance HasKind Kind where kindOf = id instance HasKind () where kindOf _ = KTuple [] instance (HasKind a, HasKind b) => HasKind (a, b) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b)] instance (HasKind a, HasKind b, HasKind c) => HasKind (a, b, c) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c)] instance (HasKind a, HasKind b, HasKind c, HasKind d) => HasKind (a, b, c, d) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e) => HasKind (a, b, c, d, e) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f) => HasKind (a, b, c, d, e, f) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f, HasKind g) => HasKind (a, b, c, d, e, f, g) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f), kindOf (Proxy @g)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f, HasKind g, HasKind h) => HasKind (a, b, c, d, e, f, g, h) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f), kindOf (Proxy @g), kindOf (Proxy @h)] instance (HasKind a, HasKind b) => HasKind (Either a b) where kindOf _ = KEither (kindOf (Proxy @a)) (kindOf (Proxy @b)) instance HasKind a => HasKind (Maybe a) where kindOf _ = KMaybe (kindOf (Proxy @a)) | Should we ask the solver to flatten the output ? This comes in handy so output is -- Essentially, we're being conservative here and simply requesting flattening anything that has -- some structure to it. needsFlattening :: Kind -> Bool needsFlattening KBool = False needsFlattening KBounded{} = False needsFlattening KUnbounded = False needsFlattening KReal = False needsFlattening KUserSort{} = False needsFlattening KFloat = False needsFlattening KDouble = False needsFlattening KFP{} = False needsFlattening KRational = False needsFlattening KChar = False needsFlattening KString = False needsFlattening KList{} = True needsFlattening KSet{} = True needsFlattening KTuple{} = True needsFlattening KMaybe{} = True needsFlattening KEither{} = True -- | Catch 0-width cases type BVZeroWidth = 'Text "Zero-width bit-vectors are not allowed." | Type family to create the appropriate non - zero constraint type family BVIsNonZero (arg :: Nat) :: Constraint where BVIsNonZero 0 = TypeError BVZeroWidth BVIsNonZero _ = () #include "MachDeps.h" -- Allowed sizes for floats, imposed by LibBF. -- NB . In LibBF bindings ( and itself as well ) , minimum number of exponent bits is specified as 3 . But this seems unnecessarily restrictive ; that constant does n't seem to be used anywhere , and furthermore my tests with sb = 2 did n't reveal anything going wrong . I emailed the author of regarding this , and he said : -- I had no clear reason to use BF_EXP_BITS_MIN = 3 . So if " 2 " is OK then -- why not. The important is that the basic operations are OK. It is likely -- there are tricky cases in the transcendental operations but even with -- large exponents libbf may have problems with them ! -- So , in SBV , we allow sb = = 2 . If this proves problematic , change the number below in definition of FP_MIN_EB to 3 ! -- NB . It would be nice if we could use the LibBF constants expBitsMin , expBitsMax , precBitsMin , precBitsMax -- for determining the valid range. Unfortunately this doesn't seem to be possible. -- See <-a-type-constraint-based-on-runtime-value-of-maxbound-int> for a discussion. So , we use CPP to work - around that . #define FP_MIN_EB 2 #define FP_MIN_SB 2 #if WORD_SIZE_IN_BITS == 64 #define FP_MAX_EB 61 #define FP_MAX_SB 4611686018427387902 #else #define FP_MAX_EB 29 #define FP_MAX_SB 1073741822 #endif | Catch an invalid FP . type InvalidFloat (eb :: Nat) (sb :: Nat) = 'Text "Invalid floating point type `SFloatingPoint " ':<>: 'ShowType eb ':<>: 'Text " " ':<>: 'ShowType sb ':<>: 'Text "'" ':$$: 'Text "" ':$$: 'Text "A valid float of type 'SFloatingPoint eb sb' must satisfy:" ':$$: 'Text " eb `elem` [" ':<>: 'ShowType FP_MIN_EB ':<>: 'Text " .. " ':<>: 'ShowType FP_MAX_EB ':<>: 'Text "]" ':$$: 'Text " sb `elem` [" ':<>: 'ShowType FP_MIN_SB ':<>: 'Text " .. " ':<>: 'ShowType FP_MAX_SB ':<>: 'Text "]" ':$$: 'Text "" ':$$: 'Text "Given type falls outside of this range, or the sizes are not known naturals." -- | A valid float has restrictions on eb/sb values. NB . In the below encoding , I found that CPP is very finicky about substitution of the machine - dependent -- macros. If you try to put the conditionals in the same line, it fails to substitute for some reason. Hence the awkward spacing. Filed this as a bug report for CPPHS at < > . type family ValidFloat (eb :: Nat) (sb :: Nat) :: Constraint where ValidFloat (eb :: Nat) (sb :: Nat) = ( KnownNat eb , KnownNat sb , If ( ( eb `CmpNat` FP_MIN_EB == 'EQ || eb `CmpNat` FP_MIN_EB == 'GT) && ( eb `CmpNat` FP_MAX_EB == 'EQ || eb `CmpNat` FP_MAX_EB == 'LT) && ( sb `CmpNat` FP_MIN_SB == 'EQ || sb `CmpNat` FP_MIN_SB == 'GT) && ( sb `CmpNat` FP_MAX_SB == 'EQ || sb `CmpNat` FP_MAX_SB == 'LT)) (() :: Constraint) (TypeError (InvalidFloat eb sb)) ) | Rounding mode to be used for the IEEE floating - point operations . Note that 's default is ' ' . If you use -- a different rounding mode, then the counter-examples you get may not match what you observe in Haskell . data RoundingMode = RoundNearestTiesToEven -- ^ Round to nearest representable floating point value. If precisely at half - way , pick the even number . ( In this context , /even/ means the lowest - order bit is zero . ) | RoundNearestTiesToAway -- ^ Round to nearest representable floating point value. If precisely at half - way , pick the number further away from 0 . -- (That is, for positive values, pick the greater; for negative values, pick the smaller.) | RoundTowardPositive -- ^ Round towards positive infinity. (Also known as rounding-up or ceiling.) | RoundTowardNegative -- ^ Round towards negative infinity. (Also known as rounding-down or floor.) ^ Round towards zero . ( Also known as truncation . ) deriving (Eq, Ord, Show, Read, G.Data, Bounded, Enum) | ' RoundingMode ' kind instance HasKind RoundingMode | Convert a rounding mode to the format SMT - Lib2 understands . smtRoundingMode :: RoundingMode -> String smtRoundingMode RoundNearestTiesToEven = "roundNearestTiesToEven" smtRoundingMode RoundNearestTiesToAway = "roundNearestTiesToAway" smtRoundingMode RoundTowardPositive = "roundTowardPositive" smtRoundingMode RoundTowardNegative = "roundTowardNegative" smtRoundingMode RoundTowardZero = "roundTowardZero"
null
https://raw.githubusercontent.com/LeventErkok/sbv/c5c02c5e245a8ac3b568836d6c4e6010aaefe42f/Data/SBV/Core/Kind.hs
haskell
--------------------------------------------------------------------------- | Module : Data.SBV.Core.Kind License : BSD3 Maintainer: Stability : experimental --------------------------------------------------------------------------- # LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE DeriveDataTypeable # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # | Kind of symbolic value the reserved names; see 'constructUKind' for details. Leave user-sorts untouched! Drop the initial S if it's there | Put parens if necessary. This test is rather crummy, but seems to work ok | Does this kind represent a signed quantity? | Construct an uninterpreted/enumerated kind from a piece of data; we distinguish simple enumerations as those make sure we don't step on ourselves: sort, even though it's internally handled differently. So, that name doesn't appear below. | A class for capturing values that have a sign and a size (finite or infinite) signature: This class can be automatically derived for data-types that have a 'G.Data' instance; this is useful for creating uninterpreted sorts. So, in reality, end users should almost never need to define any methods. defaults default signature for uninterpreted/enumerated kinds | This instance allows us to use the `kindOf (Proxy @a)` idiom instead of we throw an error. (This would mean too big of a bit-size, that we can't really deal with in any practical realm.) In fact, even the range allowed but it's hard to come up with a better bound. | Do we have a completely uninterpreted sort lying around anywhere? These are the enumerated sorts, and they are perfectly fine These are the completely uninterpreted sorts, which we are looking for here Essentially, we're being conservative here and simply requesting flattening anything that has some structure to it. | Catch 0-width cases Allowed sizes for floats, imposed by LibBF. why not. The important is that the basic operations are OK. It is likely there are tricky cases in the transcendental operations but even with large exponents libbf may have problems with them ! for determining the valid range. Unfortunately this doesn't seem to be possible. See <-a-type-constraint-based-on-runtime-value-of-maxbound-int> for a discussion. | A valid float has restrictions on eb/sb values. macros. If you try to put the conditionals in the same line, it fails to substitute for some reason. Hence the awkward spacing. a different rounding mode, then the counter-examples you get may not ^ Round to nearest representable floating point value. ^ Round to nearest representable floating point value. (That is, for positive values, pick the greater; for negative values, pick the smaller.) ^ Round towards positive infinity. (Also known as rounding-up or ceiling.) ^ Round towards negative infinity. (Also known as rounding-down or floor.)
Copyright : ( c ) Internal data - structures for the sbv library # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -Wall -Werror -fno - warn - orphans # module Data.SBV.Core.Kind ( Kind(..), HasKind(..), constructUKind, smtType, hasUninterpretedSorts , BVIsNonZero, ValidFloat, intOfProxy , showBaseKind, needsFlattening, RoundingMode(..), smtRoundingMode ) where import qualified Data.Generics as G (Data(..), DataType, dataTypeName, dataTypeOf, tyconUQname, dataTypeConstrs, constrFields) import Data.Char (isSpace) import Data.Int import Data.Word import Data.SBV.Core.AlgReals import Data.Proxy import Data.Kind import Data.List (isPrefixOf, intercalate) import Data.Typeable (Typeable) import Data.Type.Bool import Data.Type.Equality import GHC.TypeLits import Data.SBV.Utils.Lib (isKString) data Kind = KBool | KBounded !Bool !Int | KUnbounded | KReal name . Uninterpreted , or enumeration constants . | KFloat | KDouble | KFP !Int !Int | KChar | KString | KList Kind | KSet Kind | KTuple [Kind] | KMaybe Kind | KRational | KEither Kind Kind deriving (Eq, Ord, G.Data) | The interesting about the show instance is that it can tell apart two kinds nicely ; since it conveniently ignores the enumeration constructors . Also , when we construct a ' KUserSort ' , we make sure we do n't use any of instance Show Kind where show KBool = "SBool" show (KBounded False n) = pickType n "SWord" "SWord " ++ show n show (KBounded True n) = pickType n "SInt" "SInt " ++ show n show KUnbounded = "SInteger" show KReal = "SReal" show (KUserSort s _) = s show KFloat = "SFloat" show KDouble = "SDouble" show (KFP eb sb) = "SFloatingPoint " ++ show eb ++ " " ++ show sb show KString = "SString" show KChar = "SChar" show (KList e) = "[" ++ show e ++ "]" show (KSet e) = "{" ++ show e ++ "}" show (KTuple m) = "(" ++ intercalate ", " (show <$> m) ++ ")" show (KMaybe k) = "SMaybe " ++ kindParen (showBaseKind k) show (KEither k1 k2) = "SEither " ++ kindParen (showBaseKind k1) ++ " " ++ kindParen (showBaseKind k2) show KRational = "SRational" | A version of show for kinds that says instead of SBool showBaseKind :: Kind -> String showBaseKind = sh where sh k@KBool = noS (show k) sh (KBounded False n) = pickType n "Word" "WordN " ++ show n sh (KBounded True n) = pickType n "Int" "IntN " ++ show n sh k@KUnbounded = noS (show k) sh k@KReal = noS (show k) sh k@KFloat = noS (show k) sh k@KDouble = noS (show k) sh k@KFP{} = noS (show k) sh k@KChar = noS (show k) sh k@KString = noS (show k) sh KRational = "Rational" sh (KList k) = "[" ++ sh k ++ "]" sh (KSet k) = "{" ++ sh k ++ "}" sh (KTuple ks) = "(" ++ intercalate ", " (map sh ks) ++ ")" sh (KMaybe k) = "Maybe " ++ kindParen (sh k) sh (KEither k1 k2) = "Either " ++ kindParen (sh k1) ++ " " ++ kindParen (sh k2) noS ('S':s) = s noS s = s For historical reasons , we show 8 - 16 - 32 - 64 bit values with no space ; others with a space . pickType :: Int -> String -> String -> String pickType i standard other | i `elem` [8, 16, 32, 64] = standard | True = other kindParen :: String -> String kindParen s@('[':_) = s kindParen s@('(':_) = s kindParen s | any isSpace s = '(' : s ++ ")" | True = s | How the type maps to SMT land smtType :: Kind -> String smtType KBool = "Bool" smtType (KBounded _ sz) = "(_ BitVec " ++ show sz ++ ")" smtType KUnbounded = "Int" smtType KReal = "Real" smtType KFloat = "(_ FloatingPoint 8 24)" smtType KDouble = "(_ FloatingPoint 11 53)" smtType (KFP eb sb) = "(_ FloatingPoint " ++ show eb ++ " " ++ show sb ++ ")" smtType KString = "String" smtType KChar = "String" smtType (KList k) = "(Seq " ++ smtType k ++ ")" smtType (KSet k) = "(Array " ++ smtType k ++ " Bool)" smtType (KUserSort s _) = s smtType (KTuple []) = "SBVTuple0" smtType (KTuple kinds) = "(SBVTuple" ++ show (length kinds) ++ " " ++ unwords (smtType <$> kinds) ++ ")" smtType KRational = "SBVRational" smtType (KMaybe k) = "(SBVMaybe " ++ smtType k ++ ")" smtType (KEither k1 k2) = "(SBVEither " ++ smtType k1 ++ " " ++ smtType k2 ++ ")" instance Eq G.DataType where a == b = G.tyconUQname (G.dataTypeName a) == G.tyconUQname (G.dataTypeName b) instance Ord G.DataType where a `compare` b = G.tyconUQname (G.dataTypeName a) `compare` G.tyconUQname (G.dataTypeName b) kindHasSign :: Kind -> Bool kindHasSign = \case KBool -> False KBounded b _ -> b KUnbounded -> True KReal -> True KFloat -> True KDouble -> True KFP{} -> True KRational -> True KUserSort{} -> False KString -> False KChar -> False KList{} -> False KSet{} -> False KTuple{} -> False KMaybe{} -> False KEither{} -> False are mapped to proper SMT - Lib2 data - types ; while others go completely uninterpreted constructUKind :: forall a. (Read a, G.Data a) => a -> Kind constructUKind a | any (`isPrefixOf` sortName) badPrefixes = error $ unlines [ "*** Data.SBV: Cannot construct user-sort with name: " ++ show sortName , "***" , "*** Must not start with any of: " ++ intercalate ", " badPrefixes ] | True = case (constrs, concatMap G.constrFields constrs) of ([], _) -> KUserSort sortName Nothing (cs, []) -> KUserSort sortName $ Just (map show cs) _ -> error $ unlines [ "*** Data.SBV: " ++ sortName ++ " is not an enumeration." , "***" , "*** To declare an enumeration, constructors should not have any fields." , "*** To declare an uninterpreted sort, use a datatype with no constructors." ] NB . The sort " RoundingMode " is special . It 's treated by SBV as a user - defined badPrefixes = [ "SBool", "SWord", "SInt", "SInteger", "SReal", "SFloat", "SDouble" , "SString", "SChar", "[", "SSet", "STuple", "SMaybe", "SEither" , "SRational" ] dataType = G.dataTypeOf a sortName = G.tyconUQname . G.dataTypeName $ dataType constrs = G.dataTypeConstrs dataType minimal complete definition : , unless you can take advantage of the default class HasKind a where kindOf :: a -> Kind hasSign :: a -> Bool intSizeOf :: a -> Int isBoolean :: a -> Bool NB . This really means word / int ; i.e. , Real / Float will test False isReal :: a -> Bool isFloat :: a -> Bool isDouble :: a -> Bool isRational :: a -> Bool isFP :: a -> Bool isUnbounded :: a -> Bool isUserSort :: a -> Bool isChar :: a -> Bool isString :: a -> Bool isList :: a -> Bool isSet :: a -> Bool isTuple :: a -> Bool isMaybe :: a -> Bool isEither :: a -> Bool showType :: a -> String hasSign x = kindHasSign (kindOf x) intSizeOf x = case kindOf x of KBool -> error "SBV.HasKind.intSizeOf((S)Bool)" KBounded _ s -> s KUnbounded -> error "SBV.HasKind.intSizeOf((S)Integer)" KReal -> error "SBV.HasKind.intSizeOf((S)Real)" KFloat -> 32 KDouble -> 64 KFP i j -> i + j KRational -> error "SBV.HasKind.intSizeOf((S)Rational)" KUserSort s _ -> error $ "SBV.HasKind.intSizeOf: Uninterpreted sort: " ++ s KString -> error "SBV.HasKind.intSizeOf((S)Double)" KChar -> error "SBV.HasKind.intSizeOf((S)Char)" KList ek -> error $ "SBV.HasKind.intSizeOf((S)List)" ++ show ek KSet ek -> error $ "SBV.HasKind.intSizeOf((S)Set)" ++ show ek KTuple tys -> error $ "SBV.HasKind.intSizeOf((S)Tuple)" ++ show tys KMaybe k -> error $ "SBV.HasKind.intSizeOf((S)Maybe)" ++ show k KEither k1 k2 -> error $ "SBV.HasKind.intSizeOf((S)Either)" ++ show (k1, k2) isBoolean (kindOf -> KBool{}) = True isBoolean _ = False isBounded (kindOf -> KBounded{}) = True isBounded _ = False isReal (kindOf -> KReal{}) = True isReal _ = False isFloat (kindOf -> KFloat{}) = True isFloat _ = False isDouble (kindOf -> KDouble{}) = True isDouble _ = False isFP (kindOf -> KFP{}) = True isFP _ = False isRational (kindOf -> KRational{}) = True isRational _ = False isUnbounded (kindOf -> KUnbounded{}) = True isUnbounded _ = False isUserSort (kindOf -> KUserSort{}) = True isUserSort _ = False isChar (kindOf -> KChar{}) = True isChar _ = False isString (kindOf -> KString{}) = True isString _ = False isList (kindOf -> KList{}) = True isList _ = False isSet (kindOf -> KSet{}) = True isSet _ = False isTuple (kindOf -> KTuple{}) = True isTuple _ = False isMaybe (kindOf -> KMaybe{}) = True isMaybe _ = False isEither (kindOf -> KEither{}) = True isEither _ = False showType = show . kindOf default kindOf :: (Read a, G.Data a) => a -> Kind kindOf = constructUKind the ` kindOf ( undefined : : a ) ` , which is safer and looks more idiomatic . instance HasKind a => HasKind (Proxy a) where kindOf _ = kindOf (undefined :: a) instance HasKind Bool where kindOf _ = KBool instance HasKind Int8 where kindOf _ = KBounded True 8 instance HasKind Word8 where kindOf _ = KBounded False 8 instance HasKind Int16 where kindOf _ = KBounded True 16 instance HasKind Word16 where kindOf _ = KBounded False 16 instance HasKind Int32 where kindOf _ = KBounded True 32 instance HasKind Word32 where kindOf _ = KBounded False 32 instance HasKind Int64 where kindOf _ = KBounded True 64 instance HasKind Word64 where kindOf _ = KBounded False 64 instance HasKind Integer where kindOf _ = KUnbounded instance HasKind AlgReal where kindOf _ = KReal instance HasKind Rational where kindOf _ = KRational instance HasKind Float where kindOf _ = KFloat instance HasKind Double where kindOf _ = KDouble instance HasKind Char where kindOf _ = KChar | Grab the bit - size from the proxy . If the nat is too large to fit in an int , by this conversion ( i.e. , the entire range of a 64 - bit int ) is just impractical , intOfProxy :: KnownNat n => Proxy n -> Int intOfProxy p | iv == fromIntegral r = r | True = error $ unlines [ "Data.SBV: Too large bit-vector size: " ++ show iv , "" , "No reasonable proof can be performed with such large bit vectors involved," , "So, cowardly refusing to proceed any further! Please file this as a" , "feature request." ] where iv :: Integer iv = natVal p r :: Int r = fromEnum iv hasUninterpretedSorts :: Kind -> Bool hasUninterpretedSorts KBool = False hasUninterpretedSorts KBounded{} = False hasUninterpretedSorts KUnbounded = False hasUninterpretedSorts KReal = False hasUninterpretedSorts KFloat = False hasUninterpretedSorts KDouble = False hasUninterpretedSorts KFP{} = False hasUninterpretedSorts KRational = False hasUninterpretedSorts KChar = False hasUninterpretedSorts KString = False hasUninterpretedSorts (KList k) = hasUninterpretedSorts k hasUninterpretedSorts (KSet k) = hasUninterpretedSorts k hasUninterpretedSorts (KTuple ks) = any hasUninterpretedSorts ks hasUninterpretedSorts (KMaybe k) = hasUninterpretedSorts k hasUninterpretedSorts (KEither k1 k2) = any hasUninterpretedSorts [k1, k2] instance (Typeable a, HasKind a) => HasKind [a] where kindOf x | isKString @[a] x = KString | True = KList (kindOf (Proxy @a)) instance HasKind Kind where kindOf = id instance HasKind () where kindOf _ = KTuple [] instance (HasKind a, HasKind b) => HasKind (a, b) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b)] instance (HasKind a, HasKind b, HasKind c) => HasKind (a, b, c) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c)] instance (HasKind a, HasKind b, HasKind c, HasKind d) => HasKind (a, b, c, d) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e) => HasKind (a, b, c, d, e) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f) => HasKind (a, b, c, d, e, f) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f, HasKind g) => HasKind (a, b, c, d, e, f, g) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f), kindOf (Proxy @g)] instance (HasKind a, HasKind b, HasKind c, HasKind d, HasKind e, HasKind f, HasKind g, HasKind h) => HasKind (a, b, c, d, e, f, g, h) where kindOf _ = KTuple [kindOf (Proxy @a), kindOf (Proxy @b), kindOf (Proxy @c), kindOf (Proxy @d), kindOf (Proxy @e), kindOf (Proxy @f), kindOf (Proxy @g), kindOf (Proxy @h)] instance (HasKind a, HasKind b) => HasKind (Either a b) where kindOf _ = KEither (kindOf (Proxy @a)) (kindOf (Proxy @b)) instance HasKind a => HasKind (Maybe a) where kindOf _ = KMaybe (kindOf (Proxy @a)) | Should we ask the solver to flatten the output ? This comes in handy so output is needsFlattening :: Kind -> Bool needsFlattening KBool = False needsFlattening KBounded{} = False needsFlattening KUnbounded = False needsFlattening KReal = False needsFlattening KUserSort{} = False needsFlattening KFloat = False needsFlattening KDouble = False needsFlattening KFP{} = False needsFlattening KRational = False needsFlattening KChar = False needsFlattening KString = False needsFlattening KList{} = True needsFlattening KSet{} = True needsFlattening KTuple{} = True needsFlattening KMaybe{} = True needsFlattening KEither{} = True type BVZeroWidth = 'Text "Zero-width bit-vectors are not allowed." | Type family to create the appropriate non - zero constraint type family BVIsNonZero (arg :: Nat) :: Constraint where BVIsNonZero 0 = TypeError BVZeroWidth BVIsNonZero _ = () #include "MachDeps.h" NB . In LibBF bindings ( and itself as well ) , minimum number of exponent bits is specified as 3 . But this seems unnecessarily restrictive ; that constant does n't seem to be used anywhere , and furthermore my tests with sb = 2 did n't reveal anything going wrong . I emailed the author of regarding this , and he said : I had no clear reason to use BF_EXP_BITS_MIN = 3 . So if " 2 " is OK then So , in SBV , we allow sb = = 2 . If this proves problematic , change the number below in definition of FP_MIN_EB to 3 ! NB . It would be nice if we could use the LibBF constants expBitsMin , expBitsMax , precBitsMin , precBitsMax So , we use CPP to work - around that . #define FP_MIN_EB 2 #define FP_MIN_SB 2 #if WORD_SIZE_IN_BITS == 64 #define FP_MAX_EB 61 #define FP_MAX_SB 4611686018427387902 #else #define FP_MAX_EB 29 #define FP_MAX_SB 1073741822 #endif | Catch an invalid FP . type InvalidFloat (eb :: Nat) (sb :: Nat) = 'Text "Invalid floating point type `SFloatingPoint " ':<>: 'ShowType eb ':<>: 'Text " " ':<>: 'ShowType sb ':<>: 'Text "'" ':$$: 'Text "" ':$$: 'Text "A valid float of type 'SFloatingPoint eb sb' must satisfy:" ':$$: 'Text " eb `elem` [" ':<>: 'ShowType FP_MIN_EB ':<>: 'Text " .. " ':<>: 'ShowType FP_MAX_EB ':<>: 'Text "]" ':$$: 'Text " sb `elem` [" ':<>: 'ShowType FP_MIN_SB ':<>: 'Text " .. " ':<>: 'ShowType FP_MAX_SB ':<>: 'Text "]" ':$$: 'Text "" ':$$: 'Text "Given type falls outside of this range, or the sizes are not known naturals." NB . In the below encoding , I found that CPP is very finicky about substitution of the machine - dependent Filed this as a bug report for CPPHS at < > . type family ValidFloat (eb :: Nat) (sb :: Nat) :: Constraint where ValidFloat (eb :: Nat) (sb :: Nat) = ( KnownNat eb , KnownNat sb , If ( ( eb `CmpNat` FP_MIN_EB == 'EQ || eb `CmpNat` FP_MIN_EB == 'GT) && ( eb `CmpNat` FP_MAX_EB == 'EQ || eb `CmpNat` FP_MAX_EB == 'LT) && ( sb `CmpNat` FP_MIN_SB == 'EQ || sb `CmpNat` FP_MIN_SB == 'GT) && ( sb `CmpNat` FP_MAX_SB == 'EQ || sb `CmpNat` FP_MAX_SB == 'LT)) (() :: Constraint) (TypeError (InvalidFloat eb sb)) ) | Rounding mode to be used for the IEEE floating - point operations . Note that 's default is ' ' . If you use match what you observe in Haskell . If precisely at half - way , pick the even number . ( In this context , /even/ means the lowest - order bit is zero . ) If precisely at half - way , pick the number further away from 0 . ^ Round towards zero . ( Also known as truncation . ) deriving (Eq, Ord, Show, Read, G.Data, Bounded, Enum) | ' RoundingMode ' kind instance HasKind RoundingMode | Convert a rounding mode to the format SMT - Lib2 understands . smtRoundingMode :: RoundingMode -> String smtRoundingMode RoundNearestTiesToEven = "roundNearestTiesToEven" smtRoundingMode RoundNearestTiesToAway = "roundNearestTiesToAway" smtRoundingMode RoundTowardPositive = "roundTowardPositive" smtRoundingMode RoundTowardNegative = "roundTowardNegative" smtRoundingMode RoundTowardZero = "roundTowardZero"
5da6da32506467ddb7dd57e938c616e18d9506ef6b475ebcaf4f6bb5c35045f2
Commonfare-net/macao-social-wallet
confirm_transaction_form.clj
Freecoin - digital social currency toolkit part of Decentralized Citizen Engagement Technologies ( D - CENT ) R&D funded by the European Commission ( FP7 / CAPS 610349 ) Copyright ( C ) 2015 Dyne.org foundation Copyright ( C ) 2015 Thoughtworks , Inc. designed , written and maintained by < > ;; With contributions by < > < > < > ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see </>. (ns freecoin.handlers.confirm-transaction-form (:require [liberator.core :as lc] [liberator.representation :as lr] [ring.util.response :as r] [freecoin-lib.db.wallet :as wallet] [freecoin-lib.db.confirmation :as confirmation] [freecoin-lib.core :as blockchain] [freecoin.context-helpers :as ch] [freecoin.routes :as routes] [freecoin-lib.config :as config] [freecoin.views :as fv] [freecoin.auth :as auth] [freecoin.form_helpers :as fh] [freecoin.views.confirm-transaction-form :as confirm-transaction-form])) (lc/defresource get-confirm-transaction-form [wallet-store confirmation-store] :allowed-methods [:get] :available-media-types ["text/html"] :authorized? #(auth/is-signed-in %) :exists? (fn [ctx] (let [confirmation-uid (:confirmation-uid (ch/context->params ctx)) signed-in-email (:email ctx)] (when-let [confirmation (confirmation/fetch confirmation-store confirmation-uid)] (when (= signed-in-email (get-in confirmation [:data :sender-email])) {::confirmation confirmation})))) :handle-ok (fn [ctx] (let [confirmation (::confirmation ctx) recipient (wallet/fetch wallet-store (get-in ctx [::confirmation :data :recipient-email])) show-pin-entry (= nil (ch/context->cookie-data ctx))] (-> {:confirmation confirmation :recipient recipient :request (:request ctx)} (confirm-transaction-form/build show-pin-entry) fv/render-page)))) (defn preserve-session [response {:keys [session]}] (assoc response :session session)) (lc/defresource post-confirm-transaction-form [wallet-store confirmation-store blockchain] :allowed-methods [:post] :available-media-types ["text/html"] ;; TODO: fix use of authorized and exists here conforming to auth functions ;; when we tried last moving below to exists? (and lower handlers to not-found) ;; did trigger several errors in tests and even some compiling errors. :authorized? (fn [ctx] (let [signed-in-email (ch/context->signed-in-email ctx) sender-wallet (wallet/fetch wallet-store signed-in-email) confirmation-uid (:confirmation-uid (ch/context->params ctx)) confirmation (confirmation/fetch confirmation-store confirmation-uid)] (when (and sender-wallet confirmation (= signed-in-email (-> confirmation :data :sender-email))) {::confirmation confirmation ::sender-wallet sender-wallet}))) :allowed? (fn [ctx] (let [confirmation (::confirmation ctx) {:keys [status data problems]} (fh/validate-form (confirm-transaction-form/confirm-transaction-form-spec (:uid confirmation) true) (ch/context->params ctx))] (if (= :ok status) {} [false (fh/form-problem problems)]))) :post! (fn [ctx] (let [{:keys [sender-email recipient-email amount tags]} (-> ctx ::confirmation :data) sender-wallet (wallet/fetch wallet-store sender-email) recipient-wallet (wallet/fetch wallet-store recipient-email)] (blockchain/create-transaction blockchain (:email sender-wallet) amount (:email recipient-wallet) {:tags tags}) (confirmation/delete! confirmation-store (-> ctx ::confirmation :uid)) {::email (:email sender-wallet)})) :post-redirect? (fn [ctx] {:location (routes/absolute-path :account :email (::email ctx))}) :handle-see-other (fn [ctx] (-> (:location ctx) r/redirect (preserve-session (:request ctx)) lr/ring-response)) :handle-forbidden (fn [ctx] (-> (routes/absolute-path :get-confirm-transaction-form :confirmation-uid (-> ctx ::confirmation :uid)) r/redirect (fh/flash-form-problem ctx) lr/ring-response)))
null
https://raw.githubusercontent.com/Commonfare-net/macao-social-wallet/d3724d6c706cdaa669c59da439fe48b0373e17b7/src/freecoin/handlers/confirm_transaction_form.clj
clojure
With contributions by This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. along with this program. If not, see </>. TODO: fix use of authorized and exists here conforming to auth functions when we tried last moving below to exists? (and lower handlers to not-found) did trigger several errors in tests and even some compiling errors.
Freecoin - digital social currency toolkit part of Decentralized Citizen Engagement Technologies ( D - CENT ) R&D funded by the European Commission ( FP7 / CAPS 610349 ) Copyright ( C ) 2015 Dyne.org foundation Copyright ( C ) 2015 Thoughtworks , Inc. designed , written and maintained by < > < > < > < > it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Affero General Public License (ns freecoin.handlers.confirm-transaction-form (:require [liberator.core :as lc] [liberator.representation :as lr] [ring.util.response :as r] [freecoin-lib.db.wallet :as wallet] [freecoin-lib.db.confirmation :as confirmation] [freecoin-lib.core :as blockchain] [freecoin.context-helpers :as ch] [freecoin.routes :as routes] [freecoin-lib.config :as config] [freecoin.views :as fv] [freecoin.auth :as auth] [freecoin.form_helpers :as fh] [freecoin.views.confirm-transaction-form :as confirm-transaction-form])) (lc/defresource get-confirm-transaction-form [wallet-store confirmation-store] :allowed-methods [:get] :available-media-types ["text/html"] :authorized? #(auth/is-signed-in %) :exists? (fn [ctx] (let [confirmation-uid (:confirmation-uid (ch/context->params ctx)) signed-in-email (:email ctx)] (when-let [confirmation (confirmation/fetch confirmation-store confirmation-uid)] (when (= signed-in-email (get-in confirmation [:data :sender-email])) {::confirmation confirmation})))) :handle-ok (fn [ctx] (let [confirmation (::confirmation ctx) recipient (wallet/fetch wallet-store (get-in ctx [::confirmation :data :recipient-email])) show-pin-entry (= nil (ch/context->cookie-data ctx))] (-> {:confirmation confirmation :recipient recipient :request (:request ctx)} (confirm-transaction-form/build show-pin-entry) fv/render-page)))) (defn preserve-session [response {:keys [session]}] (assoc response :session session)) (lc/defresource post-confirm-transaction-form [wallet-store confirmation-store blockchain] :allowed-methods [:post] :available-media-types ["text/html"] :authorized? (fn [ctx] (let [signed-in-email (ch/context->signed-in-email ctx) sender-wallet (wallet/fetch wallet-store signed-in-email) confirmation-uid (:confirmation-uid (ch/context->params ctx)) confirmation (confirmation/fetch confirmation-store confirmation-uid)] (when (and sender-wallet confirmation (= signed-in-email (-> confirmation :data :sender-email))) {::confirmation confirmation ::sender-wallet sender-wallet}))) :allowed? (fn [ctx] (let [confirmation (::confirmation ctx) {:keys [status data problems]} (fh/validate-form (confirm-transaction-form/confirm-transaction-form-spec (:uid confirmation) true) (ch/context->params ctx))] (if (= :ok status) {} [false (fh/form-problem problems)]))) :post! (fn [ctx] (let [{:keys [sender-email recipient-email amount tags]} (-> ctx ::confirmation :data) sender-wallet (wallet/fetch wallet-store sender-email) recipient-wallet (wallet/fetch wallet-store recipient-email)] (blockchain/create-transaction blockchain (:email sender-wallet) amount (:email recipient-wallet) {:tags tags}) (confirmation/delete! confirmation-store (-> ctx ::confirmation :uid)) {::email (:email sender-wallet)})) :post-redirect? (fn [ctx] {:location (routes/absolute-path :account :email (::email ctx))}) :handle-see-other (fn [ctx] (-> (:location ctx) r/redirect (preserve-session (:request ctx)) lr/ring-response)) :handle-forbidden (fn [ctx] (-> (routes/absolute-path :get-confirm-transaction-form :confirmation-uid (-> ctx ::confirmation :uid)) r/redirect (fh/flash-form-problem ctx) lr/ring-response)))
bb6b1629f0db95160fa2ab9d2e648ea4e5b5f6880f460d50600c0fb7a9e49de6
8c6794b6/guile-tjit
array.scm
ECMAScript for Copyright ( C ) 2009 , 2010 Free Software Foundation , Inc. ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA ;;; Code: (define-module (language ecmascript array) #:use-module (oop goops) #:use-module (language ecmascript base) #:use-module (language ecmascript function) #:export (*array-prototype* new-array)) (define-class <js-array-object> (<js-object>) (vector #:init-value #() #:accessor js-array-vector #:init-keyword #:vector)) (define (new-array . vals) (let ((o (make <js-array-object> #:class "Array" #:prototype *array-prototype*))) (pput o 'length (length vals)) (let ((vect (js-array-vector o))) (let lp ((i 0) (vals vals)) (cond ((not (null? vals)) (vector-set! vect i (car vals)) (lp (1+ i) (cdr vals))) (else o)))))) (define *array-prototype* (make <js-object> #:class "Array" #:value new-array #:constructor new-array)) (hashq-set! *program-wrappers* new-array *array-prototype*) (pput *array-prototype* 'prototype *array-prototype*) (pput *array-prototype* 'constructor new-array) (define-method (pget (o <js-array-object>) p) (cond ((and (integer? p) (exact? p) (>= p 0)) (let ((v (js-array-vector o))) (if (< p (vector-length v)) (vector-ref v p) (next-method)))) ((or (and (symbol? p) (eq? p 'length)) (and (string? p) (string=? p "length"))) (vector-length (js-array-vector o))) (else (next-method)))) (define-method (pput (o <js-array-object>) p v) (cond ((and (integer? p) (exact? p) (>= 0 p)) (let ((vect (js-array-vector o))) (if (< p (vector-length vect)) (vector-set! vect p v) : round up to powers of 2 ? (let ((new (make-vector (1+ p) 0))) (vector-move-left! vect 0 (vector-length vect) new 0) (set! (js-array-vector o) new) (vector-set! new p v))))) ((or (and (symbol? p) (eq? p 'length)) (and (string? p) (string=? p "length"))) (let ((vect (js-array-vector o))) (let ((new (make-vector (->uint32 v) 0))) (vector-move-left! vect 0 (min (vector-length vect) (->uint32 v)) new 0) (set! (js-array-vector o) new)))) (else (next-method)))) (define-js-method *array-prototype* (toString) (format #f "~A" (js-array-vector this))) (define-js-method *array-prototype* (concat . rest) (let* ((len (apply + (->uint32 (pget this 'length)) (map (lambda (x) (->uint32 (pget x 'length))) rest))) (rv (make-vector len 0))) (let lp ((objs (cons this rest)) (i 0)) (cond ((null? objs) (make <js-array-object> #:class "Array" #:prototype *array-prototype* #:vector rv)) ((is-a? (car objs) <js-array-object>) (let ((v (js-array-vector (car objs)))) (vector-move-left! v 0 (vector-length v) rv i) (lp (cdr objs) (+ i (vector-length v))))) (else (error "generic array concats not yet implemented")))))) (define-js-method *array-prototype* (join . separator) (let lp ((i (1- (->uint32 (pget this 'length)))) (l '())) (if (< i 0) (string-join l (if separator (->string (car separator)) ",")) (lp (1+ i) (cons (->string (pget this i)) l))))) (define-js-method *array-prototype* (pop) (let ((len (->uint32 (pget this 'length)))) (if (zero? len) *undefined* (let ((ret (pget this (1- len)))) (pput this 'length (1- len)) ret)))) (define-js-method *array-prototype* (push . args) (let lp ((args args)) (if (null? args) (->uint32 (pget this 'length)) (begin (pput this (->uint32 (pget this 'length)) (car args)) (lp (cdr args))))))
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/language/ecmascript/array.scm
scheme
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software Code:
ECMAScript for Copyright ( C ) 2009 , 2010 Free Software Foundation , Inc. version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (define-module (language ecmascript array) #:use-module (oop goops) #:use-module (language ecmascript base) #:use-module (language ecmascript function) #:export (*array-prototype* new-array)) (define-class <js-array-object> (<js-object>) (vector #:init-value #() #:accessor js-array-vector #:init-keyword #:vector)) (define (new-array . vals) (let ((o (make <js-array-object> #:class "Array" #:prototype *array-prototype*))) (pput o 'length (length vals)) (let ((vect (js-array-vector o))) (let lp ((i 0) (vals vals)) (cond ((not (null? vals)) (vector-set! vect i (car vals)) (lp (1+ i) (cdr vals))) (else o)))))) (define *array-prototype* (make <js-object> #:class "Array" #:value new-array #:constructor new-array)) (hashq-set! *program-wrappers* new-array *array-prototype*) (pput *array-prototype* 'prototype *array-prototype*) (pput *array-prototype* 'constructor new-array) (define-method (pget (o <js-array-object>) p) (cond ((and (integer? p) (exact? p) (>= p 0)) (let ((v (js-array-vector o))) (if (< p (vector-length v)) (vector-ref v p) (next-method)))) ((or (and (symbol? p) (eq? p 'length)) (and (string? p) (string=? p "length"))) (vector-length (js-array-vector o))) (else (next-method)))) (define-method (pput (o <js-array-object>) p v) (cond ((and (integer? p) (exact? p) (>= 0 p)) (let ((vect (js-array-vector o))) (if (< p (vector-length vect)) (vector-set! vect p v) : round up to powers of 2 ? (let ((new (make-vector (1+ p) 0))) (vector-move-left! vect 0 (vector-length vect) new 0) (set! (js-array-vector o) new) (vector-set! new p v))))) ((or (and (symbol? p) (eq? p 'length)) (and (string? p) (string=? p "length"))) (let ((vect (js-array-vector o))) (let ((new (make-vector (->uint32 v) 0))) (vector-move-left! vect 0 (min (vector-length vect) (->uint32 v)) new 0) (set! (js-array-vector o) new)))) (else (next-method)))) (define-js-method *array-prototype* (toString) (format #f "~A" (js-array-vector this))) (define-js-method *array-prototype* (concat . rest) (let* ((len (apply + (->uint32 (pget this 'length)) (map (lambda (x) (->uint32 (pget x 'length))) rest))) (rv (make-vector len 0))) (let lp ((objs (cons this rest)) (i 0)) (cond ((null? objs) (make <js-array-object> #:class "Array" #:prototype *array-prototype* #:vector rv)) ((is-a? (car objs) <js-array-object>) (let ((v (js-array-vector (car objs)))) (vector-move-left! v 0 (vector-length v) rv i) (lp (cdr objs) (+ i (vector-length v))))) (else (error "generic array concats not yet implemented")))))) (define-js-method *array-prototype* (join . separator) (let lp ((i (1- (->uint32 (pget this 'length)))) (l '())) (if (< i 0) (string-join l (if separator (->string (car separator)) ",")) (lp (1+ i) (cons (->string (pget this i)) l))))) (define-js-method *array-prototype* (pop) (let ((len (->uint32 (pget this 'length)))) (if (zero? len) *undefined* (let ((ret (pget this (1- len)))) (pput this 'length (1- len)) ret)))) (define-js-method *array-prototype* (push . args) (let lp ((args args)) (if (null? args) (->uint32 (pget this 'length)) (begin (pput this (->uint32 (pget this 'length)) (car args)) (lp (cdr args))))))
580f822308cfa957b72f628c4124db813ffed1f03ac5ed638e4238c68a7d2fd1
facebookincubator/retrie
Demo.hs
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. -- {-# LANGUAGE OverloadedStrings #-} module Demo (stringToFooArg) where import Retrie argMapping :: [(FastString, String)] argMapping = [("foo", "Foo"), ("bar", "Bar")] stringToFooArg :: LibDir -> MatchResultTransformer stringToFooArg libdir _ctxt match | MatchResult substitution template <- match , Just (HoleExpr expr) <- lookupSubst "arg" substitution , L _ (HsLit _ (HsString _ str)) <- astA expr = do newExpr <- case lookup str argMapping of Nothing -> parseExpr libdir $ "error \"invalid argument: " ++ unpackFS str ++ "\"" Just constructor -> parseExpr libdir constructor return $ MatchResult (extendSubst substitution "arg" (HoleExpr newExpr)) template | otherwise = return NoMatch
null
https://raw.githubusercontent.com/facebookincubator/retrie/4b59de66e2b04b7e737c23592c86f6253e5e7a53/tests/Demo.hs
haskell
LICENSE file in the root directory of this source tree. # LANGUAGE OverloadedStrings #
Copyright ( c ) Facebook , Inc. and its affiliates . This source code is licensed under the MIT license found in the module Demo (stringToFooArg) where import Retrie argMapping :: [(FastString, String)] argMapping = [("foo", "Foo"), ("bar", "Bar")] stringToFooArg :: LibDir -> MatchResultTransformer stringToFooArg libdir _ctxt match | MatchResult substitution template <- match , Just (HoleExpr expr) <- lookupSubst "arg" substitution , L _ (HsLit _ (HsString _ str)) <- astA expr = do newExpr <- case lookup str argMapping of Nothing -> parseExpr libdir $ "error \"invalid argument: " ++ unpackFS str ++ "\"" Just constructor -> parseExpr libdir constructor return $ MatchResult (extendSubst substitution "arg" (HoleExpr newExpr)) template | otherwise = return NoMatch
0d82e3761d11dfcaf2d47617e16c5c20bb438ca9645426ed90a5335abc747134
Bodigrim/tasty-bench
bench-fibo.hs
module Main (main) where import Test.Tasty.Bench fibo :: Int -> Integer fibo n = if n < 2 then toInteger n else fibo (n - 1) + fibo (n - 2) main :: IO () main = defaultMain [ bgroup "fibonacci numbers" [ bench "fifth" $ nf fibo 5 , bench "tenth" $ nf fibo 10 , bench "twentieth" $ nf fibo 20 ] ]
null
https://raw.githubusercontent.com/Bodigrim/tasty-bench/3790437ae4a075b5046f3226eeef6c75e022de9b/bench/bench-fibo.hs
haskell
module Main (main) where import Test.Tasty.Bench fibo :: Int -> Integer fibo n = if n < 2 then toInteger n else fibo (n - 1) + fibo (n - 2) main :: IO () main = defaultMain [ bgroup "fibonacci numbers" [ bench "fifth" $ nf fibo 5 , bench "tenth" $ nf fibo 10 , bench "twentieth" $ nf fibo 20 ] ]
8bab0e4680d34d1d3a9ecaabb270537504327e75b0eb0df6204806ed42076aae
aryx/ocamltarzan
pa_value.ml
pp camlp4orf * Copyright ( c ) 2009 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2009 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (* Type generator *) open Pa_type_conv (* Fork of -api-libs.hg?file/7a17b2ab5cfc/rpc-light/pa_rpc.ml *) open Camlp4 open PreCast open Ast let value_of n = "vof_" ^ n let of_value n = n ^ "_ofv" let of_value_aux n = n ^ "_of_value_aux" let value_of_aux n = "value_of_" ^ n ^ "_aux" Utils let debug_ctyp ctyp = let module PP = Camlp4.Printers.OCaml.Make(Syntax) in let pp = new PP.printer () in Format.printf "unknown type %a@.\n" pp#ctyp ctyp let list_of_ctyp_decl tds = let rec aux accu = function | Ast.TyAnd (loc, tyl, tyr) -> aux (aux accu tyl) tyr | Ast.TyDcl (loc, id, _, ty, []) -> (id, ty) :: accu | _ -> failwith "list_of_ctyp_decl: unexpected type" in aux [] tds let rec decompose_fields _loc fields = match fields with | <:ctyp< $t1$; $t2$ >> -> decompose_fields _loc t1 @ decompose_fields _loc t2 | <:ctyp< $lid:field_name$: mutable $t$ >> | <:ctyp< $lid:field_name$: $t$ >> -> [ field_name, t ] | _ -> failwith "unexpected type while processing fields" let expr_list_of_list _loc exprs = match List.rev exprs with | [] -> <:expr< [] >> | h::t -> List.fold_left (fun accu x -> <:expr< [ $x$ :: $accu$ ] >>) <:expr< [ $h$ ] >> t let patt_list_of_list _loc patts = match List.rev patts with | [] -> <:patt< [] >> | h::t -> List.fold_left (fun accu x -> <:patt< [ $x$ :: $accu$ ] >>) <:patt< [ $h$ ] >> t let expr_tuple_of_list _loc = function | [] -> <:expr< >> | [x] -> x | h::t -> ExTup (_loc, List.fold_left (fun accu n -> <:expr< $accu$, $n$ >>) h t) let patt_tuple_of_list _loc = function | [] -> <:patt< >> | [x] -> x | h::t -> PaTup (_loc, List.fold_left (fun accu n -> <:patt< $accu$, $n$ >>) h t) let decompose_variants _loc variant = let rec fn accu = function | <:ctyp< $t$ | $u$ >> -> fn (fn accu t) u | <:ctyp< $uid:id$ of $t$ >> -> ((id, `V) , list_of_ctyp t []) :: accu | <:ctyp< `$uid:id$ of $t$ >> -> ((id, `PV), list_of_ctyp t []) :: accu | <:ctyp< $uid:id$ >> -> ((id, `V) , []) :: accu | <:ctyp< `$uid:id$ >> -> ((id, `PV), []) :: accu | _ -> failwith "decompose_variant" in List.split (fn [] variant) let recompose_variant _loc (n, t) patts = match t, patts with | `V , [] -> <:patt< $uid:n$ >> | `PV, [] -> <:patt< `$uid:n$ >> | `V , _ -> <:patt< $uid:n$ $patt_tuple_of_list _loc patts$ >> | `PV, _ -> <:patt< `$uid:n$ $patt_tuple_of_list _loc patts$ >> let count = ref 0 let new_id _loc = incr count; let new_id = Printf.sprintf "__x%i__" !count in <:expr< $lid:new_id$ >>, <:patt< $lid:new_id$ >> let new_id_list _loc l = List.split (List.map (fun _ -> new_id _loc) l) exception Type_not_supported of ctyp (* Conversion ML type -> Value.t *) module Value_of = struct let env_type _loc names = <:ctyp< { $List.fold_left (fun accu n -> <:ctyp< $lid:n$ : list ( $lid:n$ * int64 ); $accu$ >>) <:ctyp< __new_id__ : unit -> int64 >> names$ } >> let empty_env _loc names = <:expr< let __new_id__ = let count = ref 0L in let x () = do { count.val := Int64.add count.val 1L; count.val } in x in { $rbSem_of_list (List.map (fun n -> <:rec_binding< Deps.$lid:n$ = [] >>) names)$ ; __new_id__ = __new_id__ } >> let replace_env _loc names id t = <:expr< { (__env__) with Deps.$lid:t$ = [ ($id$, __id__) :: __env__.Deps.$lid:t$ ] } >> let rec create names id ctyp = let _loc = loc_of_ctyp ctyp in match ctyp with | <:ctyp< unit >> -> <:expr< V.VUnit >> | <:ctyp< int >> -> <:expr< V.VInt (Int64.of_int $id$) >> | <:ctyp< int32 >> -> <:expr< V.VInt (Int64.of_int32 $id$) >> | <:ctyp< int64 >> -> <:expr< V.VInt $id$ >> | <:ctyp< float >> -> <:expr< V.VFloat $id$ >> | <:ctyp< char >> -> <:expr< V.VInt (Int64.of_int (Char.code $id$)) >> | <:ctyp< string >> -> <:expr< V.VString $id$ >> | <:ctyp< bool >> -> <:expr< V.VBool $id$ >> | <:ctyp< [< $t$ ] >> | <:ctyp< [> $t$ ] >> | <:ctyp< [= $t$ ] >> | <:ctyp< [ $t$ ] >> -> let ids, ctyps = decompose_variants _loc t in let pattern (n, t) ctyps = let ids, pids = new_id_list _loc ctyps in let body = <:expr< V.VSum ( $str:n$, $expr_list_of_list _loc (List.map2 (create names) ids ctyps)$ ) >> in <:match_case< $recompose_variant _loc (n,t) pids$ -> $body$ >> in let patterns = mcOr_of_list (List.map2 pattern ids ctyps) in <:expr< match $id$ with [ $patterns$ ] >> | <:ctyp< option $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< match $id$ with [ Some $new_pid$ -> V.VSome $create names new_id t$ | None -> V.VNone ] >> | <:ctyp< $tup:tp$ >> -> let ctyps = list_of_ctyp tp [] in let ids, pids = new_id_list _loc ctyps in let exprs = List.map2 (create names) ids ctyps in <:expr< let $patt_tuple_of_list _loc pids$ = $id$ in V.VTuple $expr_list_of_list _loc exprs$ >> | <:ctyp< list $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< V.VList (List.map (fun $new_pid$ -> $create names new_id t$) $id$) >> | <:ctyp< array $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< V.VEnum (Array.to_list (Array.map (fun $new_pid$ -> $create names new_id t$) $id$)) >> | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let bindings = List.map2 (fun pid (f, _) -> <:binding< $pid$ = $id$ . $lid:f$ >>) pids fields in let one_expr nid (n, ctyp) = <:expr< ($str:n$, $create names nid ctyp$) >> in let expr = <:expr< V.VDict $expr_list_of_list _loc (List.map2 one_expr ids fields)$ >> in <:expr< let $biAnd_of_list bindings$ in $expr$ >> | <:ctyp< < $t$ > >> -> let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let bindings = List.map2 (fun pid (f, _) -> <:binding< $pid$ = $id$ # $lid:f$ >>) pids fields in let one_expr nid (n, ctyp) = <:expr< ($str:n$, $create names nid ctyp$) >> in let expr = <:expr< V.VDict $expr_list_of_list _loc (List.map2 one_expr ids fields)$ >> in <:expr< let $biAnd_of_list bindings$ in $expr$ >> | <:ctyp< $t$ -> $u$ >> -> <:expr< V.VArrow (let module M = Marshal in M.to_string $id$ [ M.Closures ]) >> | <:ctyp< $lid:t$ >> -> if not (List.mem t names) then <:expr< $lid:value_of t$ $id$ >> else <:expr< $lid:value_of t$ $id$ >> < : expr < if id$ _ _ env__.Deps.$lid : t$ then V.Var ( $ str : t$ , $ id$ _ _ env__.Deps.$lid : t$ ) else begin let _ _ i d _ _ = _ _ env__.Deps.__new_id _ _ ( ) in let _ _ value _ _ = $ lid : value_of_aux t$ $ replace_env _ loc names i d t$ $ id$ in if List.mem ( $ str : t$ , _ _ i d _ _ ) ( V.free_vars _ _ value _ _ ) then V.Rec ( ( $ str : t$ , _ _ i d _ _ ) , _ _ value _ _ ) else V.Ext ( ( $ str : t$ , _ _ i d _ _ ) , _ _ value _ _ ) end > > <:expr< if List.mem_assq $id$ __env__.Deps.$lid:t$ then V.Var ($str:t$, List.assq $id$ __env__.Deps.$lid:t$) else begin let __id__ = __env__.Deps.__new_id__ () in let __value__ = $lid:value_of_aux t$ $replace_env _loc names id t$ $id$ in if List.mem ($str:t$, __id__) (V.free_vars __value__) then V.Rec (($str:t$, __id__), __value__) else V.Ext (($str:t$, __id__), __value__) end >> *) | _ -> <:expr< V.VTODO>> raise ( Type_not_supported ctyp ) let gen_one names name ctyp = let _loc = loc_of_ctyp ctyp in let id, pid = new_id _loc in <:binding< $lid:value_of_aux name$ = fun __env__ -> fun $pid$ -> let module V = Ocaml in $create names id ctyp$ >> let gen tds = let _loc = loc_of_ctyp tds in let ids, ctyps = List.split (list_of_ctyp_decl tds) in let bindings = List.map2 (gen_one ids) ids ctyps in biAnd_of_list bindings let inputs _loc ids = patt_tuple_of_list _loc (List.map (fun x -> <:patt< ($lid:value_of x$ : $lid:x$ -> Ocaml.v) >>) ids) let _ _ env _ _ = $ empty_env _ loc ids$ in let _ _ i d _ _ = _ _ env__.Deps.__new_id _ _ ( ) in let _ _ env _ _ = $ replace_env _ loc ids < : expr < $ lid : x$ > > x$ in match $ lid : value_of_aux x$ _ _ env _ _ $ lid : x$ with [ Value . Rec _ as x - > x | x when ( List.mem ( $ str : x$ , _ _ i d _ _ ) ( Value.free_vars x ) ) - > Value . Rec ( ( $ str : x$ , _ _ i d _ _ ) , x ) | x - > Value . Ext ( ( $ str : x$ , _ _ env__.Deps.__new_id _ _ ( ) ) , x ) ] let __env__ = $empty_env _loc ids$ in let __id__ = __env__.Deps.__new_id__ () in let __env__ = $replace_env _loc ids <:expr< $lid:x$ >> x$ in match $lid:value_of_aux x$ __env__ $lid:x$ with [ Value.Rec _ as x -> x | x when ( List.mem ($str:x$, __id__) (Value.free_vars x) ) -> Value.Rec (($str:x$, __id__), x) | x -> Value.Ext (($str:x$, __env__.Deps.__new_id__ ()), x) ] *) let outputs _loc ids = expr_tuple_of_list _loc (List.map (fun x -> <:expr< fun $lid:x$ -> $lid:value_of_aux x$ __env__ $lid:x$ >> ) ids) end (* Conversion Value.t -> ML type *) module Of_value = struct let env_type _loc names = <:ctyp< { $List.fold_left (fun accu n -> <:ctyp< $lid:n$ : list (int64 * $lid:n$) ; $accu$ >>) <:ctyp< >> names$ } >> let empty_env _loc names = <:expr< { $rbSem_of_list (List.map (fun n -> <:rec_binding< Deps.$lid:n$ = [] >>) names)$ } >> let replace_env _loc names name = if List.length names = 1 then <:expr< { Deps.$lid:name$ = [ (__id__, __value0__) :: __env__.Deps.$lid:name$ ] } >> else <:expr< { (__env__) with Deps.$lid:name$ = [ (__id__, __value0__) :: __env__.Deps.$lid:name$ ] } >> let string_of_env _loc names = <:expr< Printf.sprintf "{%s}" (String.concat "," $expr_list_of_list _loc (List.map (fun n -> <:expr< Printf.sprintf "%s:%i" $str:n$ (List.length __env__.Deps.$lid:n$) >>) names)$) >> let str_of_id id = match id with <:expr@loc< $lid:s$ >> -> <:expr@loc< $str:s$ >> | _ -> assert false let runtime_error id expected = let _loc = Loc.ghost in <:match_case< __x__ -> do { Printf.printf "Runtime error while parsing '%s': got '%s' while '%s' was expected\\n" $str_of_id id$ (Value.to_string __x__) $str:expected$; raise (Deps.Runtime_error($str:expected$, __x__)) } >> let runtime_exn_error id doing = let _loc = Loc.ghost in <:match_case< __x__ -> do { Printf.printf "Runtime error while parsing '%s': got exception '%s' doing '%s'\\n" $str_of_id id$ (Printexc.to_string __x__) $str:doing$; raise (Deps.Runtime_exn_error($str:doing$, __x__)) } >> let rec create names id ctyp = let _loc = loc_of_ctyp ctyp in match ctyp with | <:ctyp< unit >> -> <:expr< match $id$ with [ V.Unit -> () | $runtime_error id "Unit"$ ] >> | <:ctyp< int >> -> <:expr< match $id$ with [ V.Int x -> Int64.to_int x | $runtime_error id "Int(int)"$ ] >> | <:ctyp< int32 >> -> <:expr< match $id$ with [ V.Int x -> Int64.to_int32 x | $runtime_error id "Int(int32)"$ ] >> | <:ctyp< int64 >> -> <:expr< match $id$ with [ V.Int x -> x | $runtime_error id "Int(int64)"$ ] >> | <:ctyp< float >> -> <:expr< match $id$ with [ V.Float x -> x | $runtime_error id "Float"$ ] >> | <:ctyp< char >> -> <:expr< match $id$ with [ V.Int x -> Char.chr (Int64.to_int x) | $runtime_error id "Int(char)"$ ] >> | <:ctyp< string >> -> <:expr< match $id$ with [ V.String x -> x | $runtime_error id "String(string)"$ ] >> | <:ctyp< bool >> -> <:expr< match $id$ with [ V.Bool x -> x | $runtime_error id "Bool"$ ] >> | <:ctyp< [< $t$ ] >> | <:ctyp< [> $t$ ] >> | <:ctyp< [= $t$ ] >> | <:ctyp< [ $t$ ] >> -> let ids, ctyps = decompose_variants _loc t in let pattern (n, t) ctyps = let ids, pids = new_id_list _loc ctyps in let patt = <:patt< V.Sum ( $str:n$, $patt_list_of_list _loc pids$ ) >> in let exprs = List.map2 (create names) ids ctyps in let body = List.fold_right (fun a b -> <:expr< $b$ $a$ >>) (List.rev exprs) (if t = `V then <:expr< $uid:n$ >> else <:expr< `$uid:n$ >>) in <:match_case< $patt$ -> $body$ >> in let fail_match = <:match_case< $runtime_error id "Sum"$ >> in let patterns = mcOr_of_list (List.map2 pattern ids ctyps @ [ fail_match ]) in <:expr< match $id$ with [ $patterns$ ] >> | <:ctyp< option $t$ >> -> let nid, npid = new_id _loc in <:expr< match $id$ with [ V.Null -> None | V.Value $npid$ -> Some $create names nid t$ | $runtime_error id "Null/Value"$ ] >> | <:ctyp< $tup:tp$ >> -> let ctyps = list_of_ctyp tp [] in let ids, pids = new_id_list _loc ctyps in let exprs = List.map2 (create names) ids ctyps in <:expr< match $id$ with [ V.Tuple $patt_list_of_list _loc pids$ -> $expr_tuple_of_list _loc exprs$ | $runtime_error id "List"$ ] >> | <:ctyp< list $t$ >> -> let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:expr< match $id$ with [ V.Enum $npid$ -> List.map (fun $npid2$ -> $create names nid2 t$) $nid$ | $runtime_error id "List"$ ] >> | <:ctyp< array $t$ >> -> let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:expr< match $id$ with [ V.Enum $npid$ -> Array.of_list (List.map (fun $npid2$ -> $create names nid2 t$) $nid$) | $runtime_error id "List"$ ] >> | <:ctyp< { $t$ } >> -> let nid, npid = new_id _loc in let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let exprs = List.map2 (fun id (n, ctyp) -> <:rec_binding< $lid:n$ = $create names id ctyp$ >>) ids fields in let bindings = List.map2 (fun pid (n, ctyp) -> <:binding< $pid$ = try List.assoc $str:n$ $nid$ with [ $runtime_exn_error nid ("Looking for key "^n)$ ] >> ) pids fields in <:expr< match $id$ with [ V.Dict $npid$ -> let $biAnd_of_list bindings$ in { $rbSem_of_list exprs$ } | $runtime_error id "Dict"$ ] >> | <:ctyp< < $t$ > >> -> let nid, npid = new_id _loc in let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let exprs = List.map2 (fun id (n, ctyp) -> <:class_str_item< method $lid:n$ = $create names id ctyp$ >>) ids fields in let bindings = List.map2 (fun pid (n, ctyp) -> <:binding< $pid$ = try List.assoc $str:n$ $nid$ with [ $runtime_exn_error nid ("Looking for key "^n)$ ] >> ) pids fields in <:expr< match $id$ with [ V.Dict $npid$ -> let $biAnd_of_list bindings$ in object $crSem_of_list exprs$ end | $runtime_error id "Dict"$ ] >> | <:ctyp< $t$ -> $u$ >> -> <:expr< match $id$ with [ V.Arrow f -> (let module M = Marshal in M.from_string f : $t$ -> $u$) | $runtime_error id "Marshal"$ ] >> | <:ctyp< $lid:t$ >> -> if List.mem t names then <:expr< $lid:of_value_aux t$ __env__ $id$ >> else <:expr< $lid:of_value t$ $id$ >> | _ -> <:expr< V.TODO>> raise ( Type_not_supported ctyp ) let default_value _loc = function | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let fields = List.map (fun (n, ctyp) -> <:rec_binding< $lid:n$ = Obj.magic 0 >>) fields in <:expr< { $rbSem_of_list fields$ } >> | _ -> <:expr< failwith "Cyclic values should be defined via record fields only" >> let set_value _loc = function | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let field = ref (-1) in let fields = List.map (fun (n, ctyp) -> incr field; <:expr< Obj.set_field (Obj.repr __value0__) $`int:!field$ (Obj.field (Obj.repr __value1__) $`int:!field$) >>) fields in <:expr< do { $exSem_of_list fields$ } >> | _ -> <:expr< failwith "Cyclic values should be defined via record fields only" >> let gen_one names name ctyp = let _loc = loc_of_ctyp ctyp in let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:binding< $lid:of_value_aux name$ = fun __env__ -> fun $npid$ -> let module V = Ocaml in match $nid$ with [ V.Var (n, __id__) -> List.assoc __id__ __env__.Deps.$lid:name$ | V.Rec ((n, __id__), $npid2$ ) -> if List.mem_assoc __id__ __env__.Deps.$lid:name$ then List.assoc __id__ __env__.Deps.$lid:name$ else let __value0__ = $default_value _loc ctyp$ in let __env__ = $replace_env _loc names name$ in let __value1__ = $create names nid2 ctyp$ in let () = $set_value _loc ctyp$ in __value0__ | V.Ext (n, $npid2$) -> $create names nid2 ctyp$ | $runtime_error nid "Var/Rec/Ext"$ ] >> let gen tds = let _loc = loc_of_ctyp tds in let ids, ctyps = List.split (list_of_ctyp_decl tds) in let bindings = List.map2 (gen_one ids) ids ctyps in biAnd_of_list bindings let inputs _loc ids = patt_tuple_of_list _loc (List.map (fun x -> <:patt< ($lid:of_value x$ : Value.t -> $lid:x$) >>) ids) let outputs _loc ids = expr_tuple_of_list _loc (List.map (fun x -> <:expr< $lid:of_value_aux x$ $empty_env _loc ids$ >>) ids) end let gen tds = let _loc = loc_of_ctyp tds in let ids, _ = List.split (list_of_ctyp_decl tds) in value $ Of_value.inputs _ loc ids$ = let module = struct type env = $ Of_value.env_type _ loc ids$ ; exception Runtime_error of ( string * Value.t ) ; exception Runtime_exn_error of ( string * exn ) ; end in let rec $ Of_value.gen tds$ in $ Of_value.outputs _ loc ids$ ; ... let module = struct type env = $ Value_of.env_type _ loc ids$ ; end in value $Of_value.inputs _loc ids$ = let module Deps = struct type env = $Of_value.env_type _loc ids$; exception Runtime_error of (string * Value.t); exception Runtime_exn_error of (string * exn); end in let rec $Of_value.gen tds$ in $Of_value.outputs _loc ids$; ... let module Deps = struct type env = $Value_of.env_type _loc ids$; end in *) <:str_item< value $Value_of.inputs _loc ids$ = let rec $Value_of.gen tds$ in $Value_of.outputs _loc ids$; >> let _ = add_generator "vof" (fun tds -> let _loc = loc_of_ctyp tds in <:str_item< $gen tds$ >>)
null
https://raw.githubusercontent.com/aryx/ocamltarzan/4140f5102cee83a2ca7be996ca2d92e9cb035f9c/pa/pa_value.ml
ocaml
Type generator Fork of -api-libs.hg?file/7a17b2ab5cfc/rpc-light/pa_rpc.ml Conversion ML type -> Value.t Conversion Value.t -> ML type
pp camlp4orf * Copyright ( c ) 2009 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2009 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Pa_type_conv open Camlp4 open PreCast open Ast let value_of n = "vof_" ^ n let of_value n = n ^ "_ofv" let of_value_aux n = n ^ "_of_value_aux" let value_of_aux n = "value_of_" ^ n ^ "_aux" Utils let debug_ctyp ctyp = let module PP = Camlp4.Printers.OCaml.Make(Syntax) in let pp = new PP.printer () in Format.printf "unknown type %a@.\n" pp#ctyp ctyp let list_of_ctyp_decl tds = let rec aux accu = function | Ast.TyAnd (loc, tyl, tyr) -> aux (aux accu tyl) tyr | Ast.TyDcl (loc, id, _, ty, []) -> (id, ty) :: accu | _ -> failwith "list_of_ctyp_decl: unexpected type" in aux [] tds let rec decompose_fields _loc fields = match fields with | <:ctyp< $t1$; $t2$ >> -> decompose_fields _loc t1 @ decompose_fields _loc t2 | <:ctyp< $lid:field_name$: mutable $t$ >> | <:ctyp< $lid:field_name$: $t$ >> -> [ field_name, t ] | _ -> failwith "unexpected type while processing fields" let expr_list_of_list _loc exprs = match List.rev exprs with | [] -> <:expr< [] >> | h::t -> List.fold_left (fun accu x -> <:expr< [ $x$ :: $accu$ ] >>) <:expr< [ $h$ ] >> t let patt_list_of_list _loc patts = match List.rev patts with | [] -> <:patt< [] >> | h::t -> List.fold_left (fun accu x -> <:patt< [ $x$ :: $accu$ ] >>) <:patt< [ $h$ ] >> t let expr_tuple_of_list _loc = function | [] -> <:expr< >> | [x] -> x | h::t -> ExTup (_loc, List.fold_left (fun accu n -> <:expr< $accu$, $n$ >>) h t) let patt_tuple_of_list _loc = function | [] -> <:patt< >> | [x] -> x | h::t -> PaTup (_loc, List.fold_left (fun accu n -> <:patt< $accu$, $n$ >>) h t) let decompose_variants _loc variant = let rec fn accu = function | <:ctyp< $t$ | $u$ >> -> fn (fn accu t) u | <:ctyp< $uid:id$ of $t$ >> -> ((id, `V) , list_of_ctyp t []) :: accu | <:ctyp< `$uid:id$ of $t$ >> -> ((id, `PV), list_of_ctyp t []) :: accu | <:ctyp< $uid:id$ >> -> ((id, `V) , []) :: accu | <:ctyp< `$uid:id$ >> -> ((id, `PV), []) :: accu | _ -> failwith "decompose_variant" in List.split (fn [] variant) let recompose_variant _loc (n, t) patts = match t, patts with | `V , [] -> <:patt< $uid:n$ >> | `PV, [] -> <:patt< `$uid:n$ >> | `V , _ -> <:patt< $uid:n$ $patt_tuple_of_list _loc patts$ >> | `PV, _ -> <:patt< `$uid:n$ $patt_tuple_of_list _loc patts$ >> let count = ref 0 let new_id _loc = incr count; let new_id = Printf.sprintf "__x%i__" !count in <:expr< $lid:new_id$ >>, <:patt< $lid:new_id$ >> let new_id_list _loc l = List.split (List.map (fun _ -> new_id _loc) l) exception Type_not_supported of ctyp module Value_of = struct let env_type _loc names = <:ctyp< { $List.fold_left (fun accu n -> <:ctyp< $lid:n$ : list ( $lid:n$ * int64 ); $accu$ >>) <:ctyp< __new_id__ : unit -> int64 >> names$ } >> let empty_env _loc names = <:expr< let __new_id__ = let count = ref 0L in let x () = do { count.val := Int64.add count.val 1L; count.val } in x in { $rbSem_of_list (List.map (fun n -> <:rec_binding< Deps.$lid:n$ = [] >>) names)$ ; __new_id__ = __new_id__ } >> let replace_env _loc names id t = <:expr< { (__env__) with Deps.$lid:t$ = [ ($id$, __id__) :: __env__.Deps.$lid:t$ ] } >> let rec create names id ctyp = let _loc = loc_of_ctyp ctyp in match ctyp with | <:ctyp< unit >> -> <:expr< V.VUnit >> | <:ctyp< int >> -> <:expr< V.VInt (Int64.of_int $id$) >> | <:ctyp< int32 >> -> <:expr< V.VInt (Int64.of_int32 $id$) >> | <:ctyp< int64 >> -> <:expr< V.VInt $id$ >> | <:ctyp< float >> -> <:expr< V.VFloat $id$ >> | <:ctyp< char >> -> <:expr< V.VInt (Int64.of_int (Char.code $id$)) >> | <:ctyp< string >> -> <:expr< V.VString $id$ >> | <:ctyp< bool >> -> <:expr< V.VBool $id$ >> | <:ctyp< [< $t$ ] >> | <:ctyp< [> $t$ ] >> | <:ctyp< [= $t$ ] >> | <:ctyp< [ $t$ ] >> -> let ids, ctyps = decompose_variants _loc t in let pattern (n, t) ctyps = let ids, pids = new_id_list _loc ctyps in let body = <:expr< V.VSum ( $str:n$, $expr_list_of_list _loc (List.map2 (create names) ids ctyps)$ ) >> in <:match_case< $recompose_variant _loc (n,t) pids$ -> $body$ >> in let patterns = mcOr_of_list (List.map2 pattern ids ctyps) in <:expr< match $id$ with [ $patterns$ ] >> | <:ctyp< option $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< match $id$ with [ Some $new_pid$ -> V.VSome $create names new_id t$ | None -> V.VNone ] >> | <:ctyp< $tup:tp$ >> -> let ctyps = list_of_ctyp tp [] in let ids, pids = new_id_list _loc ctyps in let exprs = List.map2 (create names) ids ctyps in <:expr< let $patt_tuple_of_list _loc pids$ = $id$ in V.VTuple $expr_list_of_list _loc exprs$ >> | <:ctyp< list $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< V.VList (List.map (fun $new_pid$ -> $create names new_id t$) $id$) >> | <:ctyp< array $t$ >> -> let new_id, new_pid = new_id _loc in <:expr< V.VEnum (Array.to_list (Array.map (fun $new_pid$ -> $create names new_id t$) $id$)) >> | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let bindings = List.map2 (fun pid (f, _) -> <:binding< $pid$ = $id$ . $lid:f$ >>) pids fields in let one_expr nid (n, ctyp) = <:expr< ($str:n$, $create names nid ctyp$) >> in let expr = <:expr< V.VDict $expr_list_of_list _loc (List.map2 one_expr ids fields)$ >> in <:expr< let $biAnd_of_list bindings$ in $expr$ >> | <:ctyp< < $t$ > >> -> let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let bindings = List.map2 (fun pid (f, _) -> <:binding< $pid$ = $id$ # $lid:f$ >>) pids fields in let one_expr nid (n, ctyp) = <:expr< ($str:n$, $create names nid ctyp$) >> in let expr = <:expr< V.VDict $expr_list_of_list _loc (List.map2 one_expr ids fields)$ >> in <:expr< let $biAnd_of_list bindings$ in $expr$ >> | <:ctyp< $t$ -> $u$ >> -> <:expr< V.VArrow (let module M = Marshal in M.to_string $id$ [ M.Closures ]) >> | <:ctyp< $lid:t$ >> -> if not (List.mem t names) then <:expr< $lid:value_of t$ $id$ >> else <:expr< $lid:value_of t$ $id$ >> < : expr < if id$ _ _ env__.Deps.$lid : t$ then V.Var ( $ str : t$ , $ id$ _ _ env__.Deps.$lid : t$ ) else begin let _ _ i d _ _ = _ _ env__.Deps.__new_id _ _ ( ) in let _ _ value _ _ = $ lid : value_of_aux t$ $ replace_env _ loc names i d t$ $ id$ in if List.mem ( $ str : t$ , _ _ i d _ _ ) ( V.free_vars _ _ value _ _ ) then V.Rec ( ( $ str : t$ , _ _ i d _ _ ) , _ _ value _ _ ) else V.Ext ( ( $ str : t$ , _ _ i d _ _ ) , _ _ value _ _ ) end > > <:expr< if List.mem_assq $id$ __env__.Deps.$lid:t$ then V.Var ($str:t$, List.assq $id$ __env__.Deps.$lid:t$) else begin let __id__ = __env__.Deps.__new_id__ () in let __value__ = $lid:value_of_aux t$ $replace_env _loc names id t$ $id$ in if List.mem ($str:t$, __id__) (V.free_vars __value__) then V.Rec (($str:t$, __id__), __value__) else V.Ext (($str:t$, __id__), __value__) end >> *) | _ -> <:expr< V.VTODO>> raise ( Type_not_supported ctyp ) let gen_one names name ctyp = let _loc = loc_of_ctyp ctyp in let id, pid = new_id _loc in <:binding< $lid:value_of_aux name$ = fun __env__ -> fun $pid$ -> let module V = Ocaml in $create names id ctyp$ >> let gen tds = let _loc = loc_of_ctyp tds in let ids, ctyps = List.split (list_of_ctyp_decl tds) in let bindings = List.map2 (gen_one ids) ids ctyps in biAnd_of_list bindings let inputs _loc ids = patt_tuple_of_list _loc (List.map (fun x -> <:patt< ($lid:value_of x$ : $lid:x$ -> Ocaml.v) >>) ids) let _ _ env _ _ = $ empty_env _ loc ids$ in let _ _ i d _ _ = _ _ env__.Deps.__new_id _ _ ( ) in let _ _ env _ _ = $ replace_env _ loc ids < : expr < $ lid : x$ > > x$ in match $ lid : value_of_aux x$ _ _ env _ _ $ lid : x$ with [ Value . Rec _ as x - > x | x when ( List.mem ( $ str : x$ , _ _ i d _ _ ) ( Value.free_vars x ) ) - > Value . Rec ( ( $ str : x$ , _ _ i d _ _ ) , x ) | x - > Value . Ext ( ( $ str : x$ , _ _ env__.Deps.__new_id _ _ ( ) ) , x ) ] let __env__ = $empty_env _loc ids$ in let __id__ = __env__.Deps.__new_id__ () in let __env__ = $replace_env _loc ids <:expr< $lid:x$ >> x$ in match $lid:value_of_aux x$ __env__ $lid:x$ with [ Value.Rec _ as x -> x | x when ( List.mem ($str:x$, __id__) (Value.free_vars x) ) -> Value.Rec (($str:x$, __id__), x) | x -> Value.Ext (($str:x$, __env__.Deps.__new_id__ ()), x) ] *) let outputs _loc ids = expr_tuple_of_list _loc (List.map (fun x -> <:expr< fun $lid:x$ -> $lid:value_of_aux x$ __env__ $lid:x$ >> ) ids) end module Of_value = struct let env_type _loc names = <:ctyp< { $List.fold_left (fun accu n -> <:ctyp< $lid:n$ : list (int64 * $lid:n$) ; $accu$ >>) <:ctyp< >> names$ } >> let empty_env _loc names = <:expr< { $rbSem_of_list (List.map (fun n -> <:rec_binding< Deps.$lid:n$ = [] >>) names)$ } >> let replace_env _loc names name = if List.length names = 1 then <:expr< { Deps.$lid:name$ = [ (__id__, __value0__) :: __env__.Deps.$lid:name$ ] } >> else <:expr< { (__env__) with Deps.$lid:name$ = [ (__id__, __value0__) :: __env__.Deps.$lid:name$ ] } >> let string_of_env _loc names = <:expr< Printf.sprintf "{%s}" (String.concat "," $expr_list_of_list _loc (List.map (fun n -> <:expr< Printf.sprintf "%s:%i" $str:n$ (List.length __env__.Deps.$lid:n$) >>) names)$) >> let str_of_id id = match id with <:expr@loc< $lid:s$ >> -> <:expr@loc< $str:s$ >> | _ -> assert false let runtime_error id expected = let _loc = Loc.ghost in <:match_case< __x__ -> do { Printf.printf "Runtime error while parsing '%s': got '%s' while '%s' was expected\\n" $str_of_id id$ (Value.to_string __x__) $str:expected$; raise (Deps.Runtime_error($str:expected$, __x__)) } >> let runtime_exn_error id doing = let _loc = Loc.ghost in <:match_case< __x__ -> do { Printf.printf "Runtime error while parsing '%s': got exception '%s' doing '%s'\\n" $str_of_id id$ (Printexc.to_string __x__) $str:doing$; raise (Deps.Runtime_exn_error($str:doing$, __x__)) } >> let rec create names id ctyp = let _loc = loc_of_ctyp ctyp in match ctyp with | <:ctyp< unit >> -> <:expr< match $id$ with [ V.Unit -> () | $runtime_error id "Unit"$ ] >> | <:ctyp< int >> -> <:expr< match $id$ with [ V.Int x -> Int64.to_int x | $runtime_error id "Int(int)"$ ] >> | <:ctyp< int32 >> -> <:expr< match $id$ with [ V.Int x -> Int64.to_int32 x | $runtime_error id "Int(int32)"$ ] >> | <:ctyp< int64 >> -> <:expr< match $id$ with [ V.Int x -> x | $runtime_error id "Int(int64)"$ ] >> | <:ctyp< float >> -> <:expr< match $id$ with [ V.Float x -> x | $runtime_error id "Float"$ ] >> | <:ctyp< char >> -> <:expr< match $id$ with [ V.Int x -> Char.chr (Int64.to_int x) | $runtime_error id "Int(char)"$ ] >> | <:ctyp< string >> -> <:expr< match $id$ with [ V.String x -> x | $runtime_error id "String(string)"$ ] >> | <:ctyp< bool >> -> <:expr< match $id$ with [ V.Bool x -> x | $runtime_error id "Bool"$ ] >> | <:ctyp< [< $t$ ] >> | <:ctyp< [> $t$ ] >> | <:ctyp< [= $t$ ] >> | <:ctyp< [ $t$ ] >> -> let ids, ctyps = decompose_variants _loc t in let pattern (n, t) ctyps = let ids, pids = new_id_list _loc ctyps in let patt = <:patt< V.Sum ( $str:n$, $patt_list_of_list _loc pids$ ) >> in let exprs = List.map2 (create names) ids ctyps in let body = List.fold_right (fun a b -> <:expr< $b$ $a$ >>) (List.rev exprs) (if t = `V then <:expr< $uid:n$ >> else <:expr< `$uid:n$ >>) in <:match_case< $patt$ -> $body$ >> in let fail_match = <:match_case< $runtime_error id "Sum"$ >> in let patterns = mcOr_of_list (List.map2 pattern ids ctyps @ [ fail_match ]) in <:expr< match $id$ with [ $patterns$ ] >> | <:ctyp< option $t$ >> -> let nid, npid = new_id _loc in <:expr< match $id$ with [ V.Null -> None | V.Value $npid$ -> Some $create names nid t$ | $runtime_error id "Null/Value"$ ] >> | <:ctyp< $tup:tp$ >> -> let ctyps = list_of_ctyp tp [] in let ids, pids = new_id_list _loc ctyps in let exprs = List.map2 (create names) ids ctyps in <:expr< match $id$ with [ V.Tuple $patt_list_of_list _loc pids$ -> $expr_tuple_of_list _loc exprs$ | $runtime_error id "List"$ ] >> | <:ctyp< list $t$ >> -> let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:expr< match $id$ with [ V.Enum $npid$ -> List.map (fun $npid2$ -> $create names nid2 t$) $nid$ | $runtime_error id "List"$ ] >> | <:ctyp< array $t$ >> -> let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:expr< match $id$ with [ V.Enum $npid$ -> Array.of_list (List.map (fun $npid2$ -> $create names nid2 t$) $nid$) | $runtime_error id "List"$ ] >> | <:ctyp< { $t$ } >> -> let nid, npid = new_id _loc in let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let exprs = List.map2 (fun id (n, ctyp) -> <:rec_binding< $lid:n$ = $create names id ctyp$ >>) ids fields in let bindings = List.map2 (fun pid (n, ctyp) -> <:binding< $pid$ = try List.assoc $str:n$ $nid$ with [ $runtime_exn_error nid ("Looking for key "^n)$ ] >> ) pids fields in <:expr< match $id$ with [ V.Dict $npid$ -> let $biAnd_of_list bindings$ in { $rbSem_of_list exprs$ } | $runtime_error id "Dict"$ ] >> | <:ctyp< < $t$ > >> -> let nid, npid = new_id _loc in let fields = decompose_fields _loc t in let ids, pids = new_id_list _loc fields in let exprs = List.map2 (fun id (n, ctyp) -> <:class_str_item< method $lid:n$ = $create names id ctyp$ >>) ids fields in let bindings = List.map2 (fun pid (n, ctyp) -> <:binding< $pid$ = try List.assoc $str:n$ $nid$ with [ $runtime_exn_error nid ("Looking for key "^n)$ ] >> ) pids fields in <:expr< match $id$ with [ V.Dict $npid$ -> let $biAnd_of_list bindings$ in object $crSem_of_list exprs$ end | $runtime_error id "Dict"$ ] >> | <:ctyp< $t$ -> $u$ >> -> <:expr< match $id$ with [ V.Arrow f -> (let module M = Marshal in M.from_string f : $t$ -> $u$) | $runtime_error id "Marshal"$ ] >> | <:ctyp< $lid:t$ >> -> if List.mem t names then <:expr< $lid:of_value_aux t$ __env__ $id$ >> else <:expr< $lid:of_value t$ $id$ >> | _ -> <:expr< V.TODO>> raise ( Type_not_supported ctyp ) let default_value _loc = function | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let fields = List.map (fun (n, ctyp) -> <:rec_binding< $lid:n$ = Obj.magic 0 >>) fields in <:expr< { $rbSem_of_list fields$ } >> | _ -> <:expr< failwith "Cyclic values should be defined via record fields only" >> let set_value _loc = function | <:ctyp< { $t$ } >> -> let fields = decompose_fields _loc t in let field = ref (-1) in let fields = List.map (fun (n, ctyp) -> incr field; <:expr< Obj.set_field (Obj.repr __value0__) $`int:!field$ (Obj.field (Obj.repr __value1__) $`int:!field$) >>) fields in <:expr< do { $exSem_of_list fields$ } >> | _ -> <:expr< failwith "Cyclic values should be defined via record fields only" >> let gen_one names name ctyp = let _loc = loc_of_ctyp ctyp in let nid, npid = new_id _loc in let nid2, npid2 = new_id _loc in <:binding< $lid:of_value_aux name$ = fun __env__ -> fun $npid$ -> let module V = Ocaml in match $nid$ with [ V.Var (n, __id__) -> List.assoc __id__ __env__.Deps.$lid:name$ | V.Rec ((n, __id__), $npid2$ ) -> if List.mem_assoc __id__ __env__.Deps.$lid:name$ then List.assoc __id__ __env__.Deps.$lid:name$ else let __value0__ = $default_value _loc ctyp$ in let __env__ = $replace_env _loc names name$ in let __value1__ = $create names nid2 ctyp$ in let () = $set_value _loc ctyp$ in __value0__ | V.Ext (n, $npid2$) -> $create names nid2 ctyp$ | $runtime_error nid "Var/Rec/Ext"$ ] >> let gen tds = let _loc = loc_of_ctyp tds in let ids, ctyps = List.split (list_of_ctyp_decl tds) in let bindings = List.map2 (gen_one ids) ids ctyps in biAnd_of_list bindings let inputs _loc ids = patt_tuple_of_list _loc (List.map (fun x -> <:patt< ($lid:of_value x$ : Value.t -> $lid:x$) >>) ids) let outputs _loc ids = expr_tuple_of_list _loc (List.map (fun x -> <:expr< $lid:of_value_aux x$ $empty_env _loc ids$ >>) ids) end let gen tds = let _loc = loc_of_ctyp tds in let ids, _ = List.split (list_of_ctyp_decl tds) in value $ Of_value.inputs _ loc ids$ = let module = struct type env = $ Of_value.env_type _ loc ids$ ; exception Runtime_error of ( string * Value.t ) ; exception Runtime_exn_error of ( string * exn ) ; end in let rec $ Of_value.gen tds$ in $ Of_value.outputs _ loc ids$ ; ... let module = struct type env = $ Value_of.env_type _ loc ids$ ; end in value $Of_value.inputs _loc ids$ = let module Deps = struct type env = $Of_value.env_type _loc ids$; exception Runtime_error of (string * Value.t); exception Runtime_exn_error of (string * exn); end in let rec $Of_value.gen tds$ in $Of_value.outputs _loc ids$; ... let module Deps = struct type env = $Value_of.env_type _loc ids$; end in *) <:str_item< value $Value_of.inputs _loc ids$ = let rec $Value_of.gen tds$ in $Value_of.outputs _loc ids$; >> let _ = add_generator "vof" (fun tds -> let _loc = loc_of_ctyp tds in <:str_item< $gen tds$ >>)
fb82837cb626001ce4e60eba503a6479df0fb950344d37e6e44f0cba560e571f
imandra-ai/ocaml-cimgui
Imgui_sys_sdl2.ml
open Ctypes open Tsdl module Types = Imgui_sdl2_ffi_f.Types module Ffi = Imgui_sdl2_ffi_f.Make(Imgui_sdl2_generated_funs) let unwrap_ = function | Ok x -> x | Error (`Msg e) -> failwith @@ "sdl error " ^ e (** Cast: get a window pointer *) let get_w_ptr (w:Sdl.window) : Types.window ptr = Ctypes.coerce (ptr void) (ptr Types.window) @@ ptr_of_raw_address @@ Sdl.unsafe_ptr_of_window w (** Cast: get a unit pointer *) let get_gl_ctx (ctx:Sdl.gl_context) : unit ptr = ptr_of_raw_address @@ Sdl.unsafe_ptr_of_gl_context ctx (** Cast: get a unit pointer *) let get_sdl_event (e:Sdl.event) : Types.event ptr = addr (Obj.magic e : Types.event) FIXME ! ! ! need upstream support from Tsdl Ctypes.coerce ( ptr void ) ( ptr Types.event ) @@ Ctypes.coerce ( ptr Tsdl.Sdl.event ) ( ptr void ) @@ e Ctypes.coerce (ptr void) (ptr Types.event) @@ Ctypes.coerce (ptr Tsdl.Sdl.event) (ptr void) @@ e *) let create_window_d3d ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr = let w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ |> get_w_ptr in if not @@ Ffi.init_for_d3d w then ( failwith "failed during initialization of D3D SDL_Window"; ); w * @param gl_ctx the openGL context let create_window_opengl ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr * Sdl.gl_context = (* TODO: provide these flags somewhere else *) let flags = Sdl.Window.(flags + opengl + resizable + allow_highdpi) in let sdl_w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ in let w = get_w_ptr sdl_w in let gl_ctx = Sdl.gl_create_context sdl_w |> unwrap_ in Sdl.gl_make_current sdl_w gl_ctx |> unwrap_; if get_gl_ctx gl_ctx |> is_null then failwith "sdl init: gl_context is null"; if not @@ Ffi.init_for_opengl w (get_gl_ctx gl_ctx) then ( failwith "failed during initialization of openGL SDL_Window"; ); w, gl_ctx let create_window_vulkan ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr = let w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ |> get_w_ptr in if not @@ Ffi.init_for_vulkan w then ( failwith "failed during initialization of vulkan SDL_Window"; ); w let new_frame = Ffi.new_frame let process_event = Ffi.process_event let shutdown = Ffi.shutdown
null
https://raw.githubusercontent.com/imandra-ai/ocaml-cimgui/55c71078705099ea60d91630610f6d750fd07abb/src/sys/sdl2/Imgui_sys_sdl2.ml
ocaml
* Cast: get a window pointer * Cast: get a unit pointer * Cast: get a unit pointer TODO: provide these flags somewhere else
open Ctypes open Tsdl module Types = Imgui_sdl2_ffi_f.Types module Ffi = Imgui_sdl2_ffi_f.Make(Imgui_sdl2_generated_funs) let unwrap_ = function | Ok x -> x | Error (`Msg e) -> failwith @@ "sdl error " ^ e let get_w_ptr (w:Sdl.window) : Types.window ptr = Ctypes.coerce (ptr void) (ptr Types.window) @@ ptr_of_raw_address @@ Sdl.unsafe_ptr_of_window w let get_gl_ctx (ctx:Sdl.gl_context) : unit ptr = ptr_of_raw_address @@ Sdl.unsafe_ptr_of_gl_context ctx let get_sdl_event (e:Sdl.event) : Types.event ptr = addr (Obj.magic e : Types.event) FIXME ! ! ! need upstream support from Tsdl Ctypes.coerce ( ptr void ) ( ptr Types.event ) @@ Ctypes.coerce ( ptr Tsdl.Sdl.event ) ( ptr void ) @@ e Ctypes.coerce (ptr void) (ptr Types.event) @@ Ctypes.coerce (ptr Tsdl.Sdl.event) (ptr void) @@ e *) let create_window_d3d ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr = let w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ |> get_w_ptr in if not @@ Ffi.init_for_d3d w then ( failwith "failed during initialization of D3D SDL_Window"; ); w * @param gl_ctx the openGL context let create_window_opengl ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr * Sdl.gl_context = let flags = Sdl.Window.(flags + opengl + resizable + allow_highdpi) in let sdl_w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ in let w = get_w_ptr sdl_w in let gl_ctx = Sdl.gl_create_context sdl_w |> unwrap_ in Sdl.gl_make_current sdl_w gl_ctx |> unwrap_; if get_gl_ctx gl_ctx |> is_null then failwith "sdl init: gl_context is null"; if not @@ Ffi.init_for_opengl w (get_gl_ctx gl_ctx) then ( failwith "failed during initialization of openGL SDL_Window"; ); w, gl_ctx let create_window_vulkan ?(w=800) ?(h=800) (flags:Sdl.Window.flags) : Types.window ptr = let w = Sdl.create_window "sdl" ~w ~h flags |> unwrap_ |> get_w_ptr in if not @@ Ffi.init_for_vulkan w then ( failwith "failed during initialization of vulkan SDL_Window"; ); w let new_frame = Ffi.new_frame let process_event = Ffi.process_event let shutdown = Ffi.shutdown
41cdfd14da6be3227ffd5a4d233866858c420d951bec46326676b6c28aba70fa
grin-compiler/ghc-wpc-sample-programs
Impl.hs
----------------------------------------------------------------------------- -- | -- Module : Text.Regex.Impl Copyright : ( c ) 2006 SPDX - License - Identifier : BSD-3 - Clause -- -- Maintainer : -- Stability : experimental -- Portability : non-portable (Text.Regex.Base needs MPTC+FD) -- -- Helper functions for defining certain instances of RegexContext . These help when defining instances of RegexContext -- with repeated types: -- -- @ instance ( RegexLike regex source ) = > RegexContext regex source source where -- @ -- -- runs into overlapping restrictions. To avoid this I have each backend define , for its own Regex type : -- -- @ -- instance RegexContext Regex String String where match = polymatch -- matchM = polymatchM -- @ -- -- @ instance RegexContext Regex ByteString ByteString where match = polymatch -- matchM = polymatchM -- @ -- -- @ -- instance RegexContext Regex Text Text where match = polymatch -- matchM = polymatchM -- @ ------------------------------------------------------------------------------- module Text.Regex.Base.Impl(polymatch,polymatchM) where import Prelude hiding (fail) import Control.Monad.Fail (MonadFail(fail)) import Text.Regex.Base import Data.Array((!)) regexFailed :: (MonadFail m) => m b # INLINE regexFailed # regexFailed = fail $ "regex failed to match" actOn :: (RegexLike r s,MonadFail m) => ((s,MatchText s,s)->t) -> r -> s -> m t # INLINE actOn # actOn f r s = case matchOnceText r s of Nothing -> regexFailed Just preMApost -> return (f preMApost) polymatch :: (RegexLike a b) => a -> b -> b # INLINE polymatch # polymatch r s = case matchOnceText r s of Nothing -> empty Just (_,ma,_) -> fst (ma!0) polymatchM :: (RegexLike a b,MonadFail m) => a -> b -> m b # INLINE polymatchM # polymatchM = actOn (\(_,ma,_)->fst (ma!0))
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/regex-base-0.94.0.0/src/Text/Regex/Base/Impl.hs
haskell
--------------------------------------------------------------------------- | Module : Text.Regex.Impl Maintainer : Stability : experimental Portability : non-portable (Text.Regex.Base needs MPTC+FD) Helper functions for defining certain instances of with repeated types: @ @ runs into overlapping restrictions. To avoid this I have each backend @ instance RegexContext Regex String String where matchM = polymatchM @ @ matchM = polymatchM @ @ instance RegexContext Regex Text Text where matchM = polymatchM @ -----------------------------------------------------------------------------
Copyright : ( c ) 2006 SPDX - License - Identifier : BSD-3 - Clause RegexContext . These help when defining instances of RegexContext instance ( RegexLike regex source ) = > RegexContext regex source source where define , for its own Regex type : match = polymatch instance RegexContext Regex ByteString ByteString where match = polymatch match = polymatch module Text.Regex.Base.Impl(polymatch,polymatchM) where import Prelude hiding (fail) import Control.Monad.Fail (MonadFail(fail)) import Text.Regex.Base import Data.Array((!)) regexFailed :: (MonadFail m) => m b # INLINE regexFailed # regexFailed = fail $ "regex failed to match" actOn :: (RegexLike r s,MonadFail m) => ((s,MatchText s,s)->t) -> r -> s -> m t # INLINE actOn # actOn f r s = case matchOnceText r s of Nothing -> regexFailed Just preMApost -> return (f preMApost) polymatch :: (RegexLike a b) => a -> b -> b # INLINE polymatch # polymatch r s = case matchOnceText r s of Nothing -> empty Just (_,ma,_) -> fst (ma!0) polymatchM :: (RegexLike a b,MonadFail m) => a -> b -> m b # INLINE polymatchM # polymatchM = actOn (\(_,ma,_)->fst (ma!0))
0a6194efda44749092136d3a1d0d286c322a6b5d04655bc580ec0b9fc96b9e45
janestreet/bonsai
default_legend.ml
open Core open Import module Model = struct module Series = struct type t = { label : string ; value : Raw_html.t option ; dash : Raw_html.t option ; color : string option ; is_visible : bool ; is_highlighted : bool } [@@deriving equal, fields, sexp] let toggle_visibility t = { t with is_visible = not t.is_visible } let view { label; value; dash; color; is_visible; is_highlighted } ~on_toggle = let dash = match dash with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in let value = match value with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in let create_style l = List.filter_opt l |> Css_gen.concat |> Vdom.Attr.style in let label_style = let margin_left = Css_gen.margin_left (`Px 5) in let color = Option.map color ~f:(fun value -> Css_gen.create ~field:"color" ~value) in create_style [ color; Some margin_left ] in let style = create_style [ Option.some_if is_highlighted (Css_gen.font_weight `Bold) ; Option.some_if is_highlighted (Css_gen.text_decoration () ~line:[ `Underline ]) ] in Vdom.Node.label ~attr:style [ Vdom.Node.input ~attr: (Vdom.Attr.many_without_merge [ Vdom.Attr.type_ "checkbox" ; Vdom.Attr.on_click (fun _ev -> on_toggle ()) ; Vdom.Attr.bool_property "checked" is_visible ]) () ; dash ; Vdom.Node.span ~attr:label_style [ Vdom.Node.textf "%s: " label ] ; value ] ;; end type t = { x_label : string ; x_value : Raw_html.t option ; series : Series.t list ; past_series : Series.t Map.M(String).t } [@@deriving equal, sexp] let view { x_label; x_value; series; past_series = _ } ~on_toggle ~select_all ~select_none = let x = let value = match x_value with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in Vdom.Node.label [ Vdom.Node.textf "%s: " x_label; value ] in (* mostly copied from bonsai_multi_select *) let select_all_or_none = let open Vdom in let link ~text ~action ~class_ = Node.a ~attr: (Vdom.Attr.many_without_merge [ Attr.href "about:blank" ; Attr.on_click (fun _ev -> Effect.Many [ action (); Effect.Prevent_default ]) ; Attr.class_ class_ ]) [ Node.text text ] in Node.div ~attr:(Attr.class_ "multi-select-select-all-none") [ Node.text "Select: " ; link ~text:"all" ~action:select_all ~class_:"multi-select-select-all" ; Node.text "; " ; link ~text:"none" ~action:select_none ~class_:"multi-select-select-none" ] in let list_elements = select_all_or_none :: x :: List.map series ~f:(fun series -> Series.view series ~on_toggle:(fun () -> on_toggle series.label)) in (* Mostly copied from vdom_input_widgets *) Vdom.Node.div ~attr: (Vdom.Attr.many_without_merge [ Vdom.Attr.classes [ "widget-checklist"; "checkbox-container" ] ; Vdom.Attr.style Css_gen.(create ~field:"list-style" ~value:"none" @> margin_left (`Px 0)) ]) (List.map list_elements ~f:(fun li -> Vdom.Node.div [ li ])) ;; end module Action = struct type t = | From_graph of Legend_data.t | Toggle_visibility of string | Select_none | Select_all [@@deriving equal, sexp] end let apply_action ~inject:_ ~schedule_event:_ (model : Model.t) (action : Action.t) = let map_series ~f = { model with series = List.map model.series ~f } in match action with | From_graph legend_data -> let series = List.map model.series ~f:(fun series -> match List.find legend_data.series ~f:(fun s -> String.equal series.label s.label) with | None -> series | Some legend_data -> let { Legend_data.Series.dashHTML ; isHighlighted ; color ; yHTML ; label = _ ; labelHTML = _ ; isVisible = _ ; y = _ } = legend_data in let color = (* keep last color if [color] is none *) Option.first_some color series.color in { series with dash = Some dashHTML ; color ; value = yHTML ; is_highlighted = Option.value ~default:false isHighlighted }) in let x_value = Option.map legend_data.xHTML ~f:(function | `number f -> Float.to_string f |> Raw_html.of_string | `html raw_html -> raw_html) in { model with x_value; series } | Select_none -> map_series ~f:(fun series -> { series with is_visible = false }) | Select_all -> map_series ~f:(fun series -> { series with is_visible = true }) | Toggle_visibility label -> map_series ~f:(fun series -> if String.(series.label = label) then Model.Series.toggle_visibility series else series) ;; let series_from_info { Per_series_info.label; visible_by_default } = { Model.Series.label ; is_visible = visible_by_default ; is_highlighted = false ; value = None ; dash = None ; color = None } ;; let create ~x_label ~per_series_info : (Model.t * Vdom.Node.t * (Action.t -> unit Vdom.Effect.t)) Bonsai.Computation.t = let create_model = let%map.Bonsai x_label = x_label and per_series_info = per_series_info in function | None -> { Model.x_label ; x_value = None ; series = List.map per_series_info ~f:series_from_info ; past_series = String.Map.empty } | Some (model : Model.t) -> let existing_y_labels = List.map model.series ~f:Model.Series.label in let model_y_labels = List.map per_series_info ~f:Per_series_info.label in if [%equal: string ] model.x_label x_label && [%equal: string list] model_y_labels existing_y_labels then { model with x_label } else ( let past_series = (* Every time the [model_y_labels] changes, we want to remember the visibility status of all the series labels we know about so far. This will help in the case where we toggle visibility on series A, flip to a graph which does not have that series, and then flip back to the original graph. Without remembering, the visibility status of series A revert back to the default status. *) List.fold ~init:model.past_series model.series ~f:(fun past_series series -> Map.set past_series ~key:series.label ~data:series) in let series = List.map per_series_info ~f:(fun per_series_info -> let { Per_series_info.label; visible_by_default = _ } = per_series_info in match Map.find past_series label with | None -> series_from_info per_series_info | Some series -> series) in { model with x_label; series; past_series }) in let%sub state = Bonsai_extra.state_machine0_dynamic_model (module Model ) (module Action) ~model:(`Computed create_model) ~apply_action in return @@ let%map model, inject_action = state in let view = Model.view model ~on_toggle:(fun label -> inject_action (Toggle_visibility label)) ~select_all:(fun () -> inject_action Select_all) ~select_none:(fun () -> inject_action Select_none) in model, view, inject_action ;;
null
https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/bindings/dygraph/src/default_legend.ml
ocaml
mostly copied from bonsai_multi_select Mostly copied from vdom_input_widgets keep last color if [color] is none Every time the [model_y_labels] changes, we want to remember the visibility status of all the series labels we know about so far. This will help in the case where we toggle visibility on series A, flip to a graph which does not have that series, and then flip back to the original graph. Without remembering, the visibility status of series A revert back to the default status.
open Core open Import module Model = struct module Series = struct type t = { label : string ; value : Raw_html.t option ; dash : Raw_html.t option ; color : string option ; is_visible : bool ; is_highlighted : bool } [@@deriving equal, fields, sexp] let toggle_visibility t = { t with is_visible = not t.is_visible } let view { label; value; dash; color; is_visible; is_highlighted } ~on_toggle = let dash = match dash with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in let value = match value with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in let create_style l = List.filter_opt l |> Css_gen.concat |> Vdom.Attr.style in let label_style = let margin_left = Css_gen.margin_left (`Px 5) in let color = Option.map color ~f:(fun value -> Css_gen.create ~field:"color" ~value) in create_style [ color; Some margin_left ] in let style = create_style [ Option.some_if is_highlighted (Css_gen.font_weight `Bold) ; Option.some_if is_highlighted (Css_gen.text_decoration () ~line:[ `Underline ]) ] in Vdom.Node.label ~attr:style [ Vdom.Node.input ~attr: (Vdom.Attr.many_without_merge [ Vdom.Attr.type_ "checkbox" ; Vdom.Attr.on_click (fun _ev -> on_toggle ()) ; Vdom.Attr.bool_property "checked" is_visible ]) () ; dash ; Vdom.Node.span ~attr:label_style [ Vdom.Node.textf "%s: " label ] ; value ] ;; end type t = { x_label : string ; x_value : Raw_html.t option ; series : Series.t list ; past_series : Series.t Map.M(String).t } [@@deriving equal, sexp] let view { x_label; x_value; series; past_series = _ } ~on_toggle ~select_all ~select_none = let x = let value = match x_value with | None -> Vdom.Node.none | Some html -> Raw_html.view ~tag:"span" html in Vdom.Node.label [ Vdom.Node.textf "%s: " x_label; value ] in let select_all_or_none = let open Vdom in let link ~text ~action ~class_ = Node.a ~attr: (Vdom.Attr.many_without_merge [ Attr.href "about:blank" ; Attr.on_click (fun _ev -> Effect.Many [ action (); Effect.Prevent_default ]) ; Attr.class_ class_ ]) [ Node.text text ] in Node.div ~attr:(Attr.class_ "multi-select-select-all-none") [ Node.text "Select: " ; link ~text:"all" ~action:select_all ~class_:"multi-select-select-all" ; Node.text "; " ; link ~text:"none" ~action:select_none ~class_:"multi-select-select-none" ] in let list_elements = select_all_or_none :: x :: List.map series ~f:(fun series -> Series.view series ~on_toggle:(fun () -> on_toggle series.label)) in Vdom.Node.div ~attr: (Vdom.Attr.many_without_merge [ Vdom.Attr.classes [ "widget-checklist"; "checkbox-container" ] ; Vdom.Attr.style Css_gen.(create ~field:"list-style" ~value:"none" @> margin_left (`Px 0)) ]) (List.map list_elements ~f:(fun li -> Vdom.Node.div [ li ])) ;; end module Action = struct type t = | From_graph of Legend_data.t | Toggle_visibility of string | Select_none | Select_all [@@deriving equal, sexp] end let apply_action ~inject:_ ~schedule_event:_ (model : Model.t) (action : Action.t) = let map_series ~f = { model with series = List.map model.series ~f } in match action with | From_graph legend_data -> let series = List.map model.series ~f:(fun series -> match List.find legend_data.series ~f:(fun s -> String.equal series.label s.label) with | None -> series | Some legend_data -> let { Legend_data.Series.dashHTML ; isHighlighted ; color ; yHTML ; label = _ ; labelHTML = _ ; isVisible = _ ; y = _ } = legend_data in let color = Option.first_some color series.color in { series with dash = Some dashHTML ; color ; value = yHTML ; is_highlighted = Option.value ~default:false isHighlighted }) in let x_value = Option.map legend_data.xHTML ~f:(function | `number f -> Float.to_string f |> Raw_html.of_string | `html raw_html -> raw_html) in { model with x_value; series } | Select_none -> map_series ~f:(fun series -> { series with is_visible = false }) | Select_all -> map_series ~f:(fun series -> { series with is_visible = true }) | Toggle_visibility label -> map_series ~f:(fun series -> if String.(series.label = label) then Model.Series.toggle_visibility series else series) ;; let series_from_info { Per_series_info.label; visible_by_default } = { Model.Series.label ; is_visible = visible_by_default ; is_highlighted = false ; value = None ; dash = None ; color = None } ;; let create ~x_label ~per_series_info : (Model.t * Vdom.Node.t * (Action.t -> unit Vdom.Effect.t)) Bonsai.Computation.t = let create_model = let%map.Bonsai x_label = x_label and per_series_info = per_series_info in function | None -> { Model.x_label ; x_value = None ; series = List.map per_series_info ~f:series_from_info ; past_series = String.Map.empty } | Some (model : Model.t) -> let existing_y_labels = List.map model.series ~f:Model.Series.label in let model_y_labels = List.map per_series_info ~f:Per_series_info.label in if [%equal: string ] model.x_label x_label && [%equal: string list] model_y_labels existing_y_labels then { model with x_label } else ( let past_series = List.fold ~init:model.past_series model.series ~f:(fun past_series series -> Map.set past_series ~key:series.label ~data:series) in let series = List.map per_series_info ~f:(fun per_series_info -> let { Per_series_info.label; visible_by_default = _ } = per_series_info in match Map.find past_series label with | None -> series_from_info per_series_info | Some series -> series) in { model with x_label; series; past_series }) in let%sub state = Bonsai_extra.state_machine0_dynamic_model (module Model ) (module Action) ~model:(`Computed create_model) ~apply_action in return @@ let%map model, inject_action = state in let view = Model.view model ~on_toggle:(fun label -> inject_action (Toggle_visibility label)) ~select_all:(fun () -> inject_action Select_all) ~select_none:(fun () -> inject_action Select_none) in model, view, inject_action ;;
9251a7b80208ee1b06ee465692f4f0e638efa510c765da23dedf1b1e71c5d32f
klutometis/clrs
quicksort.scm
(define (quicksort-general! vector p r partition!) (if (< p r) (let ((q (partition! vector p r))) (quicksort-general! vector p (- q 1) partition!) (quicksort-general! vector (+ q 1) r partition!)))) (define (quicksort! vector p r) (quicksort-general! vector p r partition!)) (define (partition-general! vector p r comparator pivot-index) (if (not (= pivot-index r)) (vector-swap! vector pivot-index r)) (let ((pivot (vector-ref vector r))) (loop continue ((for x i (in-vector vector p r)) (with j p)) => (begin (vector-swap! vector j r) j) (if (comparator x pivot) (begin (vector-swap! vector i j) (continue (=> j (+ j 1)))) (continue))))) (define (partition! vector p r) (partition-general! vector p r <= r))
null
https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/7.1/quicksort.scm
scheme
(define (quicksort-general! vector p r partition!) (if (< p r) (let ((q (partition! vector p r))) (quicksort-general! vector p (- q 1) partition!) (quicksort-general! vector (+ q 1) r partition!)))) (define (quicksort! vector p r) (quicksort-general! vector p r partition!)) (define (partition-general! vector p r comparator pivot-index) (if (not (= pivot-index r)) (vector-swap! vector pivot-index r)) (let ((pivot (vector-ref vector r))) (loop continue ((for x i (in-vector vector p r)) (with j p)) => (begin (vector-swap! vector j r) j) (if (comparator x pivot) (begin (vector-swap! vector i j) (continue (=> j (+ j 1)))) (continue))))) (define (partition! vector p r) (partition-general! vector p r <= r))
faaa478291830a2853995ff947c36a69b5b2c16b9680e877108fb41727a74723
KingMob/clojure-trie-performance
trie09.clj
(ns modulo-lotus.trie.trie09 (:require [clojure.string :refer (split triml)] [modulo-lotus.trie.helpers :refer [alpha-idx]] [modulo-lotus.trie.trie-node :as tr :refer [TrieNode add-substring count-w-prefix count-words prefix]] [taoensso.tufte :as tufte :refer (defnp p profiled profile)]) (:import [java.util Arrays])) ;; Like 07, but remove reflection and type hint more (set! *warn-on-reflection* true) (declare default-alphabet-trie-node) (defn add-substring-1 [^AlphabetTrieNode n ^chars cs] (set! word-count (inc word-count)) (let [^chars cs s clen (alength cs)] (if (> clen 0) (set! terminates? (boolean true)) (let [c (aget cs 0) i (int (alpha-idx c)) child (aget children i)] (when-not child (aset children i (default-alphabet-trie-node))) (add-substring (aget children i) (Arrays/copyOfRange cs 1 clen)))))) (deftype AlphabetTrieNode [^:unsynchronized-mutable ^boolean terminates? ^:unsynchronized-mutable ^long word-count ^:unsychronized-mutable ^objects children] TrieNode (add-substring [n s] (set! word-count (inc word-count)) (let [^chars cs s clen (alength cs)] (if (> clen 0) (set! terminates? (boolean true)) (let [c (aget cs 0) i (int (alpha-idx c)) child (aget children i)] (when-not child (aset children i (default-alphabet-trie-node))) (add-substring (aget children i) (Arrays/copyOfRange cs 1 clen)))))) (prefix [n s] (let [^chars cs s clen (alength cs)] (loop [curr n cidx 0] (if (and (< cidx clen) (some? curr)) (recur (aget ^objects (.children curr) (alpha-idx (aget cs cidx))) (inc cidx)) curr)))) (count-words [n] word-count) (count-w-prefix [n s] (if-let [subn (prefix n s)] (count-words subn) 0))) (defn empty-alphabet-vector [] (make-array AlphabetTrieNode 26)) (defn default-alphabet-trie-node [] (->AlphabetTrieNode (boolean false) 0 (empty-alphabet-vector))) (defn process-op [db op contact] (let [cs (char-array contact)] (if (= "add" op) (add-substring db cs) (println (count-w-prefix db cs))))) (defn run [] (let [n (Integer/parseInt (read-line)) db (default-alphabet-trie-node)] (loop [i n] (when (> i 0) (let [[op contact] (split (read-line) #"\s+")] (process-op db op contact) (recur (dec i)))))) (flush))
null
https://raw.githubusercontent.com/KingMob/clojure-trie-performance/4c0c77799a0763c670fdde70b737e0af936a2bb8/src/modulo_lotus/trie/trie09.clj
clojure
Like 07, but remove reflection and type hint more
(ns modulo-lotus.trie.trie09 (:require [clojure.string :refer (split triml)] [modulo-lotus.trie.helpers :refer [alpha-idx]] [modulo-lotus.trie.trie-node :as tr :refer [TrieNode add-substring count-w-prefix count-words prefix]] [taoensso.tufte :as tufte :refer (defnp p profiled profile)]) (:import [java.util Arrays])) (set! *warn-on-reflection* true) (declare default-alphabet-trie-node) (defn add-substring-1 [^AlphabetTrieNode n ^chars cs] (set! word-count (inc word-count)) (let [^chars cs s clen (alength cs)] (if (> clen 0) (set! terminates? (boolean true)) (let [c (aget cs 0) i (int (alpha-idx c)) child (aget children i)] (when-not child (aset children i (default-alphabet-trie-node))) (add-substring (aget children i) (Arrays/copyOfRange cs 1 clen)))))) (deftype AlphabetTrieNode [^:unsynchronized-mutable ^boolean terminates? ^:unsynchronized-mutable ^long word-count ^:unsychronized-mutable ^objects children] TrieNode (add-substring [n s] (set! word-count (inc word-count)) (let [^chars cs s clen (alength cs)] (if (> clen 0) (set! terminates? (boolean true)) (let [c (aget cs 0) i (int (alpha-idx c)) child (aget children i)] (when-not child (aset children i (default-alphabet-trie-node))) (add-substring (aget children i) (Arrays/copyOfRange cs 1 clen)))))) (prefix [n s] (let [^chars cs s clen (alength cs)] (loop [curr n cidx 0] (if (and (< cidx clen) (some? curr)) (recur (aget ^objects (.children curr) (alpha-idx (aget cs cidx))) (inc cidx)) curr)))) (count-words [n] word-count) (count-w-prefix [n s] (if-let [subn (prefix n s)] (count-words subn) 0))) (defn empty-alphabet-vector [] (make-array AlphabetTrieNode 26)) (defn default-alphabet-trie-node [] (->AlphabetTrieNode (boolean false) 0 (empty-alphabet-vector))) (defn process-op [db op contact] (let [cs (char-array contact)] (if (= "add" op) (add-substring db cs) (println (count-w-prefix db cs))))) (defn run [] (let [n (Integer/parseInt (read-line)) db (default-alphabet-trie-node)] (loop [i n] (when (> i 0) (let [[op contact] (split (read-line) #"\s+")] (process-op db op contact) (recur (dec i)))))) (flush))
baa33e02324e0d5d7e91a126f7cfe546a23a06bef59606a9f0a1eba897a23f91
joaopaulomoraes/7-days-of-clojure
numbers.clj
(ns seven-days-of-clojure.numbers) (+ 1 1 2 3 5 8) (- 1 1 2 3 5 8) (* 1 2 (* 5 8) 13) (/ 135 3) (mod 3 2) (min 21 13 8 5 3 2 1 1) (max 1 1 2 3 5 8 13 21)
null
https://raw.githubusercontent.com/joaopaulomoraes/7-days-of-clojure/ef26ca84f6e149ea44bdac13ef2e391e735b8347/day2/numbers.clj
clojure
(ns seven-days-of-clojure.numbers) (+ 1 1 2 3 5 8) (- 1 1 2 3 5 8) (* 1 2 (* 5 8) 13) (/ 135 3) (mod 3 2) (min 21 13 8 5 3 2 1 1) (max 1 1 2 3 5 8 13 21)
5eefa4eada3d48928ae0a3e1dfcac53918b45bd0ec2e5157153faee0753b3baa
fractalide/fractalide
sidebar.rkt
#lang racket (require racket/draw) (require racket/runtime-path) (require fractalide/modules/rkt/rkt-fbp/graph) (define-runtime-path cantor-logo-path "cantor-logo-min.png") (define cantor-logo (read-bitmap cantor-logo-path)) (define-graph (node "vp" ${gui.vertical-panel}) (edge-out "vp" "out" "out") (node "headline" ${gui.message}) (edge "headline" "out" _ "vp" "place" 0) (mesg "headline" "in" `(init . ((label . ,cantor-logo)))) (node "wallets-choice" ${cardano-wallet.wallets-choice}) (edge "wallets-choice" "out" _ "vp" "place" 5) (edge-in "in" "wallets-choice" "in") (edge-in "init" "wallets-choice" "init") (node "wallet-data-in" ${plumbing.mux-demux}) (mesg "wallet-data-in" "option" (match-lambda [(cons "wallet-name" new-name) (list (cons "edit" `#hash((name . ,new-name))))] [(cons "delete" _) (list (cons "delete" #t))])) (edge "wallet-data-in" "out" "edit" "wallets-choice" "edit" _) (edge "wallet-data-in" "out" "delete" "wallets-choice" "delete" _) (edge "wallet-data-in" "out" "init" "wallets-choice" "init" _) (edge-in "data" "wallet-data-in" "in") (node "wallet-data-out" ${plumbing.demux}) (mesg "wallet-data-out" "option" (lambda (data) (list (cons "wallet-name" (hash-ref data 'name))))) (edge "wallets-choice" "choice" _ "wallet-data-out" "in" _) (edge-out "wallet-data-out" "out" "data") (node "button-pushes" ${plumbing.mux}) (edge-out "button-pushes" "out" "choice") (node "summary" ${gui.button}) (edge "summary" "out" _ "vp" "place" 10) (edge "summary" "out" 'button "button-pushes" "in" "summary") (mesg "summary" "in" '(init . ((label . "Summary")))) (node "send" ${gui.button}) (edge "send" "out" _ "vp" "place" 20) (edge "send" "out" 'button "button-pushes" "in" "send") (mesg "send" "in" '(init . ((label . "Send")))) (node "receive" ${gui.button}) (edge "receive" "out" _ "vp" "place" 30) (edge "receive" "out" 'button "button-pushes" "in" "receive") (mesg "receive" "in" '(init . ((label . "Receive")))) (node "transactions" ${gui.button}) (edge "transactions" "out" _ "vp" "place" 40) (edge "transactions" "out" 'button "button-pushes" "in" "transactions") (mesg "transactions" "in" '(init . ((label . "Transactions")))) (node "wsettings" ${gui.button}) (edge "wsettings" "out" _ "vp" "place" 50) (edge "wsettings" "out" 'button "button-pushes" "in" "wsettings") (mesg "wsettings" "in" '(init . ((label . "Wallet settings")))) (node "new" ${gui.button}) (edge "new" "out" _ "vp" "place" 60) (edge "new" "out" 'button "button-pushes" "in" "new") (mesg "new" "in" '(init . ((label . "New wallet")))) (node "asettings" ${gui.button}) (edge "asettings" "out" _ "vp" "place" 70) (edge "asettings" "out" 'button "button-pushes" "in" "asettings") (mesg "asettings" "in" '(init . ((label . "App settings")))))
null
https://raw.githubusercontent.com/fractalide/fractalide/9c54ec2615fcc2a1f3363292d4eed2a0fcb9c3a5/modules/rkt/rkt-fbp/agents/cardano-wallet/sidebar.rkt
racket
#lang racket (require racket/draw) (require racket/runtime-path) (require fractalide/modules/rkt/rkt-fbp/graph) (define-runtime-path cantor-logo-path "cantor-logo-min.png") (define cantor-logo (read-bitmap cantor-logo-path)) (define-graph (node "vp" ${gui.vertical-panel}) (edge-out "vp" "out" "out") (node "headline" ${gui.message}) (edge "headline" "out" _ "vp" "place" 0) (mesg "headline" "in" `(init . ((label . ,cantor-logo)))) (node "wallets-choice" ${cardano-wallet.wallets-choice}) (edge "wallets-choice" "out" _ "vp" "place" 5) (edge-in "in" "wallets-choice" "in") (edge-in "init" "wallets-choice" "init") (node "wallet-data-in" ${plumbing.mux-demux}) (mesg "wallet-data-in" "option" (match-lambda [(cons "wallet-name" new-name) (list (cons "edit" `#hash((name . ,new-name))))] [(cons "delete" _) (list (cons "delete" #t))])) (edge "wallet-data-in" "out" "edit" "wallets-choice" "edit" _) (edge "wallet-data-in" "out" "delete" "wallets-choice" "delete" _) (edge "wallet-data-in" "out" "init" "wallets-choice" "init" _) (edge-in "data" "wallet-data-in" "in") (node "wallet-data-out" ${plumbing.demux}) (mesg "wallet-data-out" "option" (lambda (data) (list (cons "wallet-name" (hash-ref data 'name))))) (edge "wallets-choice" "choice" _ "wallet-data-out" "in" _) (edge-out "wallet-data-out" "out" "data") (node "button-pushes" ${plumbing.mux}) (edge-out "button-pushes" "out" "choice") (node "summary" ${gui.button}) (edge "summary" "out" _ "vp" "place" 10) (edge "summary" "out" 'button "button-pushes" "in" "summary") (mesg "summary" "in" '(init . ((label . "Summary")))) (node "send" ${gui.button}) (edge "send" "out" _ "vp" "place" 20) (edge "send" "out" 'button "button-pushes" "in" "send") (mesg "send" "in" '(init . ((label . "Send")))) (node "receive" ${gui.button}) (edge "receive" "out" _ "vp" "place" 30) (edge "receive" "out" 'button "button-pushes" "in" "receive") (mesg "receive" "in" '(init . ((label . "Receive")))) (node "transactions" ${gui.button}) (edge "transactions" "out" _ "vp" "place" 40) (edge "transactions" "out" 'button "button-pushes" "in" "transactions") (mesg "transactions" "in" '(init . ((label . "Transactions")))) (node "wsettings" ${gui.button}) (edge "wsettings" "out" _ "vp" "place" 50) (edge "wsettings" "out" 'button "button-pushes" "in" "wsettings") (mesg "wsettings" "in" '(init . ((label . "Wallet settings")))) (node "new" ${gui.button}) (edge "new" "out" _ "vp" "place" 60) (edge "new" "out" 'button "button-pushes" "in" "new") (mesg "new" "in" '(init . ((label . "New wallet")))) (node "asettings" ${gui.button}) (edge "asettings" "out" _ "vp" "place" 70) (edge "asettings" "out" 'button "button-pushes" "in" "asettings") (mesg "asettings" "in" '(init . ((label . "App settings")))))
6f1b4697c0cd10dcb72add30a92cd833672aca958d3a5332fd6f6848fba8371f
thosmos/riverdb
ui.cljc
(ns riverdb.ui (:require [clojure.string :as str] [edn-query-language.core :as eql] [riverdb.model :as model] [riverdb.model.person :as person] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.algorithms.form-state :as fs] #?(:clj [com.fulcrologic.fulcro.dom-server :as dom :refer [div label input]] :cljs [com.fulcrologic.fulcro.dom :as dom :refer [div label input]]) [com.fulcrologic.rad.authorization :as auth] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.ids :refer [new-uuid]] [com.fulcrologic.rad.rendering.semantic-ui.components :refer [ui-wrapped-dropdown]] [com.fulcrologic.rad.report :as report] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr :refer [defrouter]] [com.fulcrologic.rad.type-support.decimal :as math] [com.fulcrologic.rad.type-support.date-time :as datetime])) (form/defsc-form PersonForm [this props] {::form/id person/uid ::form/attributes [person/uid person/Name person/IsStaff person/Agency] ::form/default {:person/IsStaff false} ::form/enumeration-order :person/Name ::form/cancel-route ["people"] ::form/route-prefix "person" ::form/title "Edit Person" ::form/layout [[:person/Name :person/Agency :person/IsStaff]] ::form/subforms {:person/Agency {::form/ui form/ToOneEntityPicker ::form/pick-one {:options/query-key :org.riverdb.db.agencylookup :options/params {:limit -1 :filter {:agencylookup/Active true}} :options/subquery [:agencylookup/uuid :agencylookup/AgencyCode] :options/transform (fn [{:agencylookup/keys [uuid AgencyCode]}] {:text AgencyCode :value [:agencylookup/uuid uuid]})} ::form/label "Agency" ;; Use computed props to inform subform of its role. ::form/subform-style :inline}}}) ;(def account-validator (fs/make-validator (fn [form field] ; (case field ; :account/email (let [prefix (or ; (some-> form ; (get :account/name) ( str / split # " \s " ) ( first ) ; (str/lower-case)) ; "")] ; (str/starts-with? (get form field) prefix)) ; (= :valid (model/all-attribute-validator form field)))))) (defsc PersonListItem [this {:person/keys [uuid Name Agency IsStaff] :as props}] {::report/columns [:person/Name :person/Agency :person/IsStaff] ::report/column-headings ["Name" "Agency" "IsStaff"] ::report/row-actions {:delete (fn [this id] (form/delete! this :person/uuid id))} ::report/edit-form PersonForm :query [:person/uuid :person/Name :person/IsStaff :person/Agency] :ident :person/uuid} #_(dom/div :.item (dom/i :.large.github.middle.aligned.icon) (div :.content (dom/a :.header {:onClick (fn [] (form/edit! this AccountForm id))} name) (dom/div :.description (str (if active? "Active" "Inactive") ". Last logged in " last-login))))) (def ui-person-list-item (comp/factory PersonListItem {:keyfn :person/uuid})) (report/defsc-report PersonList [this props] {::report/BodyItem PersonListItem ::report/source-attribute :org.riverdb.db.person ::report/parameters {} ::report/route "people"})
null
https://raw.githubusercontent.com/thosmos/riverdb/b47f01a938da26298ee7924c8b2b3a2be5371927/src/rad/riverdb/ui.cljc
clojure
Use computed props to inform subform of its role. (def account-validator (fs/make-validator (fn [form field] (case field :account/email (let [prefix (or (some-> form (get :account/name) (str/lower-case)) "")] (str/starts-with? (get form field) prefix)) (= :valid (model/all-attribute-validator form field))))))
(ns riverdb.ui (:require [clojure.string :as str] [edn-query-language.core :as eql] [riverdb.model :as model] [riverdb.model.person :as person] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.algorithms.form-state :as fs] #?(:clj [com.fulcrologic.fulcro.dom-server :as dom :refer [div label input]] :cljs [com.fulcrologic.fulcro.dom :as dom :refer [div label input]]) [com.fulcrologic.rad.authorization :as auth] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.ids :refer [new-uuid]] [com.fulcrologic.rad.rendering.semantic-ui.components :refer [ui-wrapped-dropdown]] [com.fulcrologic.rad.report :as report] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr :refer [defrouter]] [com.fulcrologic.rad.type-support.decimal :as math] [com.fulcrologic.rad.type-support.date-time :as datetime])) (form/defsc-form PersonForm [this props] {::form/id person/uid ::form/attributes [person/uid person/Name person/IsStaff person/Agency] ::form/default {:person/IsStaff false} ::form/enumeration-order :person/Name ::form/cancel-route ["people"] ::form/route-prefix "person" ::form/title "Edit Person" ::form/layout [[:person/Name :person/Agency :person/IsStaff]] ::form/subforms {:person/Agency {::form/ui form/ToOneEntityPicker ::form/pick-one {:options/query-key :org.riverdb.db.agencylookup :options/params {:limit -1 :filter {:agencylookup/Active true}} :options/subquery [:agencylookup/uuid :agencylookup/AgencyCode] :options/transform (fn [{:agencylookup/keys [uuid AgencyCode]}] {:text AgencyCode :value [:agencylookup/uuid uuid]})} ::form/label "Agency" ::form/subform-style :inline}}}) ( str / split # " \s " ) ( first ) (defsc PersonListItem [this {:person/keys [uuid Name Agency IsStaff] :as props}] {::report/columns [:person/Name :person/Agency :person/IsStaff] ::report/column-headings ["Name" "Agency" "IsStaff"] ::report/row-actions {:delete (fn [this id] (form/delete! this :person/uuid id))} ::report/edit-form PersonForm :query [:person/uuid :person/Name :person/IsStaff :person/Agency] :ident :person/uuid} #_(dom/div :.item (dom/i :.large.github.middle.aligned.icon) (div :.content (dom/a :.header {:onClick (fn [] (form/edit! this AccountForm id))} name) (dom/div :.description (str (if active? "Active" "Inactive") ". Last logged in " last-login))))) (def ui-person-list-item (comp/factory PersonListItem {:keyfn :person/uuid})) (report/defsc-report PersonList [this props] {::report/BodyItem PersonListItem ::report/source-attribute :org.riverdb.db.person ::report/parameters {} ::report/route "people"})
1bdf287f3bc2d362c0743cea8dc883deac0db0dcaad7c3f02b5d2c3caad652a0
fossas/fossa-cli
Paket.hs
module Strategy.NuGet.Paket ( discover, findProjects, getDeps, mkProject, findSections, buildGraph, PaketDep (..), Section (..), Remote (..), ) where import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject) import Control.Effect.Diagnostics ( Diagnostics, Has, context, run, ) import Control.Effect.Reader (Reader) import Control.Monad (guard) import Data.Aeson (ToJSON) import Data.Char qualified as C import Data.Foldable (traverse_) import Data.Functor (void) import Data.Map.Strict qualified as Map import Data.Set (Set) import Data.Text (Text) import Data.Text qualified as Text import Data.Void (Void) import DepTypes ( DepType (NuGetType), Dependency (..), VerConstraint (CEq), ) import Discovery.Filters (AllFilters) import Discovery.Simple (simpleDiscover) import Discovery.Walk ( WalkStep (WalkContinue), findFileNamed, walkWithFilters', ) import Effect.Grapher ( LabeledGrapher, direct, edge, label, withLabeling, ) import Effect.ReadFS (ReadFS, readContentsParser) import GHC.Generics (Generic) import Graphing (Graphing) import Path (Abs, Dir, File, Path, parent) import Text.Megaparsec ( MonadParsec (eof, takeWhile1P, takeWhileP, try), Parsec, between, chunk, empty, many, some, (<|>), ) import Text.Megaparsec.Char (char, eol, space1) import Text.Megaparsec.Char.Lexer qualified as L import Types ( DependencyResults (..), DiscoveredProject (..), DiscoveredProjectType (PaketProjectType), GraphBreadth (Complete), ) type Parser = Parsec Void Text discover :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [DiscoveredProject PaketProject] discover = simpleDiscover findProjects mkProject PaketProjectType findProjects :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [PaketProject] findProjects = walkWithFilters' $ \_ _ files -> do case findFileNamed "paket.lock" files of Nothing -> pure ([], WalkContinue) Just file -> pure ([PaketProject file], WalkContinue) newtype PaketProject = PaketProject { paketLock :: Path Abs File } deriving (Eq, Ord, Show, Generic) instance ToJSON PaketProject instance AnalyzeProject PaketProject where analyzeProject _ = getDeps analyzeProject' _ = getDeps mkProject :: PaketProject -> DiscoveredProject PaketProject mkProject project = DiscoveredProject { projectType = PaketProjectType , projectBuildTargets = mempty , projectPath = parent $ paketLock project , projectData = project } getDeps :: (Has ReadFS sig m, Has Diagnostics sig m) => PaketProject -> m DependencyResults getDeps = context "Paket" . context "Static analysis" . analyze' . paketLock analyze' :: (Has ReadFS sig m, Has Diagnostics sig m) => Path Abs File -> m DependencyResults analyze' file = do sections <- readContentsParser findSections file graph <- context "Building dependency graph" $ pure (buildGraph sections) pure $ DependencyResults { dependencyGraph = graph , dependencyGraphBreadth = Complete , dependencyManifestFiles = [file] } newtype PaketPkg = PaketPkg {pkgName :: Text} deriving (Eq, Ord, Show) type PaketGrapher = LabeledGrapher PaketPkg PaketLabel data PaketLabel = PaketVersion Text | PaketRemote Text | GroupName Text | DepLocation Text deriving (Eq, Ord, Show) toDependency :: PaketPkg -> Set PaketLabel -> Dependency toDependency pkg = foldr applyLabel start where start :: Dependency start = Dependency { dependencyType = NuGetType , dependencyName = pkgName pkg , dependencyVersion = Nothing , dependencyLocations = [] , dependencyEnvironments = mempty , dependencyTags = Map.empty } applyLabel :: PaketLabel -> Dependency -> Dependency applyLabel (PaketVersion ver) dep = dep{dependencyVersion = Just (CEq ver)} applyLabel (GroupName name) dep = dep{dependencyTags = Map.insertWith (++) "group" [name] (dependencyTags dep)} applyLabel (DepLocation loc) dep = dep{dependencyTags = Map.insertWith (++) "location" [loc] (dependencyTags dep)} applyLabel (PaketRemote repo) dep = dep{dependencyLocations = repo : dependencyLocations dep} buildGraph :: [Section] -> Graphing Dependency buildGraph sections = run . withLabeling toDependency $ traverse_ (addSection "MAIN") sections where addSection :: Has PaketGrapher sig m => Text -> Section -> m () addSection group (StandardSection location remotes) = traverse_ (addRemote group location) remotes addSection _ (GroupSection group gSections) = traverse_ (addSection group) gSections addSection _ (UnknownSection _) = pure () addRemote :: Has PaketGrapher sig m => Text -> Text -> Remote -> m () addRemote group loc remote = traverse_ (addSpec (DepLocation loc) (PaketRemote $ remoteLocation remote) (GroupName group)) (remoteDependencies remote) addSpec :: Has PaketGrapher sig m => PaketLabel -> PaketLabel -> PaketLabel -> PaketDep -> m () addSpec loc remote group dep = do add edges , labels , and direct let pkg = PaketPkg (depName dep) traverse_ (edge pkg . PaketPkg) (transitive dep) label pkg (PaketVersion (depVersion dep)) label pkg remote label pkg group label pkg loc direct pkg type Name = Text type Location = Text data Section = StandardSection Location [Remote] | UnknownSection Text | GroupSection Name [Section] deriving (Eq, Ord, Show) data Remote = Remote { remoteLocation :: Text , remoteDependencies :: [PaketDep] } deriving (Eq, Ord, Show) data PaketDep = PaketDep { depName :: Text , depVersion :: Text , transitive :: [Text] } deriving (Eq, Ord, Show) data Group = Group { groupName :: Text , groupSections :: [Section] } deriving (Eq, Ord, Show) findSections :: Parser [Section] findSections = many (try standardSectionParser <|> try groupSection <|> try unknownSection) <* eof groupSection :: Parser Section groupSection = do _ <- chunk "GROUP" name <- textValue sections <- many (try standardSectionParser <|> try unknownSection) pure $ GroupSection name sections unknownSection :: Parser Section unknownSection = do emptyLine <- restOfLine guard $ not $ "GROUP" `Text.isPrefixOf` emptyLine _ <- eol pure $ UnknownSection emptyLine standardSectionParser :: Parser Section standardSectionParser = L.nonIndented scn $ L.indentBlock scn $ do location <- chunk "HTTP" <|> "GITHUB" <|> "NUGET" pure $ L.IndentMany Nothing (pure . StandardSection location) remoteParser remoteParser :: Parser Remote remoteParser = L.indentBlock scn $ do _ <- chunk "remote:" value <- textValue pure $ L.IndentMany Nothing (pure . Remote value) specParser specParser :: Parser PaketDep specParser = L.indentBlock scn $ do name <- findDep version <- findVersion _ <- restOfLine pure $ L.IndentMany Nothing (pure . PaketDep name version) specsParser specsParser :: Parser Text specsParser = findDep <* restOfLine findDep :: Parser Text findDep = lexeme (takeWhile1P (Just "dep") (not . C.isSpace)) findVersion :: Parser Text findVersion = between (char '(') (char ')') $ takeWhile1P (Just "version") (/= ')') textValue :: Parser Text textValue = chunk " " *> restOfLine restOfLine :: Parser Text restOfLine = takeWhileP (Just "ignored") (not . isEndLine) isEndLine :: Char -> Bool isEndLine '\n' = True isEndLine '\r' = True isEndLine _ = False scn :: Parser () scn = L.space space1 empty empty lexeme :: Parser a -> Parser a lexeme = L.lexeme sc sc :: Parser () sc = L.space (void $ some (char ' ')) empty empty
null
https://raw.githubusercontent.com/fossas/fossa-cli/187f19afec2133466d1998c89fc7f1c77107c2b0/src/Strategy/NuGet/Paket.hs
haskell
module Strategy.NuGet.Paket ( discover, findProjects, getDeps, mkProject, findSections, buildGraph, PaketDep (..), Section (..), Remote (..), ) where import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject) import Control.Effect.Diagnostics ( Diagnostics, Has, context, run, ) import Control.Effect.Reader (Reader) import Control.Monad (guard) import Data.Aeson (ToJSON) import Data.Char qualified as C import Data.Foldable (traverse_) import Data.Functor (void) import Data.Map.Strict qualified as Map import Data.Set (Set) import Data.Text (Text) import Data.Text qualified as Text import Data.Void (Void) import DepTypes ( DepType (NuGetType), Dependency (..), VerConstraint (CEq), ) import Discovery.Filters (AllFilters) import Discovery.Simple (simpleDiscover) import Discovery.Walk ( WalkStep (WalkContinue), findFileNamed, walkWithFilters', ) import Effect.Grapher ( LabeledGrapher, direct, edge, label, withLabeling, ) import Effect.ReadFS (ReadFS, readContentsParser) import GHC.Generics (Generic) import Graphing (Graphing) import Path (Abs, Dir, File, Path, parent) import Text.Megaparsec ( MonadParsec (eof, takeWhile1P, takeWhileP, try), Parsec, between, chunk, empty, many, some, (<|>), ) import Text.Megaparsec.Char (char, eol, space1) import Text.Megaparsec.Char.Lexer qualified as L import Types ( DependencyResults (..), DiscoveredProject (..), DiscoveredProjectType (PaketProjectType), GraphBreadth (Complete), ) type Parser = Parsec Void Text discover :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [DiscoveredProject PaketProject] discover = simpleDiscover findProjects mkProject PaketProjectType findProjects :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [PaketProject] findProjects = walkWithFilters' $ \_ _ files -> do case findFileNamed "paket.lock" files of Nothing -> pure ([], WalkContinue) Just file -> pure ([PaketProject file], WalkContinue) newtype PaketProject = PaketProject { paketLock :: Path Abs File } deriving (Eq, Ord, Show, Generic) instance ToJSON PaketProject instance AnalyzeProject PaketProject where analyzeProject _ = getDeps analyzeProject' _ = getDeps mkProject :: PaketProject -> DiscoveredProject PaketProject mkProject project = DiscoveredProject { projectType = PaketProjectType , projectBuildTargets = mempty , projectPath = parent $ paketLock project , projectData = project } getDeps :: (Has ReadFS sig m, Has Diagnostics sig m) => PaketProject -> m DependencyResults getDeps = context "Paket" . context "Static analysis" . analyze' . paketLock analyze' :: (Has ReadFS sig m, Has Diagnostics sig m) => Path Abs File -> m DependencyResults analyze' file = do sections <- readContentsParser findSections file graph <- context "Building dependency graph" $ pure (buildGraph sections) pure $ DependencyResults { dependencyGraph = graph , dependencyGraphBreadth = Complete , dependencyManifestFiles = [file] } newtype PaketPkg = PaketPkg {pkgName :: Text} deriving (Eq, Ord, Show) type PaketGrapher = LabeledGrapher PaketPkg PaketLabel data PaketLabel = PaketVersion Text | PaketRemote Text | GroupName Text | DepLocation Text deriving (Eq, Ord, Show) toDependency :: PaketPkg -> Set PaketLabel -> Dependency toDependency pkg = foldr applyLabel start where start :: Dependency start = Dependency { dependencyType = NuGetType , dependencyName = pkgName pkg , dependencyVersion = Nothing , dependencyLocations = [] , dependencyEnvironments = mempty , dependencyTags = Map.empty } applyLabel :: PaketLabel -> Dependency -> Dependency applyLabel (PaketVersion ver) dep = dep{dependencyVersion = Just (CEq ver)} applyLabel (GroupName name) dep = dep{dependencyTags = Map.insertWith (++) "group" [name] (dependencyTags dep)} applyLabel (DepLocation loc) dep = dep{dependencyTags = Map.insertWith (++) "location" [loc] (dependencyTags dep)} applyLabel (PaketRemote repo) dep = dep{dependencyLocations = repo : dependencyLocations dep} buildGraph :: [Section] -> Graphing Dependency buildGraph sections = run . withLabeling toDependency $ traverse_ (addSection "MAIN") sections where addSection :: Has PaketGrapher sig m => Text -> Section -> m () addSection group (StandardSection location remotes) = traverse_ (addRemote group location) remotes addSection _ (GroupSection group gSections) = traverse_ (addSection group) gSections addSection _ (UnknownSection _) = pure () addRemote :: Has PaketGrapher sig m => Text -> Text -> Remote -> m () addRemote group loc remote = traverse_ (addSpec (DepLocation loc) (PaketRemote $ remoteLocation remote) (GroupName group)) (remoteDependencies remote) addSpec :: Has PaketGrapher sig m => PaketLabel -> PaketLabel -> PaketLabel -> PaketDep -> m () addSpec loc remote group dep = do add edges , labels , and direct let pkg = PaketPkg (depName dep) traverse_ (edge pkg . PaketPkg) (transitive dep) label pkg (PaketVersion (depVersion dep)) label pkg remote label pkg group label pkg loc direct pkg type Name = Text type Location = Text data Section = StandardSection Location [Remote] | UnknownSection Text | GroupSection Name [Section] deriving (Eq, Ord, Show) data Remote = Remote { remoteLocation :: Text , remoteDependencies :: [PaketDep] } deriving (Eq, Ord, Show) data PaketDep = PaketDep { depName :: Text , depVersion :: Text , transitive :: [Text] } deriving (Eq, Ord, Show) data Group = Group { groupName :: Text , groupSections :: [Section] } deriving (Eq, Ord, Show) findSections :: Parser [Section] findSections = many (try standardSectionParser <|> try groupSection <|> try unknownSection) <* eof groupSection :: Parser Section groupSection = do _ <- chunk "GROUP" name <- textValue sections <- many (try standardSectionParser <|> try unknownSection) pure $ GroupSection name sections unknownSection :: Parser Section unknownSection = do emptyLine <- restOfLine guard $ not $ "GROUP" `Text.isPrefixOf` emptyLine _ <- eol pure $ UnknownSection emptyLine standardSectionParser :: Parser Section standardSectionParser = L.nonIndented scn $ L.indentBlock scn $ do location <- chunk "HTTP" <|> "GITHUB" <|> "NUGET" pure $ L.IndentMany Nothing (pure . StandardSection location) remoteParser remoteParser :: Parser Remote remoteParser = L.indentBlock scn $ do _ <- chunk "remote:" value <- textValue pure $ L.IndentMany Nothing (pure . Remote value) specParser specParser :: Parser PaketDep specParser = L.indentBlock scn $ do name <- findDep version <- findVersion _ <- restOfLine pure $ L.IndentMany Nothing (pure . PaketDep name version) specsParser specsParser :: Parser Text specsParser = findDep <* restOfLine findDep :: Parser Text findDep = lexeme (takeWhile1P (Just "dep") (not . C.isSpace)) findVersion :: Parser Text findVersion = between (char '(') (char ')') $ takeWhile1P (Just "version") (/= ')') textValue :: Parser Text textValue = chunk " " *> restOfLine restOfLine :: Parser Text restOfLine = takeWhileP (Just "ignored") (not . isEndLine) isEndLine :: Char -> Bool isEndLine '\n' = True isEndLine '\r' = True isEndLine _ = False scn :: Parser () scn = L.space space1 empty empty lexeme :: Parser a -> Parser a lexeme = L.lexeme sc sc :: Parser () sc = L.space (void $ some (char ' ')) empty empty
f28e86133a39bd29d944ea301ccc495c82ea9f672881f85cfaedc765c9f7ba83
nervous-systems/cljs-lambda
core.cljs
(ns {{name}}.core (:require [cljs-lambda.util :as lambda] [cljs-lambda.context :as ctx] [cljs-lambda.macros :refer-macros [deflambda]] [cljs.reader :refer [read-string]] [cljs.nodejs :as nodejs] [cljs.core.async :as async] [promesa.core :as p]) (:require-macros [cljs.core.async.macros :refer [go]])) (def config (-> (nodejs/require "fs") (.readFileSync "static/config.edn" "UTF-8") read-string)) (defmulti cast-async-spell (fn [{spell :spell} ctx] (keyword spell))) (defmethod cast-async-spell :delay-channel [{:keys [msecs] :or {msecs 1000}} ctx] (go (<! (async/timeout msecs)) {:waited msecs})) (defmethod cast-async-spell :delay-promise [{:keys [msecs] :or {msecs 1000}} ctx] (p/promise (fn [resolve] (p/schedule msecs #(resolve {:waited msecs}))))) (defmethod cast-async-spell :delay-fail [{:keys [msecs] :or {msecs 1000}} ctx] (go (<! (async/timeout msecs)) ;; We can fail/succeed wherever w/ fail!/succeed! - we can also ;; leave an Error instance on the channel we return, or return a reject ;; promised - see :delayed-failure above. (ctx/fail! ctx (js/Error. (str "Failing after " msecs " milliseconds"))))) (deflambda work-magic [{:keys [magic-word] :as input} ctx] (when (not= magic-word (config :magic-word)) (throw (js/Error. "Your magic word is garbage"))) (if (= (input :spell) "echo-env") (ctx/environment ctx) (cast-async-spell input ctx)))
null
https://raw.githubusercontent.com/nervous-systems/cljs-lambda/ecd74ec7046e619b3c097c222124fea4b9973241/templates/cljs-lambda/src/leiningen/new/cljs_lambda/core.cljs
clojure
We can fail/succeed wherever w/ fail!/succeed! - we can also leave an Error instance on the channel we return, or return a reject promised - see :delayed-failure above.
(ns {{name}}.core (:require [cljs-lambda.util :as lambda] [cljs-lambda.context :as ctx] [cljs-lambda.macros :refer-macros [deflambda]] [cljs.reader :refer [read-string]] [cljs.nodejs :as nodejs] [cljs.core.async :as async] [promesa.core :as p]) (:require-macros [cljs.core.async.macros :refer [go]])) (def config (-> (nodejs/require "fs") (.readFileSync "static/config.edn" "UTF-8") read-string)) (defmulti cast-async-spell (fn [{spell :spell} ctx] (keyword spell))) (defmethod cast-async-spell :delay-channel [{:keys [msecs] :or {msecs 1000}} ctx] (go (<! (async/timeout msecs)) {:waited msecs})) (defmethod cast-async-spell :delay-promise [{:keys [msecs] :or {msecs 1000}} ctx] (p/promise (fn [resolve] (p/schedule msecs #(resolve {:waited msecs}))))) (defmethod cast-async-spell :delay-fail [{:keys [msecs] :or {msecs 1000}} ctx] (go (<! (async/timeout msecs)) (ctx/fail! ctx (js/Error. (str "Failing after " msecs " milliseconds"))))) (deflambda work-magic [{:keys [magic-word] :as input} ctx] (when (not= magic-word (config :magic-word)) (throw (js/Error. "Your magic word is garbage"))) (if (= (input :spell) "echo-env") (ctx/environment ctx) (cast-async-spell input ctx)))
df01d98a46e7a20e5bd3afa1686167a6624e530625e39838aa0945cc00c0eb96
tazjin/democrify
User.hs
# LANGUAGE ForeignFunctionInterface # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module User where import Control.Applicative (optional, (<$>)) import Control.Monad (msum, when) import Control.Monad.IO.Class (liftIO) import Data.ByteString.Char8 (ByteString) import Data.Foldable (forM_) import Data.IORef import Data.Maybe (isJust) import Data.Monoid (mempty) import qualified Data.Sequence as SQ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Lazy (toStrict) import qualified Data.Text.Lazy as TL import HSObjC import Network.HTTP.Types.Status import Network.Wai.Handler.Warp import System.IO.Unsafe (unsafePerformIO) import Text.Blaze (toValue, (!)) import Text.Blaze.Html.Renderer.Text import Text.Blaze.Html5 (toHtml) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Web.Scotty Democrify modules import Acid import Admin import Queue import WebAPI -- This is an orphan instance! instance Parsable Text where parseParam = either (Left . id) (Right . toStrict) . parseParam -- |This function renders 'Html' as 'Text' and passes it to scotty html' = html . renderHtml -- *Helpers |This contains a global IORef to the Resource folder inside the Application bundle . All web assets are stored in Resources / web resourcePath :: IORef FilePath resourcePath = unsafePerformIO $ newIORef "" -- |Direct path to the web resources webResources :: IO FilePath webResources = (++ "/web/") <$> readIORef resourcePath |Default layout including Foundation stylesheets defaultLayout :: TL.Text -- ^ Title -> [H.Html] -- ^ Additional head-tag-elements -> [H.Html] -- ^ Additional scripts -> H.Html -- ^ Body -> ActionM () defaultLayout title headtags scripts body = -- The weird-looking line below makes sure that the content header is set after executing html'. -- This is done to prevent it from being overridden. flip (>>) (header "Content-Type" "text/html; charset=utf-8") $ html' $ H.docTypeHtml $ do H.head $ do H.title (H.toHtml title) H.meta ! A.name "apple-mobile-web-app-capable" ! A.content "yes" H.meta ! A.name "viewport" ! A.content "width=device-width, user-scalable=no" Stylesheets H.link ! A.href "/foundation.min.css" ! A.rel "stylesheet" H.link ! A.href "/app.css" ! A.rel "stylesheet" Favicon H.link ! A.href "/democrify_small.png" ! A.rel "icon" Scripts H.script ! A.src "/custom.modernizr.js" $ mempty sequence_ headtags H.body $ do H.nav ! A.class_ "top-bar" $ do H.ul ! A.class_ "title-area" $ do H.li ! A.class_ "name" $ H.h1 $ H.a ! A.href "/" $ do H.img ! A.alt "Logo" ! A.src "/democrify_small.png" ! A.style "height:45px;float:left;" H.span ! A.style "margin-left:5px;float:right;" $ "Democrify" H.li ! A.class_ "toggle-topbar menu-icon" $ H.a ! A.href "#" $ H.span "menu" H.section ! A.class_ "top-bar-section" $ H.ul ! A.class_ "right" $ do H.li ! A.class_ "divider" $ mempty H.li $ H.a ! A.href "/add" $ "Add song" body H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ H.footer $ do H.hr H.p ! A.style "text-align:center;" $ H.a ! A.href "" $ "Powered by Democrify" H.script ! A.src "/jquery.js" $ mempty H.script ! A.src "/foundation.min.js" $ mempty H.script ! A.src "/jquery.cookie.js" $ mempty H.script ! A.src "/app.js" $ mempty sequence_ scripts -- |Displays the user facing queue list queueView :: ActionM () queueView = do current <- liftIO displayCurrentTrack queue <- dfQuery GetQueue defaultLayout "Democrify - Queue" [] [] $ H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ do H.br current H.div ! A.class_ "row" $ H.div ! A.class_ "small-10 columns" $ queueNum queue H.hr forM_ queue (\SpotifyTrack{..} -> do H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.onclick "void(0)" ! A.class_ "vote" ! A.id (toValue tId) ! A.alt "upvote-arrow" ! A.src "/upvote_bw.png" H.div ! A.class_ "large-10 columns trackitem" $ do H.span ! A.class_ "track" $ toHtml track H.br H.span ! A.class_ "artist" $ do " by " toHtml artist H.hr) H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "sad-face" ! A.src "=:(" H.div ! A.class_ "large-10 columns trackitem" $ H.span ! A.class_ "oh-no" $ "Oh no! There is nothing more in the queue! What will happen now?" -- |Displays the user facing queue list queuePassive :: ActionM () queuePassive = do current <- liftIO displayCurrentTrack queue <- dfQuery GetQueue defaultLayout "Democrify - Queue" [H.meta ! A.httpEquiv "refresh" ! A.content "30"] [] $ H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ do H.br current H.div ! A.class_ "row" $ H.div ! A.class_ "small-10 columns" $ queueNum queue H.hr forM_ queue (\SpotifyTrack{..} -> do H.div ! A.class_ "row" $ do H.div ! A.class_ "large-12 small-4 columns trackitem" $ do H.span ! A.class_ "track" $ toHtml track H.br H.span ! A.class_ "artist" $ do " by " toHtml artist H.hr) H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "sad-face" ! A.src "=:(" H.div ! A.class_ "large-10 columns trackitem" $ H.span ! A.class_ "oh-no" $ "Oh no! There is nothing more in the queue! What will happen now?" queueNum :: SQ.Seq SpotifyTrack -> H.Html queueNum s | l == 1 = H.span ! A.class_ "queuenum" $ "1 song in the queue" | otherwise = H.span ! A.class_ "queuenum" $ toHtml $ T.append (T.pack $ show l) " songs in the queue" where l = SQ.length s displayCurrentTrack :: IO H.Html displayCurrentTrack = do current <- readIORef currentTrack let content = case current of Nothing -> H.p ! A.class_ "oh-no" $ "No track is playing right now!" Just SpotifyTrack{..} -> H.a ! A.href (toValue $ TL.append "spotify:track:" tId) $ do H.br H.span ! A.class_ "track" $ do "Current track:" H.br toHtml track H.br H.span ! A.class_ "artist" $ do "by " toHtml artist return $ H.div ! A.class_ "row current" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "current" ! A.src "/current.gif" H.div ! A.class_ "large-10 columns" $ content -- |Page that displays the song adding interface addSongView :: ActionM () addSongView = defaultLayout "Democrify - Add song" [] [ H.script ! A.src "/addsong.js" $ mempty ] $ do H.style $ "body{background-color: #222 !important;} footer{color:white;}" H.div ! A.class_ "row collapse" $ do H.div ! A.class_ "large-10 small-6 columns" $ H.input ! A.id "search" ! A.type_ "text" H.div ! A.class_ "large-1 small-3 columns" $ H.a ! A.class_ "button expand postfix" ! A.id "searchbutton" $ "Search" H.div ! A.class_ "large-1 small-3 columns" $ H.form ! A.class_ "custom" $ H.select ! A.id "searchtype" $ do H.option ! A.selected "" $ "Track" H.option "Artist" H.option "Album" H.div ! A.class_ "row" ! A.id "resultcontainer" ! A.class_ "small-12 columns" $ mempty -- |Upvotes a song based on the ID upvoteHandler :: TL.Text -> ActionM () upvoteHandler song = do dfUpdate $ UpvoteTrack song text $ TL.append "Upvoted " song -- |Adds a song to the queue based on its ID. If the song cannot be found a 404 will be returned , if the song is already in the queue -- it will be upvoted. addHandler :: TL.Text -> ActionM () addHandler trackId = do track <- liftIO $ identifyTrack trackId Preferences{..} <- liftIO getPrefs case track of Nothing -> status (mkStatus 404 "Not found") >> text "notfound" (Just t) -> do when autoShuffle (liftIO shuffleQueue) dfUpdate $ AddTrackToQueue duplicates (t { votes = 0}) text "ok" adminHandler :: ActionM () adminHandler = do queue <- dfQuery GetQueue defaultLayout "Democrify - Admin" [] [ H.script ! A.src "/admin.js" $ mempty ] (adminQueue queue) showPrefs :: ActionM () showPrefs = do prefs <- liftIO getPrefs defaultLayout "Democrify - Settings" [] [] (adminPrefs prefs) |This is supplised with the NSArray that contains all the NSStrings to the URLs . loadPlaylist :: Id -> IO () loadPlaylist pl = do Preferences{..} <- liftIO getPrefs runId $ do trackIds <- fmap (map TL.fromStrict) $ fromId pl mTracks <- liftIO $ getTrackData trackIds let tracks = map (\(Just t) -> t) $ filter isJust mTracks forM_ tracks $ \t -> dfUpdate $ AddTrackToQueue duplicates t when autoShuffle shuffleQueue return () * things -- |This serves static files serveStatic f = liftIO webResources >>= (\resPath -> file $ resPath ++ f) |This contains the routing function for . I do n't have time for type - safe routing in this project ! :D --democrify :: ActionM democrify :: ScottyM () democrify = do get "/" queueView get "/view" queuePassive get "/upvote/:song" $ param "song" >>= upvoteHandler get "/add" addSongView get "/add/:song" $ param "song" >>= addHandler get "/:file" serveStatic |This is the Scotty Application representing the admin handler . adminRoutes :: ScottyM () adminRoutes = liftIO webResources >>= \resPath -> do get "/admin" adminHandler get "/admin/vote/:song" $ param "song" >>= adminUpvoteHandler get "/admin/delete/:song" $ param "song" >>= adminDeleteHandler get "/admin/config" showPrefs get "/:file" serveStatic runServer :: IO () runServer = scotty 8686 democrify runAdminServer :: IO () runAdminServer = scottyOpts adminOpts adminRoutes where adminOpts = Options 0 $ defaultSettings { settingsPort = 1337, settingsHost = "127.0.0.1" } foreign export ccall loadPlaylist :: Id -> IO ()
null
https://raw.githubusercontent.com/tazjin/democrify/44d839428f881dff488d2e152ddb828dfd308dde/Democrify/User.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # This is an orphan instance! |This function renders 'Html' as 'Text' and passes it to scotty *Helpers |Direct path to the web resources ^ Title ^ Additional head-tag-elements ^ Additional scripts ^ Body The weird-looking line below makes sure that the content header is set after executing html'. This is done to prevent it from being overridden. |Displays the user facing queue list |Displays the user facing queue list |Page that displays the song adding interface |Upvotes a song based on the ID |Adds a song to the queue based on its ID. If the song cannot be it will be upvoted. |This serves static files democrify :: ActionM
# LANGUAGE ForeignFunctionInterface # module User where import Control.Applicative (optional, (<$>)) import Control.Monad (msum, when) import Control.Monad.IO.Class (liftIO) import Data.ByteString.Char8 (ByteString) import Data.Foldable (forM_) import Data.IORef import Data.Maybe (isJust) import Data.Monoid (mempty) import qualified Data.Sequence as SQ import Data.Text (Text) import qualified Data.Text as T import Data.Text.Lazy (toStrict) import qualified Data.Text.Lazy as TL import HSObjC import Network.HTTP.Types.Status import Network.Wai.Handler.Warp import System.IO.Unsafe (unsafePerformIO) import Text.Blaze (toValue, (!)) import Text.Blaze.Html.Renderer.Text import Text.Blaze.Html5 (toHtml) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Web.Scotty Democrify modules import Acid import Admin import Queue import WebAPI instance Parsable Text where parseParam = either (Left . id) (Right . toStrict) . parseParam html' = html . renderHtml |This contains a global IORef to the Resource folder inside the Application bundle . All web assets are stored in Resources / web resourcePath :: IORef FilePath resourcePath = unsafePerformIO $ newIORef "" webResources :: IO FilePath webResources = (++ "/web/") <$> readIORef resourcePath |Default layout including Foundation stylesheets -> ActionM () defaultLayout title headtags scripts body = flip (>>) (header "Content-Type" "text/html; charset=utf-8") $ html' $ H.docTypeHtml $ do H.head $ do H.title (H.toHtml title) H.meta ! A.name "apple-mobile-web-app-capable" ! A.content "yes" H.meta ! A.name "viewport" ! A.content "width=device-width, user-scalable=no" Stylesheets H.link ! A.href "/foundation.min.css" ! A.rel "stylesheet" H.link ! A.href "/app.css" ! A.rel "stylesheet" Favicon H.link ! A.href "/democrify_small.png" ! A.rel "icon" Scripts H.script ! A.src "/custom.modernizr.js" $ mempty sequence_ headtags H.body $ do H.nav ! A.class_ "top-bar" $ do H.ul ! A.class_ "title-area" $ do H.li ! A.class_ "name" $ H.h1 $ H.a ! A.href "/" $ do H.img ! A.alt "Logo" ! A.src "/democrify_small.png" ! A.style "height:45px;float:left;" H.span ! A.style "margin-left:5px;float:right;" $ "Democrify" H.li ! A.class_ "toggle-topbar menu-icon" $ H.a ! A.href "#" $ H.span "menu" H.section ! A.class_ "top-bar-section" $ H.ul ! A.class_ "right" $ do H.li ! A.class_ "divider" $ mempty H.li $ H.a ! A.href "/add" $ "Add song" body H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ H.footer $ do H.hr H.p ! A.style "text-align:center;" $ H.a ! A.href "" $ "Powered by Democrify" H.script ! A.src "/jquery.js" $ mempty H.script ! A.src "/foundation.min.js" $ mempty H.script ! A.src "/jquery.cookie.js" $ mempty H.script ! A.src "/app.js" $ mempty sequence_ scripts queueView :: ActionM () queueView = do current <- liftIO displayCurrentTrack queue <- dfQuery GetQueue defaultLayout "Democrify - Queue" [] [] $ H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ do H.br current H.div ! A.class_ "row" $ H.div ! A.class_ "small-10 columns" $ queueNum queue H.hr forM_ queue (\SpotifyTrack{..} -> do H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.onclick "void(0)" ! A.class_ "vote" ! A.id (toValue tId) ! A.alt "upvote-arrow" ! A.src "/upvote_bw.png" H.div ! A.class_ "large-10 columns trackitem" $ do H.span ! A.class_ "track" $ toHtml track H.br H.span ! A.class_ "artist" $ do " by " toHtml artist H.hr) H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "sad-face" ! A.src "=:(" H.div ! A.class_ "large-10 columns trackitem" $ H.span ! A.class_ "oh-no" $ "Oh no! There is nothing more in the queue! What will happen now?" queuePassive :: ActionM () queuePassive = do current <- liftIO displayCurrentTrack queue <- dfQuery GetQueue defaultLayout "Democrify - Queue" [H.meta ! A.httpEquiv "refresh" ! A.content "30"] [] $ H.div ! A.class_ "row" $ H.div ! A.class_ "small-12 columns" $ do H.br current H.div ! A.class_ "row" $ H.div ! A.class_ "small-10 columns" $ queueNum queue H.hr forM_ queue (\SpotifyTrack{..} -> do H.div ! A.class_ "row" $ do H.div ! A.class_ "large-12 small-4 columns trackitem" $ do H.span ! A.class_ "track" $ toHtml track H.br H.span ! A.class_ "artist" $ do " by " toHtml artist H.hr) H.div ! A.class_ "row" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "sad-face" ! A.src "=:(" H.div ! A.class_ "large-10 columns trackitem" $ H.span ! A.class_ "oh-no" $ "Oh no! There is nothing more in the queue! What will happen now?" queueNum :: SQ.Seq SpotifyTrack -> H.Html queueNum s | l == 1 = H.span ! A.class_ "queuenum" $ "1 song in the queue" | otherwise = H.span ! A.class_ "queuenum" $ toHtml $ T.append (T.pack $ show l) " songs in the queue" where l = SQ.length s displayCurrentTrack :: IO H.Html displayCurrentTrack = do current <- readIORef currentTrack let content = case current of Nothing -> H.p ! A.class_ "oh-no" $ "No track is playing right now!" Just SpotifyTrack{..} -> H.a ! A.href (toValue $ TL.append "spotify:track:" tId) $ do H.br H.span ! A.class_ "track" $ do "Current track:" H.br toHtml track H.br H.span ! A.class_ "artist" $ do "by " toHtml artist return $ H.div ! A.class_ "row current" $ do H.div ! A.class_ "small-3 large-2 columns" $ H.img ! A.alt "current" ! A.src "/current.gif" H.div ! A.class_ "large-10 columns" $ content addSongView :: ActionM () addSongView = defaultLayout "Democrify - Add song" [] [ H.script ! A.src "/addsong.js" $ mempty ] $ do H.style $ "body{background-color: #222 !important;} footer{color:white;}" H.div ! A.class_ "row collapse" $ do H.div ! A.class_ "large-10 small-6 columns" $ H.input ! A.id "search" ! A.type_ "text" H.div ! A.class_ "large-1 small-3 columns" $ H.a ! A.class_ "button expand postfix" ! A.id "searchbutton" $ "Search" H.div ! A.class_ "large-1 small-3 columns" $ H.form ! A.class_ "custom" $ H.select ! A.id "searchtype" $ do H.option ! A.selected "" $ "Track" H.option "Artist" H.option "Album" H.div ! A.class_ "row" ! A.id "resultcontainer" ! A.class_ "small-12 columns" $ mempty upvoteHandler :: TL.Text -> ActionM () upvoteHandler song = do dfUpdate $ UpvoteTrack song text $ TL.append "Upvoted " song found a 404 will be returned , if the song is already in the queue addHandler :: TL.Text -> ActionM () addHandler trackId = do track <- liftIO $ identifyTrack trackId Preferences{..} <- liftIO getPrefs case track of Nothing -> status (mkStatus 404 "Not found") >> text "notfound" (Just t) -> do when autoShuffle (liftIO shuffleQueue) dfUpdate $ AddTrackToQueue duplicates (t { votes = 0}) text "ok" adminHandler :: ActionM () adminHandler = do queue <- dfQuery GetQueue defaultLayout "Democrify - Admin" [] [ H.script ! A.src "/admin.js" $ mempty ] (adminQueue queue) showPrefs :: ActionM () showPrefs = do prefs <- liftIO getPrefs defaultLayout "Democrify - Settings" [] [] (adminPrefs prefs) |This is supplised with the NSArray that contains all the NSStrings to the URLs . loadPlaylist :: Id -> IO () loadPlaylist pl = do Preferences{..} <- liftIO getPrefs runId $ do trackIds <- fmap (map TL.fromStrict) $ fromId pl mTracks <- liftIO $ getTrackData trackIds let tracks = map (\(Just t) -> t) $ filter isJust mTracks forM_ tracks $ \t -> dfUpdate $ AddTrackToQueue duplicates t when autoShuffle shuffleQueue return () * things serveStatic f = liftIO webResources >>= (\resPath -> file $ resPath ++ f) |This contains the routing function for . I do n't have time for type - safe routing in this project ! :D democrify :: ScottyM () democrify = do get "/" queueView get "/view" queuePassive get "/upvote/:song" $ param "song" >>= upvoteHandler get "/add" addSongView get "/add/:song" $ param "song" >>= addHandler get "/:file" serveStatic |This is the Scotty Application representing the admin handler . adminRoutes :: ScottyM () adminRoutes = liftIO webResources >>= \resPath -> do get "/admin" adminHandler get "/admin/vote/:song" $ param "song" >>= adminUpvoteHandler get "/admin/delete/:song" $ param "song" >>= adminDeleteHandler get "/admin/config" showPrefs get "/:file" serveStatic runServer :: IO () runServer = scotty 8686 democrify runAdminServer :: IO () runAdminServer = scottyOpts adminOpts adminRoutes where adminOpts = Options 0 $ defaultSettings { settingsPort = 1337, settingsHost = "127.0.0.1" } foreign export ccall loadPlaylist :: Id -> IO ()
0f0bf2aa3baf86823b125501f0ccaf3f04f1a39c3563cda81deb879ddeaf15bc
danr/hipspec
DifficultRotate.hs
{-# LANGUAGE DeriveDataTypeable #-} module Challenges.DifficultRotate where import Prelude hiding (reverse,(++),(+),(*),(-),(<),(<=),length,drop,take) import HipSpec.Prelude data List = Cons A List | Nil deriving (Eq,Typeable,Ord) data Nat = S Nat | Z deriving (Eq,Show,Typeable,Ord) (+) :: Nat -> Nat -> Nat S n + m = S (n + m) Z + m = m (*) :: Nat -> Nat -> Nat S n * m = m + (n * m) _ * m = Z Z <= _ = True _ <= Z = False S x <= S y = x <= y _ < Z = False Z < _ = True S x < S y = x < y Z - _ = Z x - Z = x S x - S y = x - y n % Z = Z n % m | n < m = n | otherwise = (n - m) % m length :: List -> Nat length Nil = Z length (Cons _ xs) = S (length xs) (++) :: List -> List -> List Cons x xs ++ ys = Cons x (xs ++ ys) Nil ++ ys = ys rotate :: Nat -> List -> List rotate Z xs = xs rotate _ Nil = Nil rotate (S n) (Cons x xs) = rotate n (xs ++ Cons x Nil) take :: Nat -> List -> List take Z xs = Nil take _ Nil = Nil take (S n) (Cons x xs) = Cons x (take n xs) drop :: Nat -> List -> List drop Z xs = xs drop _ Nil = Nil drop (S n) (Cons x xs) = drop n xs -- From productive use of failure prop_T32 :: List -> Prop List prop_T32 xs = rotate (length xs) xs =:= xs prop_rot_self :: Nat -> List -> Prop List prop_rot_self n xs = rotate n (xs ++ xs) =:= rotate n xs ++ rotate n xs prop_rot_mod :: Nat -> List -> Prop List prop_rot_mod n xs = rotate n xs =:= drop (n % length xs) xs ++ take (n % length xs) xs sig = [ vars ["x", "y", "z"] (undefined :: A) , vars ["n", "m", "o"] (undefined :: Nat) , vars ["xs", "ys", "zs"] (undefined :: List) , fun0 "True" True , fun0 "False" False , fun0 "Z" Z , fun1 "S" S , fun2 "+" (+) , fun2 "*" (*) , fun2 "%" (%) , fun2 "-" (-) , fun2 "<" (<) , fun0 "Nil" Nil , fun2 "Cons" Cons , fun1 "length" length , fun2 "++" (++) , fun2 "rotate" rotate , fun2 "take" take , fun2 "drop" drop ] instance Enum Nat where toEnum 0 = Z toEnum n = S (toEnum (pred n)) fromEnum Z = 0 fromEnum (S n) = succ (fromEnum n) instance Arbitrary Nat where arbitrary = sized arbSized arbSized s = do x <- choose (0,round (sqrt (toEnum s))) return (toEnum x) instance Arbitrary List where arbitrary = toList `fmap` arbitrary instance Partial List where unlifted xs = toList `fmap` unlifted (fromList xs) fromList :: List -> [A] fromList (Cons x xs) = x : fromList xs fromList Nil = [] toList :: [A] -> List toList (x:xs) = Cons x (toList xs) toList [] = Nil
null
https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/examples/Challenges/DifficultRotate.hs
haskell
# LANGUAGE DeriveDataTypeable # From productive use of failure
module Challenges.DifficultRotate where import Prelude hiding (reverse,(++),(+),(*),(-),(<),(<=),length,drop,take) import HipSpec.Prelude data List = Cons A List | Nil deriving (Eq,Typeable,Ord) data Nat = S Nat | Z deriving (Eq,Show,Typeable,Ord) (+) :: Nat -> Nat -> Nat S n + m = S (n + m) Z + m = m (*) :: Nat -> Nat -> Nat S n * m = m + (n * m) _ * m = Z Z <= _ = True _ <= Z = False S x <= S y = x <= y _ < Z = False Z < _ = True S x < S y = x < y Z - _ = Z x - Z = x S x - S y = x - y n % Z = Z n % m | n < m = n | otherwise = (n - m) % m length :: List -> Nat length Nil = Z length (Cons _ xs) = S (length xs) (++) :: List -> List -> List Cons x xs ++ ys = Cons x (xs ++ ys) Nil ++ ys = ys rotate :: Nat -> List -> List rotate Z xs = xs rotate _ Nil = Nil rotate (S n) (Cons x xs) = rotate n (xs ++ Cons x Nil) take :: Nat -> List -> List take Z xs = Nil take _ Nil = Nil take (S n) (Cons x xs) = Cons x (take n xs) drop :: Nat -> List -> List drop Z xs = xs drop _ Nil = Nil drop (S n) (Cons x xs) = drop n xs prop_T32 :: List -> Prop List prop_T32 xs = rotate (length xs) xs =:= xs prop_rot_self :: Nat -> List -> Prop List prop_rot_self n xs = rotate n (xs ++ xs) =:= rotate n xs ++ rotate n xs prop_rot_mod :: Nat -> List -> Prop List prop_rot_mod n xs = rotate n xs =:= drop (n % length xs) xs ++ take (n % length xs) xs sig = [ vars ["x", "y", "z"] (undefined :: A) , vars ["n", "m", "o"] (undefined :: Nat) , vars ["xs", "ys", "zs"] (undefined :: List) , fun0 "True" True , fun0 "False" False , fun0 "Z" Z , fun1 "S" S , fun2 "+" (+) , fun2 "*" (*) , fun2 "%" (%) , fun2 "-" (-) , fun2 "<" (<) , fun0 "Nil" Nil , fun2 "Cons" Cons , fun1 "length" length , fun2 "++" (++) , fun2 "rotate" rotate , fun2 "take" take , fun2 "drop" drop ] instance Enum Nat where toEnum 0 = Z toEnum n = S (toEnum (pred n)) fromEnum Z = 0 fromEnum (S n) = succ (fromEnum n) instance Arbitrary Nat where arbitrary = sized arbSized arbSized s = do x <- choose (0,round (sqrt (toEnum s))) return (toEnum x) instance Arbitrary List where arbitrary = toList `fmap` arbitrary instance Partial List where unlifted xs = toList `fmap` unlifted (fromList xs) fromList :: List -> [A] fromList (Cons x xs) = x : fromList xs fromList Nil = [] toList :: [A] -> List toList (x:xs) = Cons x (toList xs) toList [] = Nil
6d33a3400b8b4adcd6c0026efef5cff887904023034d369a05ce3325b47dbe84
chapmanb/bcbio.variation
trusted.clj
(ns bcbio.variation.filter.trusted "Retrieve trusted variants from comparisons based on configured thresholds. Allows specification of cases where we should trust variants to pass, such as: found in more than two sequencing technologies, or called in 3 aligners, or called in 7 out of 8 inputs." (:use [bcbio.variation.multiple :only [multiple-overlap-analysis remove-mod-name prep-cmp-name-lookup get-vc-set-calls]] [bcbio.variation.variantcontext :only [parse-vcf write-vcf-w-template get-vcf-iterator]]) (:require [clojure.string :as string] [bcbio.run.fsp :as fsp] [bcbio.run.itx :as itx])) (defn- pairwise-only? "Check if a comparison set is only pairwise and not multiple." [cmp-names] (= 1 (count (set (map (fn [xs] (vec (map remove-mod-name xs))) cmp-names))))) (defn get-support-vcfs "Retrieve supporting VCFs for a set of comparisons and specified support." [cmps support config & {:keys [remove-mods?]}] (let [cmps-by-name (if (map? cmps) cmps (prep-cmp-name-lookup cmps :remove-mods? remove-mods?)) support (if (and (not (coll? support)) (pairwise-only? (keys cmps-by-name))) (first (keys cmps-by-name)) support)] (if (coll? support) (zipmap [:true-positives :false-positives] (take 2 (-> cmps-by-name (get support) :c-files vals))) (let [x (multiple-overlap-analysis cmps-by-name config support)] (into {} (map (juxt identity x) [:true-positives :false-positives :target-overlaps])))))) (defn variant-set-metadata "Retrieve metadata associated with overlapping variants from combined set attribute." [vc calls] (when-let [set-calls (get-vc-set-calls vc calls :remove-filtered? false)] (reduce (fn [coll x] (let [cur-name (string/replace (:name x) "-" "_")] (if-not (contains? set-calls cur-name) coll (reduce (fn [inner [k v]] (assoc inner k (conj (get inner k #{}) v))) coll (assoc (get x :metadata {}) :total cur-name))))) {} calls))) (defn is-trusted-variant? "Determine if we trust a variant based on specified trust parameters. The params specify required counts for inclusion. For instance: {:total 4 :technology 3 :caller 2} includes variants located in 4 total calls or in three different technologies or in 2 different callers. It can also handle percentages for required inputs: {:total 1.0 :technology 0.75}" [vc params calls] (letfn [(collapse-md-by-type [calls] (reduce (fn [coll [k v]] (assoc coll k (conj (get coll k #{}) v))) {:total (set (map :name calls))} (mapcat :metadata calls))) (calc-md-counts [calls] (reduce (fn [coll [k v]] (assoc coll k (count v))) {} (collapse-md-by-type calls))) (param-passes? [metadata md-counts [k v]] (let [n (count (get metadata k []))] (if (> v 1) (>= n v) (>= (/ n (get md-counts k)) v))))] (let [use-calls (remove :recall calls)] (some (partial param-passes? (variant-set-metadata vc use-calls) (calc-md-counts use-calls)) params)))) (defn get-comparison-fullcombine "Retrieve the all variant fullcombine VCF for a set of comparisons." [cmps support config] (:target-overlaps (get-support-vcfs cmps (if (coll? support) (first support) support) config :remove-mods? true))) (defn get-trusted-variants "Retrieve VCF file of trusted variants based on specific parameters." [cmps support params exp config] (when-let [base-vcf (get-comparison-fullcombine cmps support config)] (let [out-file (fsp/add-file-part base-vcf "trusted")] (when (itx/needs-run? out-file) (with-open [base-vcf-iter (get-vcf-iterator base-vcf (:ref exp))] (write-vcf-w-template base-vcf {:out out-file} (->> (parse-vcf base-vcf-iter) (filter #(is-trusted-variant? % params (:calls exp))) (map :vc)) (:ref exp)))) out-file)))
null
https://raw.githubusercontent.com/chapmanb/bcbio.variation/c48834a6819e63dcccb5bc51540c7e19b212a019/src/bcbio/variation/filter/trusted.clj
clojure
(ns bcbio.variation.filter.trusted "Retrieve trusted variants from comparisons based on configured thresholds. Allows specification of cases where we should trust variants to pass, such as: found in more than two sequencing technologies, or called in 3 aligners, or called in 7 out of 8 inputs." (:use [bcbio.variation.multiple :only [multiple-overlap-analysis remove-mod-name prep-cmp-name-lookup get-vc-set-calls]] [bcbio.variation.variantcontext :only [parse-vcf write-vcf-w-template get-vcf-iterator]]) (:require [clojure.string :as string] [bcbio.run.fsp :as fsp] [bcbio.run.itx :as itx])) (defn- pairwise-only? "Check if a comparison set is only pairwise and not multiple." [cmp-names] (= 1 (count (set (map (fn [xs] (vec (map remove-mod-name xs))) cmp-names))))) (defn get-support-vcfs "Retrieve supporting VCFs for a set of comparisons and specified support." [cmps support config & {:keys [remove-mods?]}] (let [cmps-by-name (if (map? cmps) cmps (prep-cmp-name-lookup cmps :remove-mods? remove-mods?)) support (if (and (not (coll? support)) (pairwise-only? (keys cmps-by-name))) (first (keys cmps-by-name)) support)] (if (coll? support) (zipmap [:true-positives :false-positives] (take 2 (-> cmps-by-name (get support) :c-files vals))) (let [x (multiple-overlap-analysis cmps-by-name config support)] (into {} (map (juxt identity x) [:true-positives :false-positives :target-overlaps])))))) (defn variant-set-metadata "Retrieve metadata associated with overlapping variants from combined set attribute." [vc calls] (when-let [set-calls (get-vc-set-calls vc calls :remove-filtered? false)] (reduce (fn [coll x] (let [cur-name (string/replace (:name x) "-" "_")] (if-not (contains? set-calls cur-name) coll (reduce (fn [inner [k v]] (assoc inner k (conj (get inner k #{}) v))) coll (assoc (get x :metadata {}) :total cur-name))))) {} calls))) (defn is-trusted-variant? "Determine if we trust a variant based on specified trust parameters. The params specify required counts for inclusion. For instance: {:total 4 :technology 3 :caller 2} includes variants located in 4 total calls or in three different technologies or in 2 different callers. It can also handle percentages for required inputs: {:total 1.0 :technology 0.75}" [vc params calls] (letfn [(collapse-md-by-type [calls] (reduce (fn [coll [k v]] (assoc coll k (conj (get coll k #{}) v))) {:total (set (map :name calls))} (mapcat :metadata calls))) (calc-md-counts [calls] (reduce (fn [coll [k v]] (assoc coll k (count v))) {} (collapse-md-by-type calls))) (param-passes? [metadata md-counts [k v]] (let [n (count (get metadata k []))] (if (> v 1) (>= n v) (>= (/ n (get md-counts k)) v))))] (let [use-calls (remove :recall calls)] (some (partial param-passes? (variant-set-metadata vc use-calls) (calc-md-counts use-calls)) params)))) (defn get-comparison-fullcombine "Retrieve the all variant fullcombine VCF for a set of comparisons." [cmps support config] (:target-overlaps (get-support-vcfs cmps (if (coll? support) (first support) support) config :remove-mods? true))) (defn get-trusted-variants "Retrieve VCF file of trusted variants based on specific parameters." [cmps support params exp config] (when-let [base-vcf (get-comparison-fullcombine cmps support config)] (let [out-file (fsp/add-file-part base-vcf "trusted")] (when (itx/needs-run? out-file) (with-open [base-vcf-iter (get-vcf-iterator base-vcf (:ref exp))] (write-vcf-w-template base-vcf {:out out-file} (->> (parse-vcf base-vcf-iter) (filter #(is-trusted-variant? % params (:calls exp))) (map :vc)) (:ref exp)))) out-file)))
545b7c0203733da50f44cc76426ccc9fe693497bbb80f74c47a6820fddc57491
ghc/packages-Cabal
PackageEnvironment.hs
# LANGUAGE DeriveGeneric # ----------------------------------------------------------------------------- -- | Module : Distribution . Client . . PackageEnvironment -- Maintainer : -- Portability : portable -- Utilities for working with the package environment file . Patterned after -- Distribution.Client.Config. ----------------------------------------------------------------------------- module Distribution.Client.Sandbox.PackageEnvironment ( PackageEnvironment(..) , PackageEnvironmentType(..) , classifyPackageEnvironment , readPackageEnvironmentFile , showPackageEnvironment , showPackageEnvironmentWithComments , loadUserConfig , userPackageEnvironmentFile ) where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Client.Config ( SavedConfig(..) , configFieldDescriptions , haddockFlagsFields , installDirsFields, withProgramsFields , withProgramOptionsFields ) import Distribution.Client.ParseUtils ( parseFields, ppFields, ppSection ) import Distribution.Client.Setup ( ConfigExFlags(..) ) import Distribution.Client.Targets ( userConstraintPackageName ) import Distribution.Simple.InstallDirs ( InstallDirs(..), PathTemplate ) import Distribution.Simple.Setup ( Flag(..) , ConfigFlags(..), HaddockFlags(..) ) import Distribution.Simple.Utils ( warn, debug ) import Distribution.Solver.Types.ConstraintSource import Distribution.Deprecated.ParseUtils ( FieldDescr(..), ParseResult(..) , commaListFieldParsec, commaNewLineListFieldParsec , liftField, lineNo, locatedErrorMsg , readFields , showPWarning , syntaxError, warning ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>) ) import System.IO.Error ( isDoesNotExistError ) import Text.PrettyPrint ( ($+$) ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Deprecated.ParseUtils as ParseUtils ( Field(..) ) -- -- * Configuration saved in the package environment file -- -- TODO: would be nice to remove duplication between D.C.Sandbox . PackageEnvironment and D.C.Config . data PackageEnvironment = PackageEnvironment { pkgEnvSavedConfig :: SavedConfig } deriving Generic instance Monoid PackageEnvironment where mempty = gmempty mappend = (<>) instance Semigroup PackageEnvironment where (<>) = gmappend -- | Optional package environment file that can be used to customize the default -- settings. Created by the user. userPackageEnvironmentFile :: FilePath userPackageEnvironmentFile = "cabal.config" -- | Type of the current package environment. data PackageEnvironmentType = UserPackageEnvironment -- ^ './cabal.config' | AmbientPackageEnvironment -- ^ '~/.cabal/config' -- | Is there a 'cabal.config' in this directory? classifyPackageEnvironment :: FilePath -> IO PackageEnvironmentType classifyPackageEnvironment pkgEnvDir = do isUser <- configExists userPackageEnvironmentFile return (classify isUser) where configExists fname = doesFileExist (pkgEnvDir </> fname) classify :: Bool -> PackageEnvironmentType classify True = UserPackageEnvironment classify False = AmbientPackageEnvironment -- | Load the user package environment if it exists (the optional "cabal.config" -- file). If it does not exist locally, attempt to load an optional global one. userPackageEnvironment :: Verbosity -> FilePath -> Maybe FilePath -> IO PackageEnvironment userPackageEnvironment verbosity pkgEnvDir globalConfigLocation = do let path = pkgEnvDir </> userPackageEnvironmentFile minp <- readPackageEnvironmentFile (ConstraintSourceUserConfig path) mempty path case (minp, globalConfigLocation) of (Just parseRes, _) -> processConfigParse path parseRes (_, Just globalLoc) -> do minp' <- readPackageEnvironmentFile (ConstraintSourceUserConfig globalLoc) mempty globalLoc maybe (warn verbosity ("no constraints file found at " ++ globalLoc) >> return mempty) (processConfigParse globalLoc) minp' _ -> do debug verbosity ("no user package environment file found at " ++ pkgEnvDir) return mempty where processConfigParse path (ParseOk warns parseResult) = do unless (null warns) $ warn verbosity $ unlines (map (showPWarning path) warns) return parseResult processConfigParse path (ParseFailed err) = do let (line, msg) = locatedErrorMsg err warn verbosity $ "Error parsing package environment file " ++ path ++ maybe "" (\n -> ":" ++ show n) line ++ ":\n" ++ msg return mempty | Same as @userPackageEnvironmentFile@ , but returns a SavedConfig . loadUserConfig :: Verbosity -> FilePath -> Maybe FilePath -> IO SavedConfig loadUserConfig verbosity pkgEnvDir globalConfigLocation = fmap pkgEnvSavedConfig $ userPackageEnvironment verbosity pkgEnvDir globalConfigLocation -- | Descriptions of all fields in the package environment file. pkgEnvFieldDescrs :: ConstraintSource -> [FieldDescr PackageEnvironment] pkgEnvFieldDescrs src = [ commaNewLineListFieldParsec "constraints" (pretty . fst) ((\pc -> (pc, src)) `fmap` parsec) (sortConstraints . configExConstraints . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configExConstraints = v })) , commaListFieldParsec "preferences" pretty parsec (configPreferences . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configPreferences = v })) ] ++ map toPkgEnv configFieldDescriptions' where configFieldDescriptions' :: [FieldDescr SavedConfig] configFieldDescriptions' = filter (\(FieldDescr name _ _) -> name /= "preference" && name /= "constraint") (configFieldDescriptions src) toPkgEnv :: FieldDescr SavedConfig -> FieldDescr PackageEnvironment toPkgEnv fieldDescr = liftField pkgEnvSavedConfig (\savedConfig pkgEnv -> pkgEnv { pkgEnvSavedConfig = savedConfig}) fieldDescr updateConfigureExFlags :: PackageEnvironment -> (ConfigExFlags -> ConfigExFlags) -> PackageEnvironment updateConfigureExFlags pkgEnv f = pkgEnv { pkgEnvSavedConfig = (pkgEnvSavedConfig pkgEnv) { savedConfigureExFlags = f . savedConfigureExFlags . pkgEnvSavedConfig $ pkgEnv } } sortConstraints = sortBy (comparing $ userConstraintPackageName . fst) -- | Read the package environment file. readPackageEnvironmentFile :: ConstraintSource -> PackageEnvironment -> FilePath -> IO (Maybe (ParseResult PackageEnvironment)) readPackageEnvironmentFile src initial file = handleNotExists $ fmap (Just . parsePackageEnvironment src initial) (readFile file) where handleNotExists action = catchIO action $ \ioe -> if isDoesNotExistError ioe then return Nothing else ioError ioe -- | Parse the package environment file. parsePackageEnvironment :: ConstraintSource -> PackageEnvironment -> String -> ParseResult PackageEnvironment parsePackageEnvironment src initial str = do fields <- readFields str let (knownSections, others) = partition isKnownSection fields pkgEnv <- parse others let config = pkgEnvSavedConfig pkgEnv installDirs0 = savedUserInstallDirs config (haddockFlags, installDirs, paths, args) <- foldM parseSections (savedHaddockFlags config, installDirs0, [], []) knownSections return pkgEnv { pkgEnvSavedConfig = config { savedConfigureFlags = (savedConfigureFlags config) { configProgramPaths = paths, configProgramArgs = args }, savedHaddockFlags = haddockFlags, savedUserInstallDirs = installDirs, savedGlobalInstallDirs = installDirs } } where isKnownSection :: ParseUtils.Field -> Bool isKnownSection (ParseUtils.Section _ "haddock" _ _) = True isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True isKnownSection _ = False parse :: [ParseUtils.Field] -> ParseResult PackageEnvironment parse = parseFields (pkgEnvFieldDescrs src) initial parseSections :: SectionsAccum -> ParseUtils.Field -> ParseResult SectionsAccum parseSections accum@(h,d,p,a) (ParseUtils.Section _ "haddock" name fs) | name == "" = do h' <- parseFields haddockFlagsFields h fs return (h', d, p, a) | otherwise = do warning "The 'haddock' section should be unnamed" return accum parseSections (h,d,p,a) (ParseUtils.Section line "install-dirs" name fs) | name == "" = do d' <- parseFields installDirsFields d fs return (h, d',p,a) | otherwise = syntaxError line $ "Named 'install-dirs' section: '" ++ name ++ "'. Note that named 'install-dirs' sections are not allowed in the '" ++ userPackageEnvironmentFile ++ "' file." parseSections accum@(h, d,p,a) (ParseUtils.Section _ "program-locations" name fs) | name == "" = do p' <- parseFields withProgramsFields p fs return (h, d, p', a) | otherwise = do warning "The 'program-locations' section should be unnamed" return accum parseSections accum@(h, d, p, a) (ParseUtils.Section _ "program-default-options" name fs) | name == "" = do a' <- parseFields withProgramOptionsFields a fs return (h, d, p, a') | otherwise = do warning "The 'program-default-options' section should be unnamed" return accum parseSections accum f = do warning $ "Unrecognized stanza on line " ++ show (lineNo f) return accum -- | Accumulator type for 'parseSections'. type SectionsAccum = (HaddockFlags, InstallDirs (Flag PathTemplate) , [(String, FilePath)], [(String, [String])]) -- | Pretty-print the package environment. showPackageEnvironment :: PackageEnvironment -> String showPackageEnvironment pkgEnv = showPackageEnvironmentWithComments Nothing pkgEnv -- | Pretty-print the package environment with default values for empty fields -- commented out (just like the default ~/.cabal/config). showPackageEnvironmentWithComments :: (Maybe PackageEnvironment) -> PackageEnvironment -> String showPackageEnvironmentWithComments mdefPkgEnv pkgEnv = Disp.render $ ppFields (pkgEnvFieldDescrs ConstraintSourceUnknown) mdefPkgEnv pkgEnv $+$ Disp.text "" $+$ ppSection "install-dirs" "" installDirsFields (fmap installDirsSection mdefPkgEnv) (installDirsSection pkgEnv) where installDirsSection = savedUserInstallDirs . pkgEnvSavedConfig
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-install/Distribution/Client/Sandbox/PackageEnvironment.hs
haskell
--------------------------------------------------------------------------- | Maintainer : Portability : portable Distribution.Client.Config. --------------------------------------------------------------------------- * Configuration saved in the package environment file TODO: would be nice to remove duplication between | Optional package environment file that can be used to customize the default settings. Created by the user. | Type of the current package environment. ^ './cabal.config' ^ '~/.cabal/config' | Is there a 'cabal.config' in this directory? | Load the user package environment if it exists (the optional "cabal.config" file). If it does not exist locally, attempt to load an optional global one. | Descriptions of all fields in the package environment file. | Read the package environment file. | Parse the package environment file. | Accumulator type for 'parseSections'. | Pretty-print the package environment. | Pretty-print the package environment with default values for empty fields commented out (just like the default ~/.cabal/config).
# LANGUAGE DeriveGeneric # Module : Distribution . Client . . PackageEnvironment Utilities for working with the package environment file . Patterned after module Distribution.Client.Sandbox.PackageEnvironment ( PackageEnvironment(..) , PackageEnvironmentType(..) , classifyPackageEnvironment , readPackageEnvironmentFile , showPackageEnvironment , showPackageEnvironmentWithComments , loadUserConfig , userPackageEnvironmentFile ) where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Client.Config ( SavedConfig(..) , configFieldDescriptions , haddockFlagsFields , installDirsFields, withProgramsFields , withProgramOptionsFields ) import Distribution.Client.ParseUtils ( parseFields, ppFields, ppSection ) import Distribution.Client.Setup ( ConfigExFlags(..) ) import Distribution.Client.Targets ( userConstraintPackageName ) import Distribution.Simple.InstallDirs ( InstallDirs(..), PathTemplate ) import Distribution.Simple.Setup ( Flag(..) , ConfigFlags(..), HaddockFlags(..) ) import Distribution.Simple.Utils ( warn, debug ) import Distribution.Solver.Types.ConstraintSource import Distribution.Deprecated.ParseUtils ( FieldDescr(..), ParseResult(..) , commaListFieldParsec, commaNewLineListFieldParsec , liftField, lineNo, locatedErrorMsg , readFields , showPWarning , syntaxError, warning ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>) ) import System.IO.Error ( isDoesNotExistError ) import Text.PrettyPrint ( ($+$) ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Deprecated.ParseUtils as ParseUtils ( Field(..) ) D.C.Sandbox . PackageEnvironment and D.C.Config . data PackageEnvironment = PackageEnvironment { pkgEnvSavedConfig :: SavedConfig } deriving Generic instance Monoid PackageEnvironment where mempty = gmempty mappend = (<>) instance Semigroup PackageEnvironment where (<>) = gmappend userPackageEnvironmentFile :: FilePath userPackageEnvironmentFile = "cabal.config" data PackageEnvironmentType classifyPackageEnvironment :: FilePath -> IO PackageEnvironmentType classifyPackageEnvironment pkgEnvDir = do isUser <- configExists userPackageEnvironmentFile return (classify isUser) where configExists fname = doesFileExist (pkgEnvDir </> fname) classify :: Bool -> PackageEnvironmentType classify True = UserPackageEnvironment classify False = AmbientPackageEnvironment userPackageEnvironment :: Verbosity -> FilePath -> Maybe FilePath -> IO PackageEnvironment userPackageEnvironment verbosity pkgEnvDir globalConfigLocation = do let path = pkgEnvDir </> userPackageEnvironmentFile minp <- readPackageEnvironmentFile (ConstraintSourceUserConfig path) mempty path case (minp, globalConfigLocation) of (Just parseRes, _) -> processConfigParse path parseRes (_, Just globalLoc) -> do minp' <- readPackageEnvironmentFile (ConstraintSourceUserConfig globalLoc) mempty globalLoc maybe (warn verbosity ("no constraints file found at " ++ globalLoc) >> return mempty) (processConfigParse globalLoc) minp' _ -> do debug verbosity ("no user package environment file found at " ++ pkgEnvDir) return mempty where processConfigParse path (ParseOk warns parseResult) = do unless (null warns) $ warn verbosity $ unlines (map (showPWarning path) warns) return parseResult processConfigParse path (ParseFailed err) = do let (line, msg) = locatedErrorMsg err warn verbosity $ "Error parsing package environment file " ++ path ++ maybe "" (\n -> ":" ++ show n) line ++ ":\n" ++ msg return mempty | Same as @userPackageEnvironmentFile@ , but returns a SavedConfig . loadUserConfig :: Verbosity -> FilePath -> Maybe FilePath -> IO SavedConfig loadUserConfig verbosity pkgEnvDir globalConfigLocation = fmap pkgEnvSavedConfig $ userPackageEnvironment verbosity pkgEnvDir globalConfigLocation pkgEnvFieldDescrs :: ConstraintSource -> [FieldDescr PackageEnvironment] pkgEnvFieldDescrs src = [ commaNewLineListFieldParsec "constraints" (pretty . fst) ((\pc -> (pc, src)) `fmap` parsec) (sortConstraints . configExConstraints . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configExConstraints = v })) , commaListFieldParsec "preferences" pretty parsec (configPreferences . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configPreferences = v })) ] ++ map toPkgEnv configFieldDescriptions' where configFieldDescriptions' :: [FieldDescr SavedConfig] configFieldDescriptions' = filter (\(FieldDescr name _ _) -> name /= "preference" && name /= "constraint") (configFieldDescriptions src) toPkgEnv :: FieldDescr SavedConfig -> FieldDescr PackageEnvironment toPkgEnv fieldDescr = liftField pkgEnvSavedConfig (\savedConfig pkgEnv -> pkgEnv { pkgEnvSavedConfig = savedConfig}) fieldDescr updateConfigureExFlags :: PackageEnvironment -> (ConfigExFlags -> ConfigExFlags) -> PackageEnvironment updateConfigureExFlags pkgEnv f = pkgEnv { pkgEnvSavedConfig = (pkgEnvSavedConfig pkgEnv) { savedConfigureExFlags = f . savedConfigureExFlags . pkgEnvSavedConfig $ pkgEnv } } sortConstraints = sortBy (comparing $ userConstraintPackageName . fst) readPackageEnvironmentFile :: ConstraintSource -> PackageEnvironment -> FilePath -> IO (Maybe (ParseResult PackageEnvironment)) readPackageEnvironmentFile src initial file = handleNotExists $ fmap (Just . parsePackageEnvironment src initial) (readFile file) where handleNotExists action = catchIO action $ \ioe -> if isDoesNotExistError ioe then return Nothing else ioError ioe parsePackageEnvironment :: ConstraintSource -> PackageEnvironment -> String -> ParseResult PackageEnvironment parsePackageEnvironment src initial str = do fields <- readFields str let (knownSections, others) = partition isKnownSection fields pkgEnv <- parse others let config = pkgEnvSavedConfig pkgEnv installDirs0 = savedUserInstallDirs config (haddockFlags, installDirs, paths, args) <- foldM parseSections (savedHaddockFlags config, installDirs0, [], []) knownSections return pkgEnv { pkgEnvSavedConfig = config { savedConfigureFlags = (savedConfigureFlags config) { configProgramPaths = paths, configProgramArgs = args }, savedHaddockFlags = haddockFlags, savedUserInstallDirs = installDirs, savedGlobalInstallDirs = installDirs } } where isKnownSection :: ParseUtils.Field -> Bool isKnownSection (ParseUtils.Section _ "haddock" _ _) = True isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True isKnownSection _ = False parse :: [ParseUtils.Field] -> ParseResult PackageEnvironment parse = parseFields (pkgEnvFieldDescrs src) initial parseSections :: SectionsAccum -> ParseUtils.Field -> ParseResult SectionsAccum parseSections accum@(h,d,p,a) (ParseUtils.Section _ "haddock" name fs) | name == "" = do h' <- parseFields haddockFlagsFields h fs return (h', d, p, a) | otherwise = do warning "The 'haddock' section should be unnamed" return accum parseSections (h,d,p,a) (ParseUtils.Section line "install-dirs" name fs) | name == "" = do d' <- parseFields installDirsFields d fs return (h, d',p,a) | otherwise = syntaxError line $ "Named 'install-dirs' section: '" ++ name ++ "'. Note that named 'install-dirs' sections are not allowed in the '" ++ userPackageEnvironmentFile ++ "' file." parseSections accum@(h, d,p,a) (ParseUtils.Section _ "program-locations" name fs) | name == "" = do p' <- parseFields withProgramsFields p fs return (h, d, p', a) | otherwise = do warning "The 'program-locations' section should be unnamed" return accum parseSections accum@(h, d, p, a) (ParseUtils.Section _ "program-default-options" name fs) | name == "" = do a' <- parseFields withProgramOptionsFields a fs return (h, d, p, a') | otherwise = do warning "The 'program-default-options' section should be unnamed" return accum parseSections accum f = do warning $ "Unrecognized stanza on line " ++ show (lineNo f) return accum type SectionsAccum = (HaddockFlags, InstallDirs (Flag PathTemplate) , [(String, FilePath)], [(String, [String])]) showPackageEnvironment :: PackageEnvironment -> String showPackageEnvironment pkgEnv = showPackageEnvironmentWithComments Nothing pkgEnv showPackageEnvironmentWithComments :: (Maybe PackageEnvironment) -> PackageEnvironment -> String showPackageEnvironmentWithComments mdefPkgEnv pkgEnv = Disp.render $ ppFields (pkgEnvFieldDescrs ConstraintSourceUnknown) mdefPkgEnv pkgEnv $+$ Disp.text "" $+$ ppSection "install-dirs" "" installDirsFields (fmap installDirsSection mdefPkgEnv) (installDirsSection pkgEnv) where installDirsSection = savedUserInstallDirs . pkgEnvSavedConfig
05ffeac66efe4f06e8407cf75b507ebbea7709532995bbedaa6edcbe6687784a
apache/couchdb-couch
couch_httpd_proxy.erl
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not % use this file except in compliance with the License. You may obtain a copy of % the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT % WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the % License for the specific language governing permissions and limitations under % the License. -module(couch_httpd_proxy). -export([handle_proxy_req/2]). -include_lib("couch/include/couch_db.hrl"). -include_lib("ibrowse/include/ibrowse.hrl"). -define(TIMEOUT, infinity). -define(PKT_SIZE, 4096). handle_proxy_req(Req, ProxyDest) -> Method = get_method(Req), Url = get_url(Req, ProxyDest), Version = get_version(Req), Headers = get_headers(Req), Body = get_body(Req), Options = [ {http_vsn, Version}, {headers_as_is, true}, {response_format, binary}, {stream_to, {self(), once}} ], case ibrowse:send_req(Url, Headers, Method, Body, Options, ?TIMEOUT) of {ibrowse_req_id, ReqId} -> stream_response(Req, ProxyDest, ReqId); {error, Reason} -> throw({error, Reason}) end. get_method(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(method) of Method when is_atom(Method) -> list_to_atom(string:to_lower(atom_to_list(Method))); Method when is_list(Method) -> list_to_atom(string:to_lower(Method)); Method when is_binary(Method) -> list_to_atom(string:to_lower(?b2l(Method))) end. get_url(Req, ProxyDest) when is_binary(ProxyDest) -> get_url(Req, ?b2l(ProxyDest)); get_url(#httpd{mochi_req=MochiReq}=Req, ProxyDest) -> BaseUrl = case mochiweb_util:partition(ProxyDest, "/") of {[], "/", _} -> couch_httpd:absolute_uri(Req, ProxyDest); _ -> ProxyDest end, ProxyPrefix = "/" ++ ?b2l(hd(Req#httpd.path_parts)), RequestedPath = MochiReq:get(raw_path), case mochiweb_util:partition(RequestedPath, ProxyPrefix) of {[], ProxyPrefix, []} -> BaseUrl; {[], ProxyPrefix, [$/ | DestPath]} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; {[], ProxyPrefix, DestPath} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; _Else -> throw({invalid_url_path, {ProxyPrefix, RequestedPath}}) end. get_version(#httpd{mochi_req=MochiReq}) -> MochiReq:get(version). get_headers(#httpd{mochi_req=MochiReq}) -> to_ibrowse_headers(mochiweb_headers:to_list(MochiReq:get(headers)), []). to_ibrowse_headers([], Acc) -> lists:reverse(Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_atom(K) -> to_ibrowse_headers([{atom_to_list(K), V} | Rest], Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_list(K) -> case string:to_lower(K) of "content-length" -> to_ibrowse_headers(Rest, [{content_length, V} | Acc]); % This appears to make ibrowse too smart. %"transfer-encoding" -> % to_ibrowse_headers(Rest, [{transfer_encoding, V} | Acc]); _ -> to_ibrowse_headers(Rest, [{K, V} | Acc]) end. get_body(#httpd{method='GET'}) -> fun() -> eof end; get_body(#httpd{method='HEAD'}) -> fun() -> eof end; get_body(#httpd{method='DELETE'}) -> fun() -> eof end; get_body(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(body_length) of undefined -> <<>>; {unknown_transfer_encoding, Unknown} -> exit({unknown_transfer_encoding, Unknown}); chunked -> {fun stream_chunked_body/1, {init, MochiReq, 0}}; 0 -> <<>>; Length when is_integer(Length) andalso Length > 0 -> {fun stream_length_body/1, {init, MochiReq, Length}}; Length -> exit({invalid_body_length, Length}) end. remove_trailing_slash(Url) -> rem_slash(lists:reverse(Url)). rem_slash([]) -> []; rem_slash([$\s | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\t | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\r | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\n | RevUrl]) -> rem_slash(RevUrl); rem_slash([$/ | RevUrl]) -> rem_slash(RevUrl); rem_slash(RevUrl) -> lists:reverse(RevUrl). stream_chunked_body({init, MReq, 0}) -> First chunk , do expect - continue dance . init_body_stream(MReq), stream_chunked_body({stream, MReq, 0, [], ?PKT_SIZE}); stream_chunked_body({stream, MReq, 0, Buf, BRem}) -> % Finished a chunk, get next length. If next length % is 0, its time to try and read trailers. {CRem, Data} = read_chunk_length(MReq), case CRem of 0 -> BodyData = lists:reverse(Buf, Data), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; _ -> stream_chunked_body( {stream, MReq, CRem, [Data | Buf], BRem-size(Data)} ) end; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) when BRem =< 0 -> Time to empty our buffers to the upstream socket . BodyData = lists:reverse(Buf), {ok, BodyData, {stream, MReq, CRem, [], ?PKT_SIZE}}; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) -> % Buffer some more data from the client. Length = lists:min([CRem, BRem]), Socket = MReq:get(socket), NewState = case mochiweb_socket:recv(Socket, Length, ?TIMEOUT) of {ok, Data} when size(Data) == CRem -> case mochiweb_socket:recv(Socket, 2, ?TIMEOUT) of {ok, <<"\r\n">>} -> {stream, MReq, 0, [<<"\r\n">>, Data | Buf], BRem-Length-2}; _ -> exit(normal) end; {ok, Data} -> {stream, MReq, CRem-Length, [Data | Buf], BRem-Length}; _ -> exit(normal) end, stream_chunked_body(NewState); stream_chunked_body({trailers, MReq, Buf, BRem}) when BRem =< 0 -> % Empty our buffers and send data upstream. BodyData = lists:reverse(Buf), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; stream_chunked_body({trailers, MReq, Buf, BRem}) -> % Read another trailer into the buffer or stop on an % empty line. Socket = MReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, <<"\r\n">>} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), BodyData = lists:reverse(Buf, <<"\r\n">>), {ok, BodyData, eof}; {ok, Footer} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), NewState = {trailers, MReq, [Footer | Buf], BRem-size(Footer)}, stream_chunked_body(NewState); _ -> exit(normal) end; stream_chunked_body(eof) -> % Tell ibrowse we're done sending data. eof. stream_length_body({init, MochiReq, Length}) -> % Do the expect-continue dance init_body_stream(MochiReq), stream_length_body({stream, MochiReq, Length}); stream_length_body({stream, _MochiReq, 0}) -> % Finished streaming. eof; stream_length_body({stream, MochiReq, Length}) -> BufLen = lists:min([Length, ?PKT_SIZE]), case MochiReq:recv(BufLen) of <<>> -> eof; Bin -> {ok, Bin, {stream, MochiReq, Length-BufLen}} end. init_body_stream(MochiReq) -> Expect = case MochiReq:get_header_value("expect") of undefined -> undefined; Value when is_list(Value) -> string:to_lower(Value) end, case Expect of "100-continue" -> MochiReq:start_raw_response({100, gb_trees:empty()}); _Else -> ok end. read_chunk_length(MochiReq) -> Socket = MochiReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, Header} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), Splitter = fun(C) -> C =/= $\r andalso C =/= $\n andalso C =/= $\s end, {Hex, _Rest} = lists:splitwith(Splitter, ?b2l(Header)), {mochihex:to_int(Hex), Header}; _ -> exit(normal) end. stream_response(Req, ProxyDest, ReqId) -> receive {ibrowse_async_headers, ReqId, "100", _} -> ibrowse does n't handle 100 Continue responses which % means we have to discard them so the proxy client % doesn't get confused. ibrowse:stream_next(ReqId), stream_response(Req, ProxyDest, ReqId); {ibrowse_async_headers, ReqId, Status, Headers} -> {Source, Dest} = get_urls(Req, ProxyDest), FixedHeaders = fix_headers(Source, Dest, Headers, []), case body_length(FixedHeaders) of chunked -> {ok, Resp} = couch_httpd:start_chunked_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp), {ok, Resp}; Length when is_integer(Length) -> {ok, Resp} = couch_httpd:start_response_length( Req, list_to_integer(Status), FixedHeaders, Length ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), {ok, Resp}; _ -> {ok, Resp} = couch_httpd:start_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), XXX : MochiWeb apparently does n't look at the % response to see if it must force close the % connection. So we help it out here. erlang:put(mochiweb_request_force_close, true), {ok, Resp} end end. stream_chunked_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send_chunk(Resp, Chunk), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> couch_httpd:last_chunk(Resp) end. stream_length_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send(Resp, Chunk), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> ok end. get_urls(Req, ProxyDest) -> SourceUrl = couch_httpd:absolute_uri(Req, "/" ++ hd(Req#httpd.path_parts)), Source = parse_url(?b2l(iolist_to_binary(SourceUrl))), case (catch parse_url(ProxyDest)) of Dest when is_record(Dest, url) -> {Source, Dest}; _ -> DestUrl = couch_httpd:absolute_uri(Req, ProxyDest), {Source, parse_url(DestUrl)} end. fix_headers(_, _, [], Acc) -> lists:reverse(Acc); fix_headers(Source, Dest, [{K, V} | Rest], Acc) -> Fixed = case string:to_lower(K) of "location" -> rewrite_location(Source, Dest, V); "content-location" -> rewrite_location(Source, Dest, V); "uri" -> rewrite_location(Source, Dest, V); "destination" -> rewrite_location(Source, Dest, V); "set-cookie" -> rewrite_cookie(Source, Dest, V); _ -> V end, fix_headers(Source, Dest, Rest, [{K, Fixed} | Acc]). rewrite_location(Source, #url{host=Host, port=Port, protocol=Proto}, Url) -> case (catch parse_url(Url)) of #url{host=Host, port=Port, protocol=Proto} = Location -> DestLoc = #url{ protocol=Source#url.protocol, host=Source#url.host, port=Source#url.port, path=join_url_path(Source#url.path, Location#url.path) }, url_to_url(DestLoc); #url{} -> Url; _ -> url_to_url(Source#url{path=join_url_path(Source#url.path, Url)}) end. rewrite_cookie(_Source, _Dest, Cookie) -> Cookie. parse_url(Url) when is_binary(Url) -> ibrowse_lib:parse_url(?b2l(Url)); parse_url(Url) when is_list(Url) -> ibrowse_lib:parse_url(?b2l(iolist_to_binary(Url))). join_url_path(Src, Dst) -> Src2 = case lists:reverse(Src) of "/" ++ RestSrc -> lists:reverse(RestSrc); _ -> Src end, Dst2 = case Dst of "/" ++ RestDst -> RestDst; _ -> Dst end, Src2 ++ "/" ++ Dst2. url_to_url(#url{host=Host, port=Port, path=Path, protocol=Proto} = Url) -> LPort = case {Proto, Port} of {http, 80} -> ""; {https, 443} -> ""; _ -> ":" ++ integer_to_list(Port) end, LPath = case Path of "/" ++ _RestPath -> Path; _ -> "/" ++ Path end, HostPart = case Url#url.host_type of ipv6_address -> "[" ++ Host ++ "]"; _ -> Host end, atom_to_list(Proto) ++ "://" ++ HostPart ++ LPort ++ LPath. body_length(Headers) -> case is_chunked(Headers) of true -> chunked; _ -> content_length(Headers) end. is_chunked([]) -> false; is_chunked([{K, V} | Rest]) -> case string:to_lower(K) of "transfer-encoding" -> string:to_lower(V) == "chunked"; _ -> is_chunked(Rest) end. content_length([]) -> undefined; content_length([{K, V} | Rest]) -> case string:to_lower(K) of "content-length" -> list_to_integer(V); _ -> content_length(Rest) end.
null
https://raw.githubusercontent.com/apache/couchdb-couch/21c8d37ac6ee1a7fed1de1f54f95a4d3cd9f5248/src/couch_httpd_proxy.erl
erlang
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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This appears to make ibrowse too smart. "transfer-encoding" -> to_ibrowse_headers(Rest, [{transfer_encoding, V} | Acc]); Finished a chunk, get next length. If next length is 0, its time to try and read trailers. Buffer some more data from the client. Empty our buffers and send data upstream. Read another trailer into the buffer or stop on an empty line. Tell ibrowse we're done sending data. Do the expect-continue dance Finished streaming. means we have to discard them so the proxy client doesn't get confused. response to see if it must force close the connection. So we help it out here.
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(couch_httpd_proxy). -export([handle_proxy_req/2]). -include_lib("couch/include/couch_db.hrl"). -include_lib("ibrowse/include/ibrowse.hrl"). -define(TIMEOUT, infinity). -define(PKT_SIZE, 4096). handle_proxy_req(Req, ProxyDest) -> Method = get_method(Req), Url = get_url(Req, ProxyDest), Version = get_version(Req), Headers = get_headers(Req), Body = get_body(Req), Options = [ {http_vsn, Version}, {headers_as_is, true}, {response_format, binary}, {stream_to, {self(), once}} ], case ibrowse:send_req(Url, Headers, Method, Body, Options, ?TIMEOUT) of {ibrowse_req_id, ReqId} -> stream_response(Req, ProxyDest, ReqId); {error, Reason} -> throw({error, Reason}) end. get_method(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(method) of Method when is_atom(Method) -> list_to_atom(string:to_lower(atom_to_list(Method))); Method when is_list(Method) -> list_to_atom(string:to_lower(Method)); Method when is_binary(Method) -> list_to_atom(string:to_lower(?b2l(Method))) end. get_url(Req, ProxyDest) when is_binary(ProxyDest) -> get_url(Req, ?b2l(ProxyDest)); get_url(#httpd{mochi_req=MochiReq}=Req, ProxyDest) -> BaseUrl = case mochiweb_util:partition(ProxyDest, "/") of {[], "/", _} -> couch_httpd:absolute_uri(Req, ProxyDest); _ -> ProxyDest end, ProxyPrefix = "/" ++ ?b2l(hd(Req#httpd.path_parts)), RequestedPath = MochiReq:get(raw_path), case mochiweb_util:partition(RequestedPath, ProxyPrefix) of {[], ProxyPrefix, []} -> BaseUrl; {[], ProxyPrefix, [$/ | DestPath]} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; {[], ProxyPrefix, DestPath} -> remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath; _Else -> throw({invalid_url_path, {ProxyPrefix, RequestedPath}}) end. get_version(#httpd{mochi_req=MochiReq}) -> MochiReq:get(version). get_headers(#httpd{mochi_req=MochiReq}) -> to_ibrowse_headers(mochiweb_headers:to_list(MochiReq:get(headers)), []). to_ibrowse_headers([], Acc) -> lists:reverse(Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_atom(K) -> to_ibrowse_headers([{atom_to_list(K), V} | Rest], Acc); to_ibrowse_headers([{K, V} | Rest], Acc) when is_list(K) -> case string:to_lower(K) of "content-length" -> to_ibrowse_headers(Rest, [{content_length, V} | Acc]); _ -> to_ibrowse_headers(Rest, [{K, V} | Acc]) end. get_body(#httpd{method='GET'}) -> fun() -> eof end; get_body(#httpd{method='HEAD'}) -> fun() -> eof end; get_body(#httpd{method='DELETE'}) -> fun() -> eof end; get_body(#httpd{mochi_req=MochiReq}) -> case MochiReq:get(body_length) of undefined -> <<>>; {unknown_transfer_encoding, Unknown} -> exit({unknown_transfer_encoding, Unknown}); chunked -> {fun stream_chunked_body/1, {init, MochiReq, 0}}; 0 -> <<>>; Length when is_integer(Length) andalso Length > 0 -> {fun stream_length_body/1, {init, MochiReq, Length}}; Length -> exit({invalid_body_length, Length}) end. remove_trailing_slash(Url) -> rem_slash(lists:reverse(Url)). rem_slash([]) -> []; rem_slash([$\s | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\t | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\r | RevUrl]) -> rem_slash(RevUrl); rem_slash([$\n | RevUrl]) -> rem_slash(RevUrl); rem_slash([$/ | RevUrl]) -> rem_slash(RevUrl); rem_slash(RevUrl) -> lists:reverse(RevUrl). stream_chunked_body({init, MReq, 0}) -> First chunk , do expect - continue dance . init_body_stream(MReq), stream_chunked_body({stream, MReq, 0, [], ?PKT_SIZE}); stream_chunked_body({stream, MReq, 0, Buf, BRem}) -> {CRem, Data} = read_chunk_length(MReq), case CRem of 0 -> BodyData = lists:reverse(Buf, Data), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; _ -> stream_chunked_body( {stream, MReq, CRem, [Data | Buf], BRem-size(Data)} ) end; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) when BRem =< 0 -> Time to empty our buffers to the upstream socket . BodyData = lists:reverse(Buf), {ok, BodyData, {stream, MReq, CRem, [], ?PKT_SIZE}}; stream_chunked_body({stream, MReq, CRem, Buf, BRem}) -> Length = lists:min([CRem, BRem]), Socket = MReq:get(socket), NewState = case mochiweb_socket:recv(Socket, Length, ?TIMEOUT) of {ok, Data} when size(Data) == CRem -> case mochiweb_socket:recv(Socket, 2, ?TIMEOUT) of {ok, <<"\r\n">>} -> {stream, MReq, 0, [<<"\r\n">>, Data | Buf], BRem-Length-2}; _ -> exit(normal) end; {ok, Data} -> {stream, MReq, CRem-Length, [Data | Buf], BRem-Length}; _ -> exit(normal) end, stream_chunked_body(NewState); stream_chunked_body({trailers, MReq, Buf, BRem}) when BRem =< 0 -> BodyData = lists:reverse(Buf), {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}}; stream_chunked_body({trailers, MReq, Buf, BRem}) -> Socket = MReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, <<"\r\n">>} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), BodyData = lists:reverse(Buf, <<"\r\n">>), {ok, BodyData, eof}; {ok, Footer} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), NewState = {trailers, MReq, [Footer | Buf], BRem-size(Footer)}, stream_chunked_body(NewState); _ -> exit(normal) end; stream_chunked_body(eof) -> eof. stream_length_body({init, MochiReq, Length}) -> init_body_stream(MochiReq), stream_length_body({stream, MochiReq, Length}); stream_length_body({stream, _MochiReq, 0}) -> eof; stream_length_body({stream, MochiReq, Length}) -> BufLen = lists:min([Length, ?PKT_SIZE]), case MochiReq:recv(BufLen) of <<>> -> eof; Bin -> {ok, Bin, {stream, MochiReq, Length-BufLen}} end. init_body_stream(MochiReq) -> Expect = case MochiReq:get_header_value("expect") of undefined -> undefined; Value when is_list(Value) -> string:to_lower(Value) end, case Expect of "100-continue" -> MochiReq:start_raw_response({100, gb_trees:empty()}); _Else -> ok end. read_chunk_length(MochiReq) -> Socket = MochiReq:get(socket), mochiweb_socket:setopts(Socket, [{packet, line}]), case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of {ok, Header} -> mochiweb_socket:setopts(Socket, [{packet, raw}]), Splitter = fun(C) -> C =/= $\r andalso C =/= $\n andalso C =/= $\s end, {Hex, _Rest} = lists:splitwith(Splitter, ?b2l(Header)), {mochihex:to_int(Hex), Header}; _ -> exit(normal) end. stream_response(Req, ProxyDest, ReqId) -> receive {ibrowse_async_headers, ReqId, "100", _} -> ibrowse does n't handle 100 Continue responses which ibrowse:stream_next(ReqId), stream_response(Req, ProxyDest, ReqId); {ibrowse_async_headers, ReqId, Status, Headers} -> {Source, Dest} = get_urls(Req, ProxyDest), FixedHeaders = fix_headers(Source, Dest, Headers, []), case body_length(FixedHeaders) of chunked -> {ok, Resp} = couch_httpd:start_chunked_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp), {ok, Resp}; Length when is_integer(Length) -> {ok, Resp} = couch_httpd:start_response_length( Req, list_to_integer(Status), FixedHeaders, Length ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), {ok, Resp}; _ -> {ok, Resp} = couch_httpd:start_response( Req, list_to_integer(Status), FixedHeaders ), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp), XXX : MochiWeb apparently does n't look at the erlang:put(mochiweb_request_force_close, true), {ok, Resp} end end. stream_chunked_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send_chunk(Resp, Chunk), ibrowse:stream_next(ReqId), stream_chunked_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> couch_httpd:last_chunk(Resp) end. stream_length_response(Req, ReqId, Resp) -> receive {ibrowse_async_response, ReqId, {error, Reason}} -> throw({error, Reason}); {ibrowse_async_response, ReqId, Chunk} -> couch_httpd:send(Resp, Chunk), ibrowse:stream_next(ReqId), stream_length_response(Req, ReqId, Resp); {ibrowse_async_response_end, ReqId} -> ok end. get_urls(Req, ProxyDest) -> SourceUrl = couch_httpd:absolute_uri(Req, "/" ++ hd(Req#httpd.path_parts)), Source = parse_url(?b2l(iolist_to_binary(SourceUrl))), case (catch parse_url(ProxyDest)) of Dest when is_record(Dest, url) -> {Source, Dest}; _ -> DestUrl = couch_httpd:absolute_uri(Req, ProxyDest), {Source, parse_url(DestUrl)} end. fix_headers(_, _, [], Acc) -> lists:reverse(Acc); fix_headers(Source, Dest, [{K, V} | Rest], Acc) -> Fixed = case string:to_lower(K) of "location" -> rewrite_location(Source, Dest, V); "content-location" -> rewrite_location(Source, Dest, V); "uri" -> rewrite_location(Source, Dest, V); "destination" -> rewrite_location(Source, Dest, V); "set-cookie" -> rewrite_cookie(Source, Dest, V); _ -> V end, fix_headers(Source, Dest, Rest, [{K, Fixed} | Acc]). rewrite_location(Source, #url{host=Host, port=Port, protocol=Proto}, Url) -> case (catch parse_url(Url)) of #url{host=Host, port=Port, protocol=Proto} = Location -> DestLoc = #url{ protocol=Source#url.protocol, host=Source#url.host, port=Source#url.port, path=join_url_path(Source#url.path, Location#url.path) }, url_to_url(DestLoc); #url{} -> Url; _ -> url_to_url(Source#url{path=join_url_path(Source#url.path, Url)}) end. rewrite_cookie(_Source, _Dest, Cookie) -> Cookie. parse_url(Url) when is_binary(Url) -> ibrowse_lib:parse_url(?b2l(Url)); parse_url(Url) when is_list(Url) -> ibrowse_lib:parse_url(?b2l(iolist_to_binary(Url))). join_url_path(Src, Dst) -> Src2 = case lists:reverse(Src) of "/" ++ RestSrc -> lists:reverse(RestSrc); _ -> Src end, Dst2 = case Dst of "/" ++ RestDst -> RestDst; _ -> Dst end, Src2 ++ "/" ++ Dst2. url_to_url(#url{host=Host, port=Port, path=Path, protocol=Proto} = Url) -> LPort = case {Proto, Port} of {http, 80} -> ""; {https, 443} -> ""; _ -> ":" ++ integer_to_list(Port) end, LPath = case Path of "/" ++ _RestPath -> Path; _ -> "/" ++ Path end, HostPart = case Url#url.host_type of ipv6_address -> "[" ++ Host ++ "]"; _ -> Host end, atom_to_list(Proto) ++ "://" ++ HostPart ++ LPort ++ LPath. body_length(Headers) -> case is_chunked(Headers) of true -> chunked; _ -> content_length(Headers) end. is_chunked([]) -> false; is_chunked([{K, V} | Rest]) -> case string:to_lower(K) of "transfer-encoding" -> string:to_lower(V) == "chunked"; _ -> is_chunked(Rest) end. content_length([]) -> undefined; content_length([{K, V} | Rest]) -> case string:to_lower(K) of "content-length" -> list_to_integer(V); _ -> content_length(Rest) end.
ac0bf0466a7c67a8a9cdd19e0a30a48f7f933d2d26ebf6395cbb41723899137d
manuel-serrano/bigloo
ast.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / comptime / Write / ast.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Sat Dec 31 07:29:03 1994 * / * Last change : Fri Mar 18 11:43:48 2011 ( serrano ) * / * Copyright : 1994 - 2020 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* The ast pretty-printer */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module write_ast (include "Engine/pass.sch" "Ast/node.sch") (import engine_param init_main write_scheme type_pptype tools_shape tools_args) (export (write-ast ast))) ;*---------------------------------------------------------------------*/ ;* write-ast ... */ ;*---------------------------------------------------------------------*/ (define (write-ast globals) (profile write (let* ((output-name (if (string? *dest*) *dest* (if (and (pair? *src-files*) (string? (car *src-files*))) (string-append (prefix (car *src-files*)) "." (symbol->string *pass*) ".ast") #f))) (port (if (string? output-name) (open-output-file output-name) (current-output-port)))) (if (not (output-port? port)) (error "write-ast" "Can't open output file" output-name) (unwind-protect (begin (if (not *ast-case-sensitive*) (set! *pp-case* 'lower)) (write-scheme-file-header port (string-append "The AST (" *current-pass* ")")) (for-each (lambda (g) (let ((fun (global-value g))) (write-scheme-comment port (shape g)) (write-scheme-comment port (function-type->string g)) (write-scheme-comment port (make-sfun-sinfo g)) (pp `(,(case (sfun-class fun) ((sgfun) 'define-generic) ((sifun) 'define-inline) ((smfun) 'define-method) (else 'define)) ,(cons (shape g) (args-list->args* (map shape (sfun-args fun)) (sfun-arity fun))) ,(shape (sfun-body fun))) port))) globals)) (close-output-port port)))))) ;*---------------------------------------------------------------------*/ ;* make-sfun-sinfo ... */ ;*---------------------------------------------------------------------*/ (define (make-sfun-sinfo::bstring g::global) (define (atom->string atom) (case atom ((#t) "#t") ((#f) "#f") ((#unspecified) "#unspecified") (else (cond ((symbol? atom) (if *ast-case-sensitive* (symbol->string atom) (string-downcase (symbol->string atom)))) ((number? atom) (number->string atom)) ((string? atom) atom) (else (let ((p (open-output-string))) (display atom p) (close-output-port p))))))) (let ((sfun (global-value g))) (string-append "[" (if *ast-case-sensitive* (symbol->string (global-import g)) (string-downcase (symbol->string (global-import g)))) " side-effect: " (atom->string (sfun-side-effect sfun)) (let ((t (sfun-predicate-of sfun))) (if (type? t) (string-append " predicate-of: " (atom->string (shape t))) "")) " occ: " (integer->string (global-occurrence g)) " rm: " (atom->string (global-removable g)) " loc: " (let ((p (open-output-string))) (display (sfun-loc sfun) p) (close-output-port p)) (if (global-user? g) " user?: #t" " user?: #f") " removable: " (with-output-to-string (lambda () (display (global-removable g)))) "]")))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/comptime/Write/ast.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The ast pretty-printer */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * write-ast ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * make-sfun-sinfo ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / comptime / Write / ast.scm * / * Author : * / * Creation : Sat Dec 31 07:29:03 1994 * / * Last change : Fri Mar 18 11:43:48 2011 ( serrano ) * / * Copyright : 1994 - 2020 , see LICENSE file * / (module write_ast (include "Engine/pass.sch" "Ast/node.sch") (import engine_param init_main write_scheme type_pptype tools_shape tools_args) (export (write-ast ast))) (define (write-ast globals) (profile write (let* ((output-name (if (string? *dest*) *dest* (if (and (pair? *src-files*) (string? (car *src-files*))) (string-append (prefix (car *src-files*)) "." (symbol->string *pass*) ".ast") #f))) (port (if (string? output-name) (open-output-file output-name) (current-output-port)))) (if (not (output-port? port)) (error "write-ast" "Can't open output file" output-name) (unwind-protect (begin (if (not *ast-case-sensitive*) (set! *pp-case* 'lower)) (write-scheme-file-header port (string-append "The AST (" *current-pass* ")")) (for-each (lambda (g) (let ((fun (global-value g))) (write-scheme-comment port (shape g)) (write-scheme-comment port (function-type->string g)) (write-scheme-comment port (make-sfun-sinfo g)) (pp `(,(case (sfun-class fun) ((sgfun) 'define-generic) ((sifun) 'define-inline) ((smfun) 'define-method) (else 'define)) ,(cons (shape g) (args-list->args* (map shape (sfun-args fun)) (sfun-arity fun))) ,(shape (sfun-body fun))) port))) globals)) (close-output-port port)))))) (define (make-sfun-sinfo::bstring g::global) (define (atom->string atom) (case atom ((#t) "#t") ((#f) "#f") ((#unspecified) "#unspecified") (else (cond ((symbol? atom) (if *ast-case-sensitive* (symbol->string atom) (string-downcase (symbol->string atom)))) ((number? atom) (number->string atom)) ((string? atom) atom) (else (let ((p (open-output-string))) (display atom p) (close-output-port p))))))) (let ((sfun (global-value g))) (string-append "[" (if *ast-case-sensitive* (symbol->string (global-import g)) (string-downcase (symbol->string (global-import g)))) " side-effect: " (atom->string (sfun-side-effect sfun)) (let ((t (sfun-predicate-of sfun))) (if (type? t) (string-append " predicate-of: " (atom->string (shape t))) "")) " occ: " (integer->string (global-occurrence g)) " rm: " (atom->string (global-removable g)) " loc: " (let ((p (open-output-string))) (display (sfun-loc sfun) p) (close-output-port p)) (if (global-user? g) " user?: #t" " user?: #f") " removable: " (with-output-to-string (lambda () (display (global-removable g)))) "]")))
9a9ad9144b1f8db8e66efdae8da9107775bb139875621c0de39657a000827db6
gwathlobal/CotD
level-modifier.lisp
(in-package :cotd) ;;--------------------------------- ;; LEVEL-MOD-TYPE Constants ;;--------------------------------- (defenum:defenum level-mod-type-enum (:level-mod-controlled-by :level-mod-sector-feat :level-mod-sector-item :level-mod-tod :level-mod-weather :level-mod-player-placement :level-mod-misc)) (defconstant +level-mod-controlled-by+ 0) (defconstant +level-mod-sector-feat+ 1) (defconstant +level-mod-sector-item+ 2) (defconstant +level-mod-time-of-day+ 3) (defconstant +level-mod-weather+ 4) (defconstant +level-mod-player-placement+ 5) (defconstant +level-mod-misc+ 6) ;;--------------------------------- ;; LEVEL-MODIFIER Constants ;;--------------------------------- (defconstant +lm-controlled-by-none+ 0) (defconstant +lm-controlled-by-demons+ 1) (defconstant +lm-controlled-by-military+ 2) (defconstant +lm-feat-river+ 3) (defconstant +lm-feat-sea+ 4) (defconstant +lm-feat-barricade+ 5) (defconstant +lm-feat-library+ 6) (defconstant +lm-feat-church+ 7) (defconstant +lm-feat-lair+ 8) (defconstant +lm-item-book-of-rituals+ 9) (defconstant +lm-item-holy-relic+ 10) (defconstant +lm-tod-morning+ 11) (defconstant +lm-tod-noon+ 12) (defconstant +lm-tod-evening+ 13) (defconstant +lm-tod-night+ 14) (defconstant +lm-weather-rain+ 15) (defconstant +lm-weather-snow+ 16) (defconstant +lm-placement-player+ 17) (defconstant +lm-placement-dead-player+ 18) (defconstant +lm-placement-angel-chrome+ 19) (defconstant +lm-placement-angel-trinity+ 20) (defconstant +lm-placement-demon-crimson+ 21) (defconstant +lm-placement-demon-shadow+ 22) (defconstant +lm-placement-demon-malseraph+ 23) (defconstant +lm-placement-military-chaplain+ 24) (defconstant +lm-placement-military-scout+ 25) (defconstant +lm-placement-priest+ 26) (defconstant +lm-placement-satanist+ 27) (defconstant +lm-placement-eater+ 28) (defconstant +lm-placement-skinchanger+ 29) (defconstant +lm-placement-thief+ 30) (defconstant +lm-placement-ghost+ 31) (defconstant +lm-placement-test+ 32) (defconstant +lm-tod-hell+ 33) (defconstant +lm-feat-hell-engine+ 34) (defconstant +lm-feat-hell-flesh-storage+ 35) (defconstant +lm-weather-acid-rain+ 36) (defconstant +lm-misc-eater-incursion+ 37) (defconstant +lm-misc-malseraphs-blessing+ 38) (defparameter *level-modifiers* (make-array (list 0) :adjustable t)) (defclass level-modifier () ((id :initarg :id :accessor id) (name :initarg :name :accessor name) (priority :initform 0 :initarg :priority :accessor priority) (lm-type :initarg :lm-type :accessor lm-type :type level-mod-type-enum) (lm-debug :initform nil :initarg :lm-debug :accessor lm-debug :type boolean) (disabled :initform nil :initarg :disabled :accessor disabled :type boolean) (template-level-gen-func :initform nil :initarg :template-level-gen-func :accessor template-level-gen-func) (overall-post-process-func-list :initform nil :initarg :overall-post-process-func-list :accessor overall-post-process-func-list) (terrain-post-process-func-list :initform nil :initarg :terrain-post-process-func-list :accessor terrain-post-process-func-list) (faction-list-func :initform nil :initarg :faction-list-func :accessor faction-list-func) ;; the func that takes world-sector-type and returns a list of faction-ids (is-available-for-mission :initform nil :initarg :is-available-for-mission :accessor is-available-for-mission) ;; takes world-sector-type-id, mission-type-id and world-time (random-available-for-mission :initform nil :initarg :random-available-for-mission :accessor random-available-for-mission) (scenario-enabled-func :initform nil :initarg :scenario-enabled-func :accessor scenario-enabled-func) (scenario-disabled-func :initform nil :initarg :scenario-disabled-func :accessor scenario-disabled-func) (depends-on-lvl-mod-func :initform nil :initarg :depends-on-lvl-mod-func :accessor depends-on-lvl-mod-func) ;; takes world-sector, mission-type-id and world-time (always-present-func :initform nil :initarg :always-present-func :accessor always-present-func) ;; takes world-sector, mission and world-time )) (defun set-level-modifier (&key id name type debug disabled priority template-level-gen-func overall-post-process-func-list terrain-post-process-func-list faction-list-func (is-available-for-mission #'(lambda (world-sector mission-type-id world-time) (declare (ignore world-sector mission-type-id world-time)) t)) random-available-for-mission scenario-enabled-func scenario-disabled-func (depends-on-lvl-mod-func #'(lambda (world-sector mission-type-id world-time) (declare (ignore world-sector mission-type-id world-time)) nil)) (always-present-func #'(lambda (world-sector mission world-time) (declare (ignore world-sector mission world-time)) nil))) (unless id (error ":ID is an obligatory parameter!")) (unless name (error ":NAME is an obligatory parameter!")) (unless type (error ":TYPE is an obligatory parameter!")) (when (>= id (length *level-modifiers*)) (adjust-array *level-modifiers* (list (1+ id)) :initial-element nil)) (setf (aref *level-modifiers* id) (make-instance 'level-modifier :id id :name name :lm-type type :lm-debug debug :disabled disabled :priority priority :template-level-gen-func template-level-gen-func :overall-post-process-func-list overall-post-process-func-list :terrain-post-process-func-list terrain-post-process-func-list :faction-list-func faction-list-func :is-available-for-mission is-available-for-mission :random-available-for-mission random-available-for-mission :scenario-enabled-func scenario-enabled-func :scenario-disabled-func scenario-disabled-func :depends-on-lvl-mod-func depends-on-lvl-mod-func :always-present-func always-present-func))) (defun get-level-modifier-by-id (level-modifier-id) (aref *level-modifiers* level-modifier-id)) (defun get-all-lvl-mods-list (&key (include-disabled nil)) (loop for lvl-mod across *level-modifiers* when (or (not include-disabled) (and include-disabled (disabled lvl-mod))) collect lvl-mod)) (defun change-level-to-snow (level world-sector mission world) (declare (ignore world-sector mission world)) (loop for x from 0 below (array-dimension (terrain level) 0) do (loop for y from 0 below (array-dimension (terrain level) 1) do (loop for z from (1- (array-dimension (terrain level) 2)) downto 0 do (cond ((= (aref (terrain level) x y z) +terrain-border-floor+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-border-grass+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-dirt+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-dirt-bright+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-grass+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-tree-birch+) (setf (aref (terrain level) x y z) +terrain-tree-birch-snow+)) ((= (aref (terrain level) x y z) +terrain-water-liquid+) (progn (setf (aref (terrain level) x y z) +terrain-wall-ice+) (when (and (< z (1- (array-dimension (terrain level) 2))) (= (aref (terrain level) x y (1+ z)) +terrain-floor-air+)) (setf (aref (terrain level) x y (1+ z)) +terrain-water-ice+)))) ((= (aref (terrain level) x y z) +terrain-floor-leaves+) (setf (aref (terrain level) x y z) +terrain-floor-leaves-snow+)))))) )
null
https://raw.githubusercontent.com/gwathlobal/CotD/d01ef486cc1d3b21d2ad670ebdb443e957290aa2/src/level-modifiers/level-modifier.lisp
lisp
--------------------------------- LEVEL-MOD-TYPE Constants --------------------------------- --------------------------------- LEVEL-MODIFIER Constants --------------------------------- the func that takes world-sector-type and returns a list of faction-ids takes world-sector-type-id, mission-type-id and world-time takes world-sector, mission-type-id and world-time takes world-sector, mission and world-time
(in-package :cotd) (defenum:defenum level-mod-type-enum (:level-mod-controlled-by :level-mod-sector-feat :level-mod-sector-item :level-mod-tod :level-mod-weather :level-mod-player-placement :level-mod-misc)) (defconstant +level-mod-controlled-by+ 0) (defconstant +level-mod-sector-feat+ 1) (defconstant +level-mod-sector-item+ 2) (defconstant +level-mod-time-of-day+ 3) (defconstant +level-mod-weather+ 4) (defconstant +level-mod-player-placement+ 5) (defconstant +level-mod-misc+ 6) (defconstant +lm-controlled-by-none+ 0) (defconstant +lm-controlled-by-demons+ 1) (defconstant +lm-controlled-by-military+ 2) (defconstant +lm-feat-river+ 3) (defconstant +lm-feat-sea+ 4) (defconstant +lm-feat-barricade+ 5) (defconstant +lm-feat-library+ 6) (defconstant +lm-feat-church+ 7) (defconstant +lm-feat-lair+ 8) (defconstant +lm-item-book-of-rituals+ 9) (defconstant +lm-item-holy-relic+ 10) (defconstant +lm-tod-morning+ 11) (defconstant +lm-tod-noon+ 12) (defconstant +lm-tod-evening+ 13) (defconstant +lm-tod-night+ 14) (defconstant +lm-weather-rain+ 15) (defconstant +lm-weather-snow+ 16) (defconstant +lm-placement-player+ 17) (defconstant +lm-placement-dead-player+ 18) (defconstant +lm-placement-angel-chrome+ 19) (defconstant +lm-placement-angel-trinity+ 20) (defconstant +lm-placement-demon-crimson+ 21) (defconstant +lm-placement-demon-shadow+ 22) (defconstant +lm-placement-demon-malseraph+ 23) (defconstant +lm-placement-military-chaplain+ 24) (defconstant +lm-placement-military-scout+ 25) (defconstant +lm-placement-priest+ 26) (defconstant +lm-placement-satanist+ 27) (defconstant +lm-placement-eater+ 28) (defconstant +lm-placement-skinchanger+ 29) (defconstant +lm-placement-thief+ 30) (defconstant +lm-placement-ghost+ 31) (defconstant +lm-placement-test+ 32) (defconstant +lm-tod-hell+ 33) (defconstant +lm-feat-hell-engine+ 34) (defconstant +lm-feat-hell-flesh-storage+ 35) (defconstant +lm-weather-acid-rain+ 36) (defconstant +lm-misc-eater-incursion+ 37) (defconstant +lm-misc-malseraphs-blessing+ 38) (defparameter *level-modifiers* (make-array (list 0) :adjustable t)) (defclass level-modifier () ((id :initarg :id :accessor id) (name :initarg :name :accessor name) (priority :initform 0 :initarg :priority :accessor priority) (lm-type :initarg :lm-type :accessor lm-type :type level-mod-type-enum) (lm-debug :initform nil :initarg :lm-debug :accessor lm-debug :type boolean) (disabled :initform nil :initarg :disabled :accessor disabled :type boolean) (template-level-gen-func :initform nil :initarg :template-level-gen-func :accessor template-level-gen-func) (overall-post-process-func-list :initform nil :initarg :overall-post-process-func-list :accessor overall-post-process-func-list) (terrain-post-process-func-list :initform nil :initarg :terrain-post-process-func-list :accessor terrain-post-process-func-list) (random-available-for-mission :initform nil :initarg :random-available-for-mission :accessor random-available-for-mission) (scenario-enabled-func :initform nil :initarg :scenario-enabled-func :accessor scenario-enabled-func) (scenario-disabled-func :initform nil :initarg :scenario-disabled-func :accessor scenario-disabled-func) )) (defun set-level-modifier (&key id name type debug disabled priority template-level-gen-func overall-post-process-func-list terrain-post-process-func-list faction-list-func (is-available-for-mission #'(lambda (world-sector mission-type-id world-time) (declare (ignore world-sector mission-type-id world-time)) t)) random-available-for-mission scenario-enabled-func scenario-disabled-func (depends-on-lvl-mod-func #'(lambda (world-sector mission-type-id world-time) (declare (ignore world-sector mission-type-id world-time)) nil)) (always-present-func #'(lambda (world-sector mission world-time) (declare (ignore world-sector mission world-time)) nil))) (unless id (error ":ID is an obligatory parameter!")) (unless name (error ":NAME is an obligatory parameter!")) (unless type (error ":TYPE is an obligatory parameter!")) (when (>= id (length *level-modifiers*)) (adjust-array *level-modifiers* (list (1+ id)) :initial-element nil)) (setf (aref *level-modifiers* id) (make-instance 'level-modifier :id id :name name :lm-type type :lm-debug debug :disabled disabled :priority priority :template-level-gen-func template-level-gen-func :overall-post-process-func-list overall-post-process-func-list :terrain-post-process-func-list terrain-post-process-func-list :faction-list-func faction-list-func :is-available-for-mission is-available-for-mission :random-available-for-mission random-available-for-mission :scenario-enabled-func scenario-enabled-func :scenario-disabled-func scenario-disabled-func :depends-on-lvl-mod-func depends-on-lvl-mod-func :always-present-func always-present-func))) (defun get-level-modifier-by-id (level-modifier-id) (aref *level-modifiers* level-modifier-id)) (defun get-all-lvl-mods-list (&key (include-disabled nil)) (loop for lvl-mod across *level-modifiers* when (or (not include-disabled) (and include-disabled (disabled lvl-mod))) collect lvl-mod)) (defun change-level-to-snow (level world-sector mission world) (declare (ignore world-sector mission world)) (loop for x from 0 below (array-dimension (terrain level) 0) do (loop for y from 0 below (array-dimension (terrain level) 1) do (loop for z from (1- (array-dimension (terrain level) 2)) downto 0 do (cond ((= (aref (terrain level) x y z) +terrain-border-floor+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-border-grass+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-dirt+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-dirt-bright+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-floor-grass+) (setf (aref (terrain level) x y z) +terrain-floor-snow+)) ((= (aref (terrain level) x y z) +terrain-tree-birch+) (setf (aref (terrain level) x y z) +terrain-tree-birch-snow+)) ((= (aref (terrain level) x y z) +terrain-water-liquid+) (progn (setf (aref (terrain level) x y z) +terrain-wall-ice+) (when (and (< z (1- (array-dimension (terrain level) 2))) (= (aref (terrain level) x y (1+ z)) +terrain-floor-air+)) (setf (aref (terrain level) x y (1+ z)) +terrain-water-ice+)))) ((= (aref (terrain level) x y z) +terrain-floor-leaves+) (setf (aref (terrain level) x y z) +terrain-floor-leaves-snow+)))))) )
6e065162d35bfce70250a9a7122073a6db0a5b321dc2277fe66d440e4de976a2
toaq/zugai
Xbar.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Xbar where -- This module convers zugai parse trees to -org.netlify.app/parser/ style *binary* (X-bar) parse trees. import Control.Monad.State import Data.Aeson.Micro (object, (.=)) import Data.Aeson.Micro qualified as J import Data.Char import Data.Foldable import Data.List.NonEmpty (NonEmpty (..)) import Data.Maybe import Data.Text (Text) import Data.Text qualified as T import Data.Text.IO qualified as T import Debug.Trace import Dictionary import Lex import Parse import Scope import Text.Parsec (SourcePos) import Text.Parsec.Pos (initialPos) import TextUtils import ToSrc import XbarLabels import XbarUtils runXbarWithMovements :: Dictionary -> Discourse -> (Xbar (), Movements) runXbarWithMovements dict d = case runState (unMx (toXbar d)) (XbarState 0 [] emptyMovements dict) of (x, s) -> (x, xbarMovements s) runXbar :: Dictionary -> Discourse -> Xbar () runXbar dict d = fst (runXbarWithMovements dict d) -- Turn n≥1 terms into a parse tree with a "term" or "terms" head. -- termsToXbar :: Foldable t => t Term -> Mx Xbar termsToXbar = foldl1 ( \ma mb - > do a < - ma ; b < - mb ; mkPair " Terms " a b ) . map toXbar . toList -- When rendering an elided VP after "sa", this "∅" VP is rendered as a fallback. nullVp :: SourcePos -> Vp nullVp sourcePos = Single (Nonserial (Vverb (W (Pos sourcePos "" "") []))) -- Pair a construct with its optional terminator. terminated :: Category -> Xbar () -> Terminator -> Mx (Xbar ()) terminated _ t Nothing = pure t terminated cat t (Just word) = do xF <- mkTag (Label (X_F cat) []) =<< toXbar word mkPair (Label (XP (X_F cat)) []) t xF covert :: Mx (Xbar ()) covert = mkLeaf (Covert " ") -- I know this is kinda silly... but it's useful that `T.strip` ignores it. blank :: Mx (Xbar ()) blank = mkLeaf (Covert "") prenexToXbar :: NonEmpty (Xbar ()) -> W () -> Xbar () -> Mx (Xbar ()) prenexToXbar (x :| []) bi c = do xBi <- toXbar bi xTopic <- mkTag _Topic xBi xTopic' <- mkPair _Topic' xTopic c mkPair _TopicP x xTopic' prenexToXbar (x :| (x' : xs)) bi c = do xBi <- mkTag _Topic =<< covert xRest <- prenexToXbar (x' :| xs) bi c xTopic' <- mkPair _Topic' xBi xRest mkPair _TopicP x xTopic' instance ToXbar Discourse where toXbar (Discourse ds) = foldl1 (\ma mb -> do a <- ma; b <- mb; mkPair _SAP a b) (toXbar <$> ds) instance ToXbar DiscourseItem where toXbar (DiSentence x) = toXbar x toXbar (DiFragment x) = toXbar x toXbar (DiFree x) = toXbar x instance ToXbar Sentence where toXbar (Sentence msc stmt ill) = do t <- do sa <- maybe covert toXbar ill x <- toXbar stmt y <- mkTag _SA sa mkPair _SAP x y case msc of Just sc -> do xSConn <- mkTag _SAP =<< toXbar sc; mkPair _SAP xSConn t Nothing -> pure t instance ToXbar Fragment where toXbar (FrPrenex (Prenex ts bi)) = do xsTopics <- mapM toXbar ts prenexToXbar xsTopics bi =<< covert toXbar (FrTopic t) = toXbar t instance ToXbar Statement where toXbar (Statement mc mp pred) = do pushScope xC <- case mc of Just c -> toXbar c Nothing -> mkTag _C =<< covert maybeXsTopicsBi <- case mp of Nothing -> pure Nothing Just (Prenex ts bi) -> do xs <- mapM toXbar ts pure (Just (xs, bi)) xFP <- toXbar pred xTopicP <- case maybeXsTopicsBi of Just (xs, bi) -> prenexToXbar xs bi xFP Nothing -> pure xFP s <- popScope xWithFoc <- foldrM mkFocAdvP xTopicP (scopeFocuses s) xWithQPs <- foldrM mkQP xWithFoc (scopeQuantifiers s) if or [d == Ja | (d, _, _) <- scopeQuantifiers s] then mkPair _CPλ xC xWithQPs else mkPair _CP xC xWithQPs focGloss :: Text -> Source focGloss "ku" = Covert "focus, -contrast" focGloss "bei" = Covert "focus, +contrast" focGloss "tou" = Covert "only" focGloss "mao" = Covert "also" focGloss "juaq" = Covert "even" focGloss _ = Covert "?" mkFocAdvP :: (Text, Int) -> Xbar () -> Mx (Xbar ()) mkFocAdvP (focuser, iDP) x = do xFocAdv <- mkTag _Foc =<< mkLeaf (focGloss $ bareToaq focuser) -- Copy the DP up here... kind of a hack xDP <- case subtreeByIndex iDP x of Just dp -> mkRoof _DP . Traced =<< aggregateSrc dp Nothing -> mkRoof _DP (Traced "???") move' iDP (index xDP) xFocAdvP <- mkPair _FocP xFocAdv xDP mkPair (label x) xFocAdvP x qgloss :: Determiner -> Text qgloss Sa = "∃" qgloss Tu = "∀" qgloss Tuq = "Λ" qgloss Ke = "℩" qgloss Ja = "λ" qgloss (XShi q) = qgloss q <> "¹" qgloss _ = "…" labelIsVP :: Label -> Bool labelIsVP = (== XP (Head HV)) . labelCategory mkQP :: (Determiner, VarRef, Int) -> Xbar () -> Mx (Xbar ()) mkQP (det, name, indexOfDPV) x = do let isVP = case subtreeByIndex indexOfDPV x of Just xDPV -> labelIsVP (label xDPV) _ -> False xQ <- mkTag _Q =<< mkLeaf (Covert $ qgloss det) xV <- if isVP then mkRoof _VP (Traced name) else do vl <- verbLabel name; mkTag vl =<< mkLeaf (Traced name) move' indexOfDPV (index xV) xQP <- mkPair _QP xQ xV mkPair (label x) xQP x verbClassName :: Maybe VerbClass -> HeadCategory verbClassName Nothing = HV verbClassName (Just Tense) = HT verbClassName (Just Aspect) = HAsp verbClassName (Just Modality) = HMod verbClassName (Just Negation) = HNeg verbLabel :: Text -> Mx Label verbLabel verbText = do d <- gets xbarDictionary let mvc = lookupVerbClass d verbText pure (Label (Head (verbClassName mvc)) []) vpcLabel :: VpC -> Mx Label vpcLabel (Nonserial (Vverb w)) = verbLabel (unW w) vpcLabel (Nonserial _) = pure $ Label (Head HV) [] vpcLabel (Serial x _) = vpcLabel (Nonserial x) make a V / VP / vP ( ) out of ( verb , NPs ) and return xVP . makeVP :: Xbar () -> [Xbar ()] -> Mx (Xbar ()) makeVP xV xsNp = do verb <- aggregateSrc xV dict <- gets xbarDictionary case xsNp of xs | Just i <- lookupMaxArity dict verb, length xs > i -> error $ show verb <> " accepts at most " <> show i <> " argument" <> ['s' | i /= 1] [] -> do pure xV [xDPS] | labelIsVP (label xV) -> do -- Our "xV" is actually a VP with an incorporated object. xv <- mkTag _v =<< blank xv' <- mkPair _v' xv xV mkPair _vP xDPS xv' [xDPS] -> do vname <- verbLabel verb let xV' = if labelCategory (label xV) == Head HV then relabel vname xV else xV mkPair (Label (XP $ labelCategory vname) []) xV' xDPS [xDPS, xDPO] -> do xV' <- mkPair _V' xV xDPO mkPair _VP xDPS xV' [xDPA, xDPS, xDPO] -> do xv <- mkTag _v =<< blank xV' <- mkPair _V' xV xDPO xVP <- mkPair _VP xDPS xV' xv' <- mkPair _v' xv xVP mkPair _vP xDPA xv' _ -> error "verb has too many arguments" newtype Pro = Pro (Maybe Int) deriving (Eq, Ord, Show) instance ToXbar Pro where toXbar (Pro i) = do xDP <- mkTag _DP =<< mkLeaf (Covert "PRO") mapM_ (coindex (index xDP)) i pure xDP instance (ToXbar a, ToXbar b) => ToXbar (Either a b) where toXbar (Left a) = toXbar a toXbar (Right b) = toXbar b selectCoindex :: Char -> [Xbar ()] -> Maybe Int selectCoindex 'i' (xi : _) = Just (index xi) selectCoindex 'i' xs = error $ "couldn't coindex with subject: " <> show (length xs) <> " args" selectCoindex 'j' (_ : xj : _) = Just (index xj) selectCoindex 'j' xs = error $ "couldn't coindex with object: " <> show (length xs) <> " args" selectCoindex 'x' _ = Nothing selectCoindex c _ = error $ "unrecognized coindex char: " <> show c -- make a VP for a serial and return (top arity, V to trace into F, VP) makeVPSerial :: VpC -> [Either Pro Np] -> Mx (Int, Xbar (), Xbar ()) makeVPSerial vp nps = do (vNow, xsNpsNow, serialTail) <- case vp of Nonserial v -> do xsNps <- mapM toXbar nps pure (v, xsNps, Nothing) Serial v vs -> do dict <- gets xbarDictionary let frame = fromMaybe "c 0" (lookupFrame dict (toSrc v)) -- let proCount = frameDigit frame let cCount = sum [1 | 'c' <- T.unpack frame] xsNpsNow <- (++) <$> mapM toXbar (take cCount nps) <*> replicateM (cCount - length nps) (mkTag _DP =<< covert) let ijxs = [c | (d : cs) <- T.unpack <$> T.words frame, isDigit d, c <- cs] let pros = [Left (Pro (selectCoindex c xsNpsNow)) | c <- ijxs] let npsLater = pros ++ drop cCount nps pure (v, xsNpsNow, Just (vs, npsLater)) xVnow <- mapSrc (Traced . T.toLower . sourceText) <$> toXbar vNow xsNpsSerial <- case serialTail of Nothing -> pure [] Just (w, nps) -> do (_, xVs, xVPs) <- makeVPSerial w nps move xVs xVnow pure [xVPs] let xsArgs = xsNpsNow ++ xsNpsSerial xVPish <- makeVP xVnow xsArgs pure (length xsArgs, xVnow, xVPish) needsVPMovement :: VpC -> Bool needsVPMovement (Nonserial (Vverb {})) = False needsVPMovement (Nonserial _) = True needsVPMovement (Serial n _) = needsVPMovement (Nonserial n) ensurePhrase :: Category -> Category ensurePhrase c@(XP _) = c ensurePhrase c = XP c instance ToXbar PredicationC where toXbar (Predication predicate advsL nps advsR) = do xsAdvL <- mapM toXbar advsL let v = case predicate of Predicate (Single s) -> s _ -> error "coordination of verbs not supported in xbar" (arity, xVTrace, xVPish) <- makeVPSerial v (map Right nps) xFV <- if needsVPMovement v then do mkRoof _Fplus (Overt $ toSrc v) else do vl <- vpcLabel v relabel _Fplus <$> toXbar v move xVTrace xFV xsAdvR <- mapM toXbar advsR let isVPLike label = case labelCategory label of XP _ -> True; _ -> False let attachAdverbials (Pair i _ t xL xR) | not (isVPLike t) = do xR' <- attachAdverbials xR pure (Pair i () t xL xR') attachAdverbials x = do let lbl = Label (ensurePhrase $ labelCategory $ label x) [] x' <- foldlM (mkPair lbl) x xsAdvR foldrM (mkPair lbl) x' xsAdvL xVPa <- attachAdverbials xVPish mkPair _FP xFV xVPa instance ToXbar Predicate where toXbar (Predicate vp) = toXbar vp instance ToXbar Adverbial where toXbar (Tadvp t) = toXbar t toXbar (Tpp t) = toXbar t instance ToXbar Topic where toXbar (Topicn t) = toXbar t toXbar (Topica t) = toXbar t A little helper typeclass to deal with " na " in the ' instance below . -- We just want to handle the types na=() (no "na") and na=(W()) (yes "na") differently in toXbar. class ToXbarNa na where toXbarNa :: Xbar () -> na -> Mx (Xbar ()) instance ToXbarNa () where toXbarNa t () = pure t instance ToXbarNa (W ()) where toXbarNa t na = do t1 <- toXbar na t2 <- mkTag _CoF t1 mkPair _CoP t t2 instance (ToXbar t, ToXbarNa na) => ToXbar (Connable' na t) where toXbar (Conn x na ru y) = do tx <- toXbar x t1 <- toXbarNa tx na tr <- toXbar ru ty <- toXbar y t2 <- mkPair _Co' tr ty mkPair _CoP t1 t2 toXbar (ConnTo to ru x to' y) = do tt <- mkTag _Co =<< toXbar to tr <- toXbar ru t1 <- mkPair _Co' tt tr tx <- toXbar x tt' <- mkTag _Co =<< toXbar to' ty <- toXbar y t3 <- mkPair _Co' tt' ty t2 <- mkPair _CoP tx t3 mkPair _CoP t1 t2 toXbar (Single x) = toXbar x instance ToXbar AdvpC where toXbar (Advp t7 verb) = do xAdv <- mkTag _Adv =<< mkLeaf (Overt $ posSrc t7) xV <- toXbar verb mkPair _AdvP xAdv xV instance ToXbar PpC where toXbar (Pp (Single (Prep t6 verb)) np) = do xP <- mkTag _P =<< mkLeaf (Overt $ posSrc t6) xV <- toXbar verb xNP <- toXbar np xVP <- mkPair _VP xV xNP mkPair _PP xP xVP toXbar (Pp _ np) = error "X-bar: coordination of prepositions is unimplemented" instance ToXbar NpC where toXbar (Focused foc np) = do xFoc <- mkTag _Foc =<< toXbar foc xDP <- toXbar np focus (toSrc foc) (index xDP) mkPair _FocP xFoc xDP toXbar (Unf np) = toXbar np instance ToXbar NpF where toXbar (ArgRel arg rel) = do xDP <- toXbar arg xCP <- toXbar rel mkPair _DP xDP xCP toXbar (Unr np) = toXbar np instance ToXbar NpR where toXbar (Npro txt) = do xDP <- mkTag _DP =<< mkLeaf (Overt $ inT2 $ unW txt) ss <- getScopes mi <- scopeLookup (toName txt) mapM_ (coindex (index xDP)) mi pure xDP toXbar (Ndp dp) = toXbar dp toXbar (Ncc cc) = toXbar cc bindVp :: Determiner -> Text -> Int -> Int -> Mx () bindVp det name iDP iVP = do quantify det name iVP bind name iDP dictionary <- gets xbarDictionary let anaphora = lookupPronoun dictionary name case anaphora of Just prn -> bind prn iDP Nothing -> pure () instance ToXbar Dp where toXbar (Dp det@(W pos _) maybeVp) = do xD <- mkTag _D =<< mkLeaf (Overt $ posSrc pos) iDP <- nextNodeNumber xVP <- case maybeVp of Nothing -> toXbar (nullVp (posPos pos)) Just vp -> toXbar vp let iVP = index xVP let name = maybe "" toName maybeVp case unW det of DT2 -> do mi <- scopeLookup name case mi of Nothing -> pure () -- bindVp Ke name iDP iVP <-- do this in semantics stage instead. Just i -> coindex iDP i det -> do bindVp det name iDP iVP pure $ Pair iDP () _DP xD xVP instance ToXbar RelC where toXbar (Rel pred tmr) = do x <- toXbar pred; terminated (Head HC) x tmr instance ToXbar Cc where toXbar (Cc pred tmr) = do x <- toXbar pred; terminated (Head HC) x tmr instance ToXbar VpC where toXbar (Serial v w) = do xV <- toXbar v xW <- toXbar w serial <- mkPair _V' xV xW mkRoof _V . Overt =<< aggregateSrc serial toXbar (Nonserial x) = toXbar x instance ToXbar VpN where toXbar (Vname nv name tmr) = do xV <- toXbar nv xDP <- toXbar name xVP <- mkPair _VP xV xDP terminated (Head HV) xVP tmr toXbar (Vshu shu text) = do xV <- mkTag _V =<< toXbar shu xDP <- mkTag _DP =<< toXbar text mkPair _VP xV xDP toXbar (Voiv oiv np tmr) = do xCopV <- mkTag _CoP =<< toXbar oiv pushScope xDP <- toXbar np s <- popScope let gloss = if unW oiv == "po" then "[hao]" else "[" <> unW oiv <> "ga]" xV <- mkTag _V =<< mkLeaf (Covert gloss) xV' <- mkPair _V' xV xDP xDPpro <- toXbar (Pro Nothing) xVP <- mkPair _VP xDPpro xV' xWithFoc <- foldrM mkFocAdvP xVP (scopeFocuses s) xWithQPs <- foldrM mkQP xWithFoc (scopeQuantifiers s) xC <- mkTag _C =<< covert xCP <- mkPair _CP xC xWithQPs xCopVP <- mkPair _CoP xCopV xCP terminated (Head HV) xCopVP tmr toXbar (Vmo mo disc teo) = do xV <- mkTag _V =<< toXbar mo xDiscourse <- toXbar disc xVP <- mkPair _VP xV xDiscourse terminated (Head HV) xVP teo toXbar (Vlu lu stmt ky) = do xV <- mkTag _V =<< toXbar lu xCP <- toXbar stmt case stmt of Statement (Just c) _ _ -> error $ "lu cannot be followed by an overt complementizer (\"lu " <> T.unpack (toSrc c) <> "\" is invalid)" _ -> pure () xVP <- mkPair _VP xV xCP terminated (Head HV) xVP ky toXbar (Vverb w) = do label <- verbLabel (unW w) mkTag label =<< toXbar w instance ToXbar Name where toXbar (VerbName x) = relabel _DP <$> toXbar x toXbar (TermName x) = relabel _DP <$> toXbar x instance ToXbar FreeMod where toXbar (Fint teto) = mkTag _Free =<< toXbar teto toXbar (Fvoc hu np) = do x <- toXbar hu; y <- toXbar np; mkPair _Free x y toXbar (Finc ju sentence) = do x <- toXbar ju; y <- toXbar sentence; mkPair _Free x y toXbar (Fpar kio disc ki) = do x <- toXbar kio; y <- toXbar disc; z <- toXbar ki; mkPair _Free x =<< mkPair _Free y z instance ToXbar () where toXbar () = mkLeaf (Covert "()") instance ToXbar ( Pos Text ) where toXbar ( Pos _ ) = Leaf src txt instance ToXbar t => ToXbar (Pos t) where toXbar (Pos _ src t) = do inner <- toXbar t case inner of Leaf _ _ -> mkLeaf (Overt src) Tag _ _ t (Leaf _ _) -> mkTag t =<< mkLeaf (Overt src) x -> pure x instance ToXbar t => ToXbar (W t) where toXbar (W w fms) = foldl (\ma mb -> do a <- ma; b <- mb; mkPair _FreeP a b) (toXbar w) (toXbar <$> fms) instance ToXbar Text where toXbar = mkLeaf . Overt instance ToXbar (Text, Tone) where toXbar (t, _) = mkLeaf (Overt t) instance ToXbar String where toXbar t = toXbar (T.pack t) instance ToXbar NameVerb where toXbar nv = mkTag _V =<< toXbar (show nv) instance ToXbar Determiner where toXbar det = mkTag _D =<< toXbar (show det) instance ToXbar Connective where toXbar t = mkTag _Co =<< toXbar (show t) instance ToXbar Complementizer where toXbar t = mkTag _C =<< toXbar (show t) -- Convert an Xbar () tree to JSON. xbarToJson :: Maybe (Text -> Text) -> Xbar d -> J.Value xbarToJson annotate xbar = case xbar of Leaf {source = src} -> object [ "type" .= J.String "leaf", "src" .= srcToJson src, "gloss" .= case annotate of Just f -> srcToJson (mapSource f src); _ -> J.Null ] Roof {label = t, source = src} -> object [ "type" .= J.String "roof", "tag" .= labelToJson t, "src" .= srcToJson src ] Tag {label = t, child = sub} -> object [ "type" .= J.String "node", "tag" .= labelToJson t, "children" .= J.Array [xbarToJson annotate sub] ] Pair {label = t, leftChild = x, rightChild = y} -> object [ "type" .= J.String "node", "tag" .= labelToJson t, "children" .= J.Array (xbarToJson annotate <$> [x, y]) ] where srcToJson (Overt t) = J.String t srcToJson (Covert t) = J.String t srcToJson (Traced t) = J.String t bleh
null
https://raw.githubusercontent.com/toaq/zugai/2168cfb865a243dbf5516db30d3fc3ef5840c8b8/src/Xbar.hs
haskell
This module convers zugai parse trees to -org.netlify.app/parser/ style *binary* (X-bar) parse trees. Turn n≥1 terms into a parse tree with a "term" or "terms" head. termsToXbar :: Foldable t => t Term -> Mx Xbar When rendering an elided VP after "sa", this "∅" VP is rendered as a fallback. Pair a construct with its optional terminator. I know this is kinda silly... but it's useful that `T.strip` ignores it. Copy the DP up here... kind of a hack Our "xV" is actually a VP with an incorporated object. make a VP for a serial and return (top arity, V to trace into F, VP) let proCount = frameDigit frame We just want to handle the types na=() (no "na") and na=(W()) (yes "na") differently in toXbar. bindVp Ke name iDP iVP <-- do this in semantics stage instead. Convert an Xbar () tree to JSON.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Xbar where import Control.Monad.State import Data.Aeson.Micro (object, (.=)) import Data.Aeson.Micro qualified as J import Data.Char import Data.Foldable import Data.List.NonEmpty (NonEmpty (..)) import Data.Maybe import Data.Text (Text) import Data.Text qualified as T import Data.Text.IO qualified as T import Debug.Trace import Dictionary import Lex import Parse import Scope import Text.Parsec (SourcePos) import Text.Parsec.Pos (initialPos) import TextUtils import ToSrc import XbarLabels import XbarUtils runXbarWithMovements :: Dictionary -> Discourse -> (Xbar (), Movements) runXbarWithMovements dict d = case runState (unMx (toXbar d)) (XbarState 0 [] emptyMovements dict) of (x, s) -> (x, xbarMovements s) runXbar :: Dictionary -> Discourse -> Xbar () runXbar dict d = fst (runXbarWithMovements dict d) termsToXbar = foldl1 ( \ma mb - > do a < - ma ; b < - mb ; mkPair " Terms " a b ) . map toXbar . toList nullVp :: SourcePos -> Vp nullVp sourcePos = Single (Nonserial (Vverb (W (Pos sourcePos "" "") []))) terminated :: Category -> Xbar () -> Terminator -> Mx (Xbar ()) terminated _ t Nothing = pure t terminated cat t (Just word) = do xF <- mkTag (Label (X_F cat) []) =<< toXbar word mkPair (Label (XP (X_F cat)) []) t xF covert :: Mx (Xbar ()) blank :: Mx (Xbar ()) blank = mkLeaf (Covert "") prenexToXbar :: NonEmpty (Xbar ()) -> W () -> Xbar () -> Mx (Xbar ()) prenexToXbar (x :| []) bi c = do xBi <- toXbar bi xTopic <- mkTag _Topic xBi xTopic' <- mkPair _Topic' xTopic c mkPair _TopicP x xTopic' prenexToXbar (x :| (x' : xs)) bi c = do xBi <- mkTag _Topic =<< covert xRest <- prenexToXbar (x' :| xs) bi c xTopic' <- mkPair _Topic' xBi xRest mkPair _TopicP x xTopic' instance ToXbar Discourse where toXbar (Discourse ds) = foldl1 (\ma mb -> do a <- ma; b <- mb; mkPair _SAP a b) (toXbar <$> ds) instance ToXbar DiscourseItem where toXbar (DiSentence x) = toXbar x toXbar (DiFragment x) = toXbar x toXbar (DiFree x) = toXbar x instance ToXbar Sentence where toXbar (Sentence msc stmt ill) = do t <- do sa <- maybe covert toXbar ill x <- toXbar stmt y <- mkTag _SA sa mkPair _SAP x y case msc of Just sc -> do xSConn <- mkTag _SAP =<< toXbar sc; mkPair _SAP xSConn t Nothing -> pure t instance ToXbar Fragment where toXbar (FrPrenex (Prenex ts bi)) = do xsTopics <- mapM toXbar ts prenexToXbar xsTopics bi =<< covert toXbar (FrTopic t) = toXbar t instance ToXbar Statement where toXbar (Statement mc mp pred) = do pushScope xC <- case mc of Just c -> toXbar c Nothing -> mkTag _C =<< covert maybeXsTopicsBi <- case mp of Nothing -> pure Nothing Just (Prenex ts bi) -> do xs <- mapM toXbar ts pure (Just (xs, bi)) xFP <- toXbar pred xTopicP <- case maybeXsTopicsBi of Just (xs, bi) -> prenexToXbar xs bi xFP Nothing -> pure xFP s <- popScope xWithFoc <- foldrM mkFocAdvP xTopicP (scopeFocuses s) xWithQPs <- foldrM mkQP xWithFoc (scopeQuantifiers s) if or [d == Ja | (d, _, _) <- scopeQuantifiers s] then mkPair _CPλ xC xWithQPs else mkPair _CP xC xWithQPs focGloss :: Text -> Source focGloss "ku" = Covert "focus, -contrast" focGloss "bei" = Covert "focus, +contrast" focGloss "tou" = Covert "only" focGloss "mao" = Covert "also" focGloss "juaq" = Covert "even" focGloss _ = Covert "?" mkFocAdvP :: (Text, Int) -> Xbar () -> Mx (Xbar ()) mkFocAdvP (focuser, iDP) x = do xFocAdv <- mkTag _Foc =<< mkLeaf (focGloss $ bareToaq focuser) xDP <- case subtreeByIndex iDP x of Just dp -> mkRoof _DP . Traced =<< aggregateSrc dp Nothing -> mkRoof _DP (Traced "???") move' iDP (index xDP) xFocAdvP <- mkPair _FocP xFocAdv xDP mkPair (label x) xFocAdvP x qgloss :: Determiner -> Text qgloss Sa = "∃" qgloss Tu = "∀" qgloss Tuq = "Λ" qgloss Ke = "℩" qgloss Ja = "λ" qgloss (XShi q) = qgloss q <> "¹" qgloss _ = "…" labelIsVP :: Label -> Bool labelIsVP = (== XP (Head HV)) . labelCategory mkQP :: (Determiner, VarRef, Int) -> Xbar () -> Mx (Xbar ()) mkQP (det, name, indexOfDPV) x = do let isVP = case subtreeByIndex indexOfDPV x of Just xDPV -> labelIsVP (label xDPV) _ -> False xQ <- mkTag _Q =<< mkLeaf (Covert $ qgloss det) xV <- if isVP then mkRoof _VP (Traced name) else do vl <- verbLabel name; mkTag vl =<< mkLeaf (Traced name) move' indexOfDPV (index xV) xQP <- mkPair _QP xQ xV mkPair (label x) xQP x verbClassName :: Maybe VerbClass -> HeadCategory verbClassName Nothing = HV verbClassName (Just Tense) = HT verbClassName (Just Aspect) = HAsp verbClassName (Just Modality) = HMod verbClassName (Just Negation) = HNeg verbLabel :: Text -> Mx Label verbLabel verbText = do d <- gets xbarDictionary let mvc = lookupVerbClass d verbText pure (Label (Head (verbClassName mvc)) []) vpcLabel :: VpC -> Mx Label vpcLabel (Nonserial (Vverb w)) = verbLabel (unW w) vpcLabel (Nonserial _) = pure $ Label (Head HV) [] vpcLabel (Serial x _) = vpcLabel (Nonserial x) make a V / VP / vP ( ) out of ( verb , NPs ) and return xVP . makeVP :: Xbar () -> [Xbar ()] -> Mx (Xbar ()) makeVP xV xsNp = do verb <- aggregateSrc xV dict <- gets xbarDictionary case xsNp of xs | Just i <- lookupMaxArity dict verb, length xs > i -> error $ show verb <> " accepts at most " <> show i <> " argument" <> ['s' | i /= 1] [] -> do pure xV [xDPS] | labelIsVP (label xV) -> do xv <- mkTag _v =<< blank xv' <- mkPair _v' xv xV mkPair _vP xDPS xv' [xDPS] -> do vname <- verbLabel verb let xV' = if labelCategory (label xV) == Head HV then relabel vname xV else xV mkPair (Label (XP $ labelCategory vname) []) xV' xDPS [xDPS, xDPO] -> do xV' <- mkPair _V' xV xDPO mkPair _VP xDPS xV' [xDPA, xDPS, xDPO] -> do xv <- mkTag _v =<< blank xV' <- mkPair _V' xV xDPO xVP <- mkPair _VP xDPS xV' xv' <- mkPair _v' xv xVP mkPair _vP xDPA xv' _ -> error "verb has too many arguments" newtype Pro = Pro (Maybe Int) deriving (Eq, Ord, Show) instance ToXbar Pro where toXbar (Pro i) = do xDP <- mkTag _DP =<< mkLeaf (Covert "PRO") mapM_ (coindex (index xDP)) i pure xDP instance (ToXbar a, ToXbar b) => ToXbar (Either a b) where toXbar (Left a) = toXbar a toXbar (Right b) = toXbar b selectCoindex :: Char -> [Xbar ()] -> Maybe Int selectCoindex 'i' (xi : _) = Just (index xi) selectCoindex 'i' xs = error $ "couldn't coindex with subject: " <> show (length xs) <> " args" selectCoindex 'j' (_ : xj : _) = Just (index xj) selectCoindex 'j' xs = error $ "couldn't coindex with object: " <> show (length xs) <> " args" selectCoindex 'x' _ = Nothing selectCoindex c _ = error $ "unrecognized coindex char: " <> show c makeVPSerial :: VpC -> [Either Pro Np] -> Mx (Int, Xbar (), Xbar ()) makeVPSerial vp nps = do (vNow, xsNpsNow, serialTail) <- case vp of Nonserial v -> do xsNps <- mapM toXbar nps pure (v, xsNps, Nothing) Serial v vs -> do dict <- gets xbarDictionary let frame = fromMaybe "c 0" (lookupFrame dict (toSrc v)) let cCount = sum [1 | 'c' <- T.unpack frame] xsNpsNow <- (++) <$> mapM toXbar (take cCount nps) <*> replicateM (cCount - length nps) (mkTag _DP =<< covert) let ijxs = [c | (d : cs) <- T.unpack <$> T.words frame, isDigit d, c <- cs] let pros = [Left (Pro (selectCoindex c xsNpsNow)) | c <- ijxs] let npsLater = pros ++ drop cCount nps pure (v, xsNpsNow, Just (vs, npsLater)) xVnow <- mapSrc (Traced . T.toLower . sourceText) <$> toXbar vNow xsNpsSerial <- case serialTail of Nothing -> pure [] Just (w, nps) -> do (_, xVs, xVPs) <- makeVPSerial w nps move xVs xVnow pure [xVPs] let xsArgs = xsNpsNow ++ xsNpsSerial xVPish <- makeVP xVnow xsArgs pure (length xsArgs, xVnow, xVPish) needsVPMovement :: VpC -> Bool needsVPMovement (Nonserial (Vverb {})) = False needsVPMovement (Nonserial _) = True needsVPMovement (Serial n _) = needsVPMovement (Nonserial n) ensurePhrase :: Category -> Category ensurePhrase c@(XP _) = c ensurePhrase c = XP c instance ToXbar PredicationC where toXbar (Predication predicate advsL nps advsR) = do xsAdvL <- mapM toXbar advsL let v = case predicate of Predicate (Single s) -> s _ -> error "coordination of verbs not supported in xbar" (arity, xVTrace, xVPish) <- makeVPSerial v (map Right nps) xFV <- if needsVPMovement v then do mkRoof _Fplus (Overt $ toSrc v) else do vl <- vpcLabel v relabel _Fplus <$> toXbar v move xVTrace xFV xsAdvR <- mapM toXbar advsR let isVPLike label = case labelCategory label of XP _ -> True; _ -> False let attachAdverbials (Pair i _ t xL xR) | not (isVPLike t) = do xR' <- attachAdverbials xR pure (Pair i () t xL xR') attachAdverbials x = do let lbl = Label (ensurePhrase $ labelCategory $ label x) [] x' <- foldlM (mkPair lbl) x xsAdvR foldrM (mkPair lbl) x' xsAdvL xVPa <- attachAdverbials xVPish mkPair _FP xFV xVPa instance ToXbar Predicate where toXbar (Predicate vp) = toXbar vp instance ToXbar Adverbial where toXbar (Tadvp t) = toXbar t toXbar (Tpp t) = toXbar t instance ToXbar Topic where toXbar (Topicn t) = toXbar t toXbar (Topica t) = toXbar t A little helper typeclass to deal with " na " in the ' instance below . class ToXbarNa na where toXbarNa :: Xbar () -> na -> Mx (Xbar ()) instance ToXbarNa () where toXbarNa t () = pure t instance ToXbarNa (W ()) where toXbarNa t na = do t1 <- toXbar na t2 <- mkTag _CoF t1 mkPair _CoP t t2 instance (ToXbar t, ToXbarNa na) => ToXbar (Connable' na t) where toXbar (Conn x na ru y) = do tx <- toXbar x t1 <- toXbarNa tx na tr <- toXbar ru ty <- toXbar y t2 <- mkPair _Co' tr ty mkPair _CoP t1 t2 toXbar (ConnTo to ru x to' y) = do tt <- mkTag _Co =<< toXbar to tr <- toXbar ru t1 <- mkPair _Co' tt tr tx <- toXbar x tt' <- mkTag _Co =<< toXbar to' ty <- toXbar y t3 <- mkPair _Co' tt' ty t2 <- mkPair _CoP tx t3 mkPair _CoP t1 t2 toXbar (Single x) = toXbar x instance ToXbar AdvpC where toXbar (Advp t7 verb) = do xAdv <- mkTag _Adv =<< mkLeaf (Overt $ posSrc t7) xV <- toXbar verb mkPair _AdvP xAdv xV instance ToXbar PpC where toXbar (Pp (Single (Prep t6 verb)) np) = do xP <- mkTag _P =<< mkLeaf (Overt $ posSrc t6) xV <- toXbar verb xNP <- toXbar np xVP <- mkPair _VP xV xNP mkPair _PP xP xVP toXbar (Pp _ np) = error "X-bar: coordination of prepositions is unimplemented" instance ToXbar NpC where toXbar (Focused foc np) = do xFoc <- mkTag _Foc =<< toXbar foc xDP <- toXbar np focus (toSrc foc) (index xDP) mkPair _FocP xFoc xDP toXbar (Unf np) = toXbar np instance ToXbar NpF where toXbar (ArgRel arg rel) = do xDP <- toXbar arg xCP <- toXbar rel mkPair _DP xDP xCP toXbar (Unr np) = toXbar np instance ToXbar NpR where toXbar (Npro txt) = do xDP <- mkTag _DP =<< mkLeaf (Overt $ inT2 $ unW txt) ss <- getScopes mi <- scopeLookup (toName txt) mapM_ (coindex (index xDP)) mi pure xDP toXbar (Ndp dp) = toXbar dp toXbar (Ncc cc) = toXbar cc bindVp :: Determiner -> Text -> Int -> Int -> Mx () bindVp det name iDP iVP = do quantify det name iVP bind name iDP dictionary <- gets xbarDictionary let anaphora = lookupPronoun dictionary name case anaphora of Just prn -> bind prn iDP Nothing -> pure () instance ToXbar Dp where toXbar (Dp det@(W pos _) maybeVp) = do xD <- mkTag _D =<< mkLeaf (Overt $ posSrc pos) iDP <- nextNodeNumber xVP <- case maybeVp of Nothing -> toXbar (nullVp (posPos pos)) Just vp -> toXbar vp let iVP = index xVP let name = maybe "" toName maybeVp case unW det of DT2 -> do mi <- scopeLookup name case mi of Just i -> coindex iDP i det -> do bindVp det name iDP iVP pure $ Pair iDP () _DP xD xVP instance ToXbar RelC where toXbar (Rel pred tmr) = do x <- toXbar pred; terminated (Head HC) x tmr instance ToXbar Cc where toXbar (Cc pred tmr) = do x <- toXbar pred; terminated (Head HC) x tmr instance ToXbar VpC where toXbar (Serial v w) = do xV <- toXbar v xW <- toXbar w serial <- mkPair _V' xV xW mkRoof _V . Overt =<< aggregateSrc serial toXbar (Nonserial x) = toXbar x instance ToXbar VpN where toXbar (Vname nv name tmr) = do xV <- toXbar nv xDP <- toXbar name xVP <- mkPair _VP xV xDP terminated (Head HV) xVP tmr toXbar (Vshu shu text) = do xV <- mkTag _V =<< toXbar shu xDP <- mkTag _DP =<< toXbar text mkPair _VP xV xDP toXbar (Voiv oiv np tmr) = do xCopV <- mkTag _CoP =<< toXbar oiv pushScope xDP <- toXbar np s <- popScope let gloss = if unW oiv == "po" then "[hao]" else "[" <> unW oiv <> "ga]" xV <- mkTag _V =<< mkLeaf (Covert gloss) xV' <- mkPair _V' xV xDP xDPpro <- toXbar (Pro Nothing) xVP <- mkPair _VP xDPpro xV' xWithFoc <- foldrM mkFocAdvP xVP (scopeFocuses s) xWithQPs <- foldrM mkQP xWithFoc (scopeQuantifiers s) xC <- mkTag _C =<< covert xCP <- mkPair _CP xC xWithQPs xCopVP <- mkPair _CoP xCopV xCP terminated (Head HV) xCopVP tmr toXbar (Vmo mo disc teo) = do xV <- mkTag _V =<< toXbar mo xDiscourse <- toXbar disc xVP <- mkPair _VP xV xDiscourse terminated (Head HV) xVP teo toXbar (Vlu lu stmt ky) = do xV <- mkTag _V =<< toXbar lu xCP <- toXbar stmt case stmt of Statement (Just c) _ _ -> error $ "lu cannot be followed by an overt complementizer (\"lu " <> T.unpack (toSrc c) <> "\" is invalid)" _ -> pure () xVP <- mkPair _VP xV xCP terminated (Head HV) xVP ky toXbar (Vverb w) = do label <- verbLabel (unW w) mkTag label =<< toXbar w instance ToXbar Name where toXbar (VerbName x) = relabel _DP <$> toXbar x toXbar (TermName x) = relabel _DP <$> toXbar x instance ToXbar FreeMod where toXbar (Fint teto) = mkTag _Free =<< toXbar teto toXbar (Fvoc hu np) = do x <- toXbar hu; y <- toXbar np; mkPair _Free x y toXbar (Finc ju sentence) = do x <- toXbar ju; y <- toXbar sentence; mkPair _Free x y toXbar (Fpar kio disc ki) = do x <- toXbar kio; y <- toXbar disc; z <- toXbar ki; mkPair _Free x =<< mkPair _Free y z instance ToXbar () where toXbar () = mkLeaf (Covert "()") instance ToXbar ( Pos Text ) where toXbar ( Pos _ ) = Leaf src txt instance ToXbar t => ToXbar (Pos t) where toXbar (Pos _ src t) = do inner <- toXbar t case inner of Leaf _ _ -> mkLeaf (Overt src) Tag _ _ t (Leaf _ _) -> mkTag t =<< mkLeaf (Overt src) x -> pure x instance ToXbar t => ToXbar (W t) where toXbar (W w fms) = foldl (\ma mb -> do a <- ma; b <- mb; mkPair _FreeP a b) (toXbar w) (toXbar <$> fms) instance ToXbar Text where toXbar = mkLeaf . Overt instance ToXbar (Text, Tone) where toXbar (t, _) = mkLeaf (Overt t) instance ToXbar String where toXbar t = toXbar (T.pack t) instance ToXbar NameVerb where toXbar nv = mkTag _V =<< toXbar (show nv) instance ToXbar Determiner where toXbar det = mkTag _D =<< toXbar (show det) instance ToXbar Connective where toXbar t = mkTag _Co =<< toXbar (show t) instance ToXbar Complementizer where toXbar t = mkTag _C =<< toXbar (show t) xbarToJson :: Maybe (Text -> Text) -> Xbar d -> J.Value xbarToJson annotate xbar = case xbar of Leaf {source = src} -> object [ "type" .= J.String "leaf", "src" .= srcToJson src, "gloss" .= case annotate of Just f -> srcToJson (mapSource f src); _ -> J.Null ] Roof {label = t, source = src} -> object [ "type" .= J.String "roof", "tag" .= labelToJson t, "src" .= srcToJson src ] Tag {label = t, child = sub} -> object [ "type" .= J.String "node", "tag" .= labelToJson t, "children" .= J.Array [xbarToJson annotate sub] ] Pair {label = t, leftChild = x, rightChild = y} -> object [ "type" .= J.String "node", "tag" .= labelToJson t, "children" .= J.Array (xbarToJson annotate <$> [x, y]) ] where srcToJson (Overt t) = J.String t srcToJson (Covert t) = J.String t srcToJson (Traced t) = J.String t bleh
fe68eda7dfd15eea6bd80d1ee64bdb4bcc52a7d063e3dca35fafa63dd2bdf215
dbtoaster/dbtoaster-a5
Plan.ml
* A plan is the third representation in the compiler pipeline ( SQL - > Calc - > Plan ) Each plan consists of a set of compiled datastructures , which consist of { ul { - A datastructure description , including a name and a definition of the the query which the datastructure is responsible for maintaining } { - A set of triggers which are used to maintain the datastructure . } } @author A plan is the third representation in the compiler pipeline (SQL -> Calc -> Plan) Each plan consists of a set of compiled datastructures, which consist of {ul {- A datastructure description, including a name and a definition of the the query which the datastructure is responsible for maintaining} {- A set of triggers which are used to maintain the datastructure.} } @author Oliver Kennedy *) open Calculus * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (** A datastructure description *) type ds_t = { ds_name : expr_t; (** The name of the datastructure. The content of this expr_t must always be a single external leaf and can always be simply (assuming its schema matches) dropped into an existing expression in order to access this datastructure. {b mk_ds_name} and {b expand_ds_name} are utility methods for interacting with ds_names *) ds_definition : expr_t; (** The definition of the datastructure. This is the query that the map will be maintaining the result of *) } (** Construct a ds_name for a ds_t *) let mk_ds_name ?(ivc = None) (name:string) (schema:schema_t) (t:Type.type_t)= Calculus.mk_external name (fst schema) (snd schema) t ivc * Extract the name , schema , type , and code from a ds_name let expand_ds_name (name:expr_t) = begin match name with | CalcRing.Val(External(e)) -> e | _ -> failwith "Error: invalid datastructure name" end (** Stringify a datastructure description. The string conforms to the grammar of Calculusparser *) let string_of_ds (ds:ds_t): string = (string_of_expr ds.ds_name)^" := "^(string_of_expr ds.ds_definition) (******************* Statements *******************) (** A statement can either update (increment) the existing value of the key that it is writing to, or replace the value of the key that it is writing to entirely *) type stmt_type_t = UpdateStmt | ReplaceStmt (** A statement which alters the contents of a datastructure when executed *) type 'expr stmt_base_t = { target_map : 'expr; (** The datastructure to be modified *) update_type : stmt_type_t; (** The type of alteration to be performed *) update_expr : 'expr (** The calculus expression defining the new value or update *) } type stmt_t = expr_t stmt_base_t (** Stringify a statement. This string conforms to the grammar of Calculusparser *) let string_of_statement (stmt:stmt_t): string = let expr_string = (CalculusPrinter.string_of_expr (stmt.update_expr)) in (CalculusPrinter.string_of_expr (stmt.target_map))^ (if stmt.update_type = UpdateStmt then " += " else " := ")^ (if String.contains expr_string '\n' then "\n " else "")^ expr_string * * * * * * * * * * * * * * * * * * Compiled * * * * * * * * * * * * * * * * * * (** A compiled datastructure *) type compiled_ds_t = { description : ds_t; triggers : (Schema.event_t * stmt_t) list } * An incremental view maintenance plan ( produced by Compiler ) type plan_t = compiled_ds_t list let string_of_compiled_ds (ds: compiled_ds_t): string = "DECLARE "^(string_of_ds ds.description)^"\n"^(String.concat "\n" (List.map (fun x -> " "^x) ( (List.map (fun (evt, stmt) -> (Schema.string_of_event evt)^" DO "^(string_of_statement stmt)) ds.triggers) ))) let string_of_plan (plan:plan_t): string = ListExtras.string_of_list ~sep:"\n\n" string_of_compiled_ds plan
null
https://raw.githubusercontent.com/dbtoaster/dbtoaster-a5/6436110ad283378085a935ecca69080b7127467b/src/compiler/Plan.ml
ocaml
* A datastructure description * The name of the datastructure. The content of this expr_t must always be a single external leaf and can always be simply (assuming its schema matches) dropped into an existing expression in order to access this datastructure. {b mk_ds_name} and {b expand_ds_name} are utility methods for interacting with ds_names * The definition of the datastructure. This is the query that the map will be maintaining the result of * Construct a ds_name for a ds_t * Stringify a datastructure description. The string conforms to the grammar of Calculusparser ****************** Statements ****************** * A statement can either update (increment) the existing value of the key that it is writing to, or replace the value of the key that it is writing to entirely * A statement which alters the contents of a datastructure when executed * The datastructure to be modified * The type of alteration to be performed * The calculus expression defining the new value or update * Stringify a statement. This string conforms to the grammar of Calculusparser * A compiled datastructure
* A plan is the third representation in the compiler pipeline ( SQL - > Calc - > Plan ) Each plan consists of a set of compiled datastructures , which consist of { ul { - A datastructure description , including a name and a definition of the the query which the datastructure is responsible for maintaining } { - A set of triggers which are used to maintain the datastructure . } } @author A plan is the third representation in the compiler pipeline (SQL -> Calc -> Plan) Each plan consists of a set of compiled datastructures, which consist of {ul {- A datastructure description, including a name and a definition of the the query which the datastructure is responsible for maintaining} {- A set of triggers which are used to maintain the datastructure.} } @author Oliver Kennedy *) open Calculus * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * type ds_t = { } let mk_ds_name ?(ivc = None) (name:string) (schema:schema_t) (t:Type.type_t)= Calculus.mk_external name (fst schema) (snd schema) t ivc * Extract the name , schema , type , and code from a ds_name let expand_ds_name (name:expr_t) = begin match name with | CalcRing.Val(External(e)) -> e | _ -> failwith "Error: invalid datastructure name" end let string_of_ds (ds:ds_t): string = (string_of_expr ds.ds_name)^" := "^(string_of_expr ds.ds_definition) type stmt_type_t = UpdateStmt | ReplaceStmt type 'expr stmt_base_t = { } type stmt_t = expr_t stmt_base_t let string_of_statement (stmt:stmt_t): string = let expr_string = (CalculusPrinter.string_of_expr (stmt.update_expr)) in (CalculusPrinter.string_of_expr (stmt.target_map))^ (if stmt.update_type = UpdateStmt then " += " else " := ")^ (if String.contains expr_string '\n' then "\n " else "")^ expr_string * * * * * * * * * * * * * * * * * * Compiled * * * * * * * * * * * * * * * * * * type compiled_ds_t = { description : ds_t; triggers : (Schema.event_t * stmt_t) list } * An incremental view maintenance plan ( produced by Compiler ) type plan_t = compiled_ds_t list let string_of_compiled_ds (ds: compiled_ds_t): string = "DECLARE "^(string_of_ds ds.description)^"\n"^(String.concat "\n" (List.map (fun x -> " "^x) ( (List.map (fun (evt, stmt) -> (Schema.string_of_event evt)^" DO "^(string_of_statement stmt)) ds.triggers) ))) let string_of_plan (plan:plan_t): string = ListExtras.string_of_list ~sep:"\n\n" string_of_compiled_ds plan
81276b7fd72b143db8a305c976268294983b72e91e3385eb1df22fa881af1f6e
vii/dysfunkycom
color.lisp
;; lispbuilder-sdl ( C)2006 < > (in-package #:lispbuilder-sdl) (defclass color () ((color-vector :accessor fp :initform (vector 0 0 0) :initarg :color)) (:documentation "A color containing `INTEGER` Red, Green and Blue components. Free using [FREE](#free).")) (defclass color-a (color) ((color-vector :accessor fp :initform (vector 0 0 0 0) :initarg :color)) (:documentation "An color containing `INTEGER` Red, Green, Blue and Alpha components. Free using [FREE](#free).")) (defun color (&key (r 0) (g 0) (b 0) (a nil)) "Returns a new `RGB` [COLOR](#color) from the specified `R`ed, `G`reen, and `B`lue components. Returns a new `RGBA` [COLOR-A](#color-a) from the specified `R`ed, `G`reen, `B`lue, and `A`lpha components." (if a (make-instance 'color-a :color (vector (cast-to-int r) (cast-to-int g) (cast-to-int b) (cast-to-int a))) (make-instance 'color :color (vector (cast-to-int r) (cast-to-int g) (cast-to-int b))))) (defmacro with-color ((var &optional color (free t)) &body body) "A convience macro that binds `\*DEFAULT-COLOR\*` to `VAR` within the scope of `WITH-COLOR`. `VAR` is set to `COLOR` when `COLOR` is not `NIL`.`VAR` must be of type [COLOR](#color), or [COLOR-A](#color-a). `VAR` is freed using [FREE](#free) when `FREE` is `T`." `(let* ((,@(if color `(,var ,color) `(,var ,var))) (*default-color* ,var)) (symbol-macrolet ((,(intern (string-upcase (format nil "~A.r" var))) (r ,var)) (,(intern (string-upcase (format nil "~A.g" var))) (g ,var)) (,(intern (string-upcase (format nil "~A.b" var))) (b ,var)) (,(intern (string-upcase (format nil "~A.a" var))) (a ,var))) (declare (ignorable ,(intern (string-upcase (format nil "~A.r" var))) ,(intern (string-upcase (format nil "~A.g" var))) ,(intern (string-upcase (format nil "~A.b" var))) ,(intern (string-upcase (format nil "~A.a" var))))) ,@body (if ,free (free ,var))))) (defmethod free ((color color)) nil) (defmethod r ((color color)) (svref (fp color) 0)) (defmethod (setf r) (r-val (color color)) (setf (svref (fp color) 0) (cast-to-int r-val))) (defmethod g ((color color)) (svref (fp color) 1)) (defmethod (setf g) (g-val (color color)) (setf (svref (fp color) 1) (cast-to-int g-val))) (defmethod b ((color color)) (svref (fp color) 2)) (defmethod (setf b) (b-val (color color)) (setf (svref (fp color) 2) (cast-to-int b-val))) (defmethod a ((color color)) nil) (defmethod a ((color color-a)) (svref (fp color) 3)) (defmethod (setf a) (a-val (color color-a)) (setf (svref (fp color) 3) (cast-to-int a-val))) (defmethod set-color ((dst color) (src color)) (set-color-* dst :r (r src) :g (g src) :b (b src) :a (a src)) dst) (defmethod set-color-* ((color color) &key r g b a) (when r (setf (r color) r)) (when g (setf (g color) g)) (when b (setf (b color) b)) (when a (setf (a color) a)) color) (defmethod color-* ((color color)) (values (r color) (g color) (b color))) (defmethod color-* ((color color-a)) (values (r color) (g color) (b color) (a color))) (defmethod map-color-* ((r integer) (g integer) (b integer) a &optional (surface *default-surface*)) (if a (sdl-cffi::sdl-map-rgba (sdl-base::pixel-format (fp surface)) r g b a) (sdl-cffi::sdl-map-rgb (sdl-base::pixel-format (fp surface)) r g b))) (defmethod map-color ((color color) &optional (surface *default-surface*)) (map-color-* (r color) (g color) (b color) nil surface)) (defmethod map-color ((color color-a) &optional (surface *default-surface*)) (map-color-* (r color) (g color) (b color) (a color) surface)) (defmethod pack-color-* ((r integer) (g integer) (b integer) &optional (a nil)) (let ((col #x00000000)) (setf col (logior (ash r 24) (ash g 16) (ash b 8) (if a a #xFF))) col)) (defmethod pack-color ((color color)) (pack-color-* (r color) (g color) (b color))) (defmethod pack-color ((color color-a)) (pack-color-* (r color) (g color) (b color) (a color))) (defmacro with-foreign-color-copy ((struct color) &body body) "Creates and assigns a new foreign `SDL_Color` to `STRUCT`. Then copies the color components from `COLOR` into `STRUCT`. `STRUCT` is free'd when out of scope." `(cffi:with-foreign-object (,struct 'sdl-cffi::SDL-Color) (cffi:with-foreign-slots ((sdl-cffi::r sdl-cffi::g sdl-cffi::b) ,struct sdl-cffi::SDL-Color) (setf sdl-cffi::r (r ,color) sdl-cffi::g (g ,color) sdl-cffi::b (b ,color))) ,@body)) (defmethod color= (color1 color2) (declare (ignore color1 color2)) nil) (defmethod color= ((color1 color) (color2 color)) (and (eq (r color1) (r color2)) (eq (g color1) (g color2)) (eq (b color1) (b color2)))) (defmethod color= ((color1 color-a) (color2 color-a)) (and (eq (r color1) (r color2)) (eq (g color1) (g color2)) (eq (b color1) (b color2)) (eq (a color1) (a color2)))) (defmethod any-color-but-this (color) (color :r (if (> (r color) 254) 0 255)))
null
https://raw.githubusercontent.com/vii/dysfunkycom/a493fa72662b79e7c4e70361ad0ea3c7235b6166/addons/lispbuilder-sdl/sdl/color.lisp
lisp
lispbuilder-sdl
( C)2006 < > (in-package #:lispbuilder-sdl) (defclass color () ((color-vector :accessor fp :initform (vector 0 0 0) :initarg :color)) (:documentation "A color containing `INTEGER` Red, Green and Blue components. Free using [FREE](#free).")) (defclass color-a (color) ((color-vector :accessor fp :initform (vector 0 0 0 0) :initarg :color)) (:documentation "An color containing `INTEGER` Red, Green, Blue and Alpha components. Free using [FREE](#free).")) (defun color (&key (r 0) (g 0) (b 0) (a nil)) "Returns a new `RGB` [COLOR](#color) from the specified `R`ed, `G`reen, and `B`lue components. Returns a new `RGBA` [COLOR-A](#color-a) from the specified `R`ed, `G`reen, `B`lue, and `A`lpha components." (if a (make-instance 'color-a :color (vector (cast-to-int r) (cast-to-int g) (cast-to-int b) (cast-to-int a))) (make-instance 'color :color (vector (cast-to-int r) (cast-to-int g) (cast-to-int b))))) (defmacro with-color ((var &optional color (free t)) &body body) "A convience macro that binds `\*DEFAULT-COLOR\*` to `VAR` within the scope of `WITH-COLOR`. `VAR` is set to `COLOR` when `COLOR` is not `NIL`.`VAR` must be of type [COLOR](#color), or [COLOR-A](#color-a). `VAR` is freed using [FREE](#free) when `FREE` is `T`." `(let* ((,@(if color `(,var ,color) `(,var ,var))) (*default-color* ,var)) (symbol-macrolet ((,(intern (string-upcase (format nil "~A.r" var))) (r ,var)) (,(intern (string-upcase (format nil "~A.g" var))) (g ,var)) (,(intern (string-upcase (format nil "~A.b" var))) (b ,var)) (,(intern (string-upcase (format nil "~A.a" var))) (a ,var))) (declare (ignorable ,(intern (string-upcase (format nil "~A.r" var))) ,(intern (string-upcase (format nil "~A.g" var))) ,(intern (string-upcase (format nil "~A.b" var))) ,(intern (string-upcase (format nil "~A.a" var))))) ,@body (if ,free (free ,var))))) (defmethod free ((color color)) nil) (defmethod r ((color color)) (svref (fp color) 0)) (defmethod (setf r) (r-val (color color)) (setf (svref (fp color) 0) (cast-to-int r-val))) (defmethod g ((color color)) (svref (fp color) 1)) (defmethod (setf g) (g-val (color color)) (setf (svref (fp color) 1) (cast-to-int g-val))) (defmethod b ((color color)) (svref (fp color) 2)) (defmethod (setf b) (b-val (color color)) (setf (svref (fp color) 2) (cast-to-int b-val))) (defmethod a ((color color)) nil) (defmethod a ((color color-a)) (svref (fp color) 3)) (defmethod (setf a) (a-val (color color-a)) (setf (svref (fp color) 3) (cast-to-int a-val))) (defmethod set-color ((dst color) (src color)) (set-color-* dst :r (r src) :g (g src) :b (b src) :a (a src)) dst) (defmethod set-color-* ((color color) &key r g b a) (when r (setf (r color) r)) (when g (setf (g color) g)) (when b (setf (b color) b)) (when a (setf (a color) a)) color) (defmethod color-* ((color color)) (values (r color) (g color) (b color))) (defmethod color-* ((color color-a)) (values (r color) (g color) (b color) (a color))) (defmethod map-color-* ((r integer) (g integer) (b integer) a &optional (surface *default-surface*)) (if a (sdl-cffi::sdl-map-rgba (sdl-base::pixel-format (fp surface)) r g b a) (sdl-cffi::sdl-map-rgb (sdl-base::pixel-format (fp surface)) r g b))) (defmethod map-color ((color color) &optional (surface *default-surface*)) (map-color-* (r color) (g color) (b color) nil surface)) (defmethod map-color ((color color-a) &optional (surface *default-surface*)) (map-color-* (r color) (g color) (b color) (a color) surface)) (defmethod pack-color-* ((r integer) (g integer) (b integer) &optional (a nil)) (let ((col #x00000000)) (setf col (logior (ash r 24) (ash g 16) (ash b 8) (if a a #xFF))) col)) (defmethod pack-color ((color color)) (pack-color-* (r color) (g color) (b color))) (defmethod pack-color ((color color-a)) (pack-color-* (r color) (g color) (b color) (a color))) (defmacro with-foreign-color-copy ((struct color) &body body) "Creates and assigns a new foreign `SDL_Color` to `STRUCT`. Then copies the color components from `COLOR` into `STRUCT`. `STRUCT` is free'd when out of scope." `(cffi:with-foreign-object (,struct 'sdl-cffi::SDL-Color) (cffi:with-foreign-slots ((sdl-cffi::r sdl-cffi::g sdl-cffi::b) ,struct sdl-cffi::SDL-Color) (setf sdl-cffi::r (r ,color) sdl-cffi::g (g ,color) sdl-cffi::b (b ,color))) ,@body)) (defmethod color= (color1 color2) (declare (ignore color1 color2)) nil) (defmethod color= ((color1 color) (color2 color)) (and (eq (r color1) (r color2)) (eq (g color1) (g color2)) (eq (b color1) (b color2)))) (defmethod color= ((color1 color-a) (color2 color-a)) (and (eq (r color1) (r color2)) (eq (g color1) (g color2)) (eq (b color1) (b color2)) (eq (a color1) (a color2)))) (defmethod any-color-but-this (color) (color :r (if (> (r color) 254) 0 255)))
6f23672b084a2ab45b0501caf18c228f34495f9a6534ed78de8f983d2776181e
TrustInSoft/tis-kernel
utils_parser.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Aorai plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) ( Institut National de Recherche en Informatique et en (* Automatique) *) INSA ( Institut National des Sciences Appliquees ) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) let rec get_last_field my_field my_offset = match my_offset with | Cil_types.NoOffset -> my_field | Cil_types.Field(fieldinfo,the_offset) -> get_last_field fieldinfo the_offset | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : struct with array access." let rec add_offset father_offset new_offset = match father_offset with | Cil_types.NoOffset -> new_offset | Cil_types.Field(_,the_offset) -> (Cil.addOffset father_offset (add_offset the_offset new_offset)) | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : struct with array access." let rec get_field_info_from_name my_list name = if(List.length my_list <> 0) then begin let my_field = List.hd my_list in if(my_field.Cil_types.fname = name) then my_field else get_field_info_from_name (List.tl my_list) name end else Aorai_option.fatal "no field found with name :%s" name let get_new_offset my_host my_offset name= match my_host with | Cil_types.Var(var) -> let var_info = var in (* if my_offset is null no need to search the last field *) (* else we need to have the last *) let my_comp = if (my_offset = Cil_types.NoOffset) then match var_info.Cil_types.vtype with | Cil_types.TComp(mc,_,_) -> mc | _ -> assert false Cil_types . TComp(my_comp , _ , _ ) = var_info.Cil_types.vtype in else begin let get_field_from_offset my_offset = begin match my_offset with | Cil_types.Field(fieldinfo,_) -> fieldinfo | _ -> Aorai_option.fatal "support only struct no array wtih struct" end in let field_info = get_field_from_offset my_offset in let last_field_offset = get_last_field field_info my_offset in (* last field in offset but not the field we want, for that we search in*) let mc = last_field_offset.Cil_types.fcomp in mc end in let field_info = get_field_info_from_name my_comp.Cil_types.cfields name in Cil_types.Field(field_info,Cil_types.NoOffset) | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : mem is not supported"
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/aorai/utils_parser.ml
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) Automatique) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ if my_offset is null no need to search the last field else we need to have the last last field in offset but not the field we want, for that we search in
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Aorai plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies ( Institut National de Recherche en Informatique et en INSA ( Institut National des Sciences Appliquees ) Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . let rec get_last_field my_field my_offset = match my_offset with | Cil_types.NoOffset -> my_field | Cil_types.Field(fieldinfo,the_offset) -> get_last_field fieldinfo the_offset | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : struct with array access." let rec add_offset father_offset new_offset = match father_offset with | Cil_types.NoOffset -> new_offset | Cil_types.Field(_,the_offset) -> (Cil.addOffset father_offset (add_offset the_offset new_offset)) | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : struct with array access." let rec get_field_info_from_name my_list name = if(List.length my_list <> 0) then begin let my_field = List.hd my_list in if(my_field.Cil_types.fname = name) then my_field else get_field_info_from_name (List.tl my_list) name end else Aorai_option.fatal "no field found with name :%s" name let get_new_offset my_host my_offset name= match my_host with | Cil_types.Var(var) -> let var_info = var in let my_comp = if (my_offset = Cil_types.NoOffset) then match var_info.Cil_types.vtype with | Cil_types.TComp(mc,_,_) -> mc | _ -> assert false Cil_types . TComp(my_comp , _ , _ ) = var_info.Cil_types.vtype in else begin let get_field_from_offset my_offset = begin match my_offset with | Cil_types.Field(fieldinfo,_) -> fieldinfo | _ -> Aorai_option.fatal "support only struct no array wtih struct" end in let field_info = get_field_from_offset my_offset in let last_field_offset = get_last_field field_info my_offset in let mc = last_field_offset.Cil_types.fcomp in mc end in let field_info = get_field_info_from_name my_comp.Cil_types.cfields name in Cil_types.Field(field_info,Cil_types.NoOffset) | _ -> Aorai_option.fatal "NOT YET IMPLEMENTED : mem is not supported"
397d88a26f34c03f69422aa3d0a223d6d7569718e0c3be2512e55b641959f48e
kennknowles/aspcc
configure.ml
open Conf;; open Util;; type aspcc_module = { name : string; findlibs : string list; desc : string; } let available_modules = [ { name = "VbPervasives"; findlibs = ["unix"; "netstring"]; desc = "The documented standard VbScript functions." }; { name = "aspIntrinsics"; findlibs = ["netstring"]; desc = "The intrinsic ASP objects minus session - currenlty uses CGI environment" }; { name = "regexp"; findlibs = ["pcre"]; desc = "The RegExp object" }; { name = "session_persil"; findlibs = ["mysql"]; desc = "The Session and Application ASP objects, implemented with PersiL" }; { name = "session_perl"; findlibs = ["perl"]; desc = "The Session and Application ASP objects, with perl's Apache::Session" }; { name = "session_hack"; findlibs = ["unix"]; desc = "The Session and Application APS objects, hacked with temp files" }; { name = "wscript"; findlibs = ["unix"]; desc = "Compatability with Wscript, for accessing Argv, etc" }; { name = "scripting"; findlibs = ["unix"]; desc = "Contains only the dictionary object." }; { name = "tools"; findlibs = []; desc = "The MSWC Tools object." }; { name = "browsertype"; findlibs = []; desc = "The MSWC BrowserType object" }; { name = "msXml_gdome2"; findlibs = ["gdome2"]; desc = "A wrapper on gdome2 compatible with MSXML. (incomplete)" }; { name = "msXml_pxp"; findlibs = ["pxp"]; desc = "A wrapper on pxp compatible with pxp. (broken)" }; { name = "ado"; findlibs = ["freetds"; "dbi"]; desc = "An ADO implementation on top of ocamldbi." } ] ;; let default_modules = [ "VbPervasives"; "scripting"; "aspIntrinsics"; "ado"; "wscript"; "tools"; "session_hack"; "regexp"; "browsertype"; ] ;; let spec = [ param "modules" (StringList default_modules) ~doc:( "\n\t\t\ Space-separated (must quote it!) list of modules to include - compile time only =(\n\t\t\ Defaults to: '" ^ (String.concat " " default_modules) ^ "' \n\t\t\ Available:\n\t\t" ^ (String.concat "\n\t\t" (List.map (fun x -> Printf.sprintf "%s\t%s" x.name x.desc) available_modules)) ^ "\n\n") ] ;; (* Dealing with which modules were selected *) module StringMap = Map.Make(String) let module_conf = Conf.configure spec let selected_modules = let module_names = (module_conf # get_stringlist "modules") in List.filter (fun x -> List.mem x.name module_names) available_modules let module_filename aspcc_mod = "runtime/modules/" ^ aspcc_mod.name ^ ".ml" let unique li = let rec unique_r ?(so_far = []) li = match li with | [] -> List.rev so_far | entry :: rest -> if List.mem entry rest then unique_r ~so_far rest else unique_r ~so_far:(entry :: so_far) rest in unique_r li let findlib_names = ["str"; "netstring"; "pcre"] @ (List.flatten (List.map (fun x -> x.findlibs) selected_modules)) let all_findlibs = List.map (fun libname -> Conf.findlib_check libname) (unique findlib_names) let findlib_conf = Conf.configure all_findlibs open AutoMake;; let prepend li item = li := item :: !li ;; let module_sources = List.map module_filename selected_modules ;; (* Inform the user of the configuration *) let _ = print_string (findlib_conf # summarize); print_string (module_conf # summarize_params); print_endline "Now 'make' to build the utilities, and 'make install' to install them.\n" (* The makefile generation information *) let _ = output_makefile ~configuration:(module_conf :> AutoMake.configuration) (package ~package:"aspcc" ~version:"0.1" ~sources:(split "frontends/MyArg.mli frontends/MyArg.ml parsed/Symbol.mli parsed/Symbol.ml runtime/Tables.mli runtime/Tables.ml parsed/AspAst.ml runtime/VbTypes.ml parsed/Opcode.ml runtime/VbValues.mli runtime/VbValues.ml output/vb.mli output/vb.ml output/opcodeDump.ml parsing/aspParser.mly parsing/aspLexer.mll typing/Typing.ml runtime/Runtime.mli runtime/Runtime.ml runtime/VbClass.mli runtime/VbClass.ml runtime/AstRun.mli runtime/AstRun.ml runtime/OpcodeRun.ml output/lexDump.mli output/lexDump.ml output/astDump.mli output/astDump.ml") ~findlibs:findlib_names ~includes:["parsed"; "parsing"; "runtime"; "output"; "frontends"; "compile"; "typing"] ~flags:[ [`document], ["-I ml -colorize-code -sort -keep-code"]; [`mly], ["-v"]; [`compile; `byte], ["-g"]; ] (* document all modules regardless of inclusion *) [ documentation "docs" ~sources:(split "runtime/modules/vbStdLib.ml runtime/modules/scripting.ml runtime/modules/msXml_pxp.ml runtime/modules/msXml_gdome2.ml runtime/modules/aspConsole.ml frontends/aspcc.ml frontends/mod_aspcc.ml"); executable "aspcc" ~sources:(module_sources @ (split "compile/compile.ml frontends/aspcc.ml")); executable "asptop" ~sources:(module_sources @ (split "compile/compile.ml frontends/asptop.ml")); executable "aspdoc" ~sources:(split "parsed/doc.mli parsed/doc.ml output/HtmlDoc.mli output/HtmlDoc.ml frontends/aspdoc.ml"); executable "aspcheck" ~sources:["frontends/aspcheck.ml"] ] ) ;;
null
https://raw.githubusercontent.com/kennknowles/aspcc/951a91cc21e291b1d3c750bbbca7fa79209edd08/configure.ml
ocaml
Dealing with which modules were selected Inform the user of the configuration The makefile generation information document all modules regardless of inclusion
open Conf;; open Util;; type aspcc_module = { name : string; findlibs : string list; desc : string; } let available_modules = [ { name = "VbPervasives"; findlibs = ["unix"; "netstring"]; desc = "The documented standard VbScript functions." }; { name = "aspIntrinsics"; findlibs = ["netstring"]; desc = "The intrinsic ASP objects minus session - currenlty uses CGI environment" }; { name = "regexp"; findlibs = ["pcre"]; desc = "The RegExp object" }; { name = "session_persil"; findlibs = ["mysql"]; desc = "The Session and Application ASP objects, implemented with PersiL" }; { name = "session_perl"; findlibs = ["perl"]; desc = "The Session and Application ASP objects, with perl's Apache::Session" }; { name = "session_hack"; findlibs = ["unix"]; desc = "The Session and Application APS objects, hacked with temp files" }; { name = "wscript"; findlibs = ["unix"]; desc = "Compatability with Wscript, for accessing Argv, etc" }; { name = "scripting"; findlibs = ["unix"]; desc = "Contains only the dictionary object." }; { name = "tools"; findlibs = []; desc = "The MSWC Tools object." }; { name = "browsertype"; findlibs = []; desc = "The MSWC BrowserType object" }; { name = "msXml_gdome2"; findlibs = ["gdome2"]; desc = "A wrapper on gdome2 compatible with MSXML. (incomplete)" }; { name = "msXml_pxp"; findlibs = ["pxp"]; desc = "A wrapper on pxp compatible with pxp. (broken)" }; { name = "ado"; findlibs = ["freetds"; "dbi"]; desc = "An ADO implementation on top of ocamldbi." } ] ;; let default_modules = [ "VbPervasives"; "scripting"; "aspIntrinsics"; "ado"; "wscript"; "tools"; "session_hack"; "regexp"; "browsertype"; ] ;; let spec = [ param "modules" (StringList default_modules) ~doc:( "\n\t\t\ Space-separated (must quote it!) list of modules to include - compile time only =(\n\t\t\ Defaults to: '" ^ (String.concat " " default_modules) ^ "' \n\t\t\ Available:\n\t\t" ^ (String.concat "\n\t\t" (List.map (fun x -> Printf.sprintf "%s\t%s" x.name x.desc) available_modules)) ^ "\n\n") ] ;; module StringMap = Map.Make(String) let module_conf = Conf.configure spec let selected_modules = let module_names = (module_conf # get_stringlist "modules") in List.filter (fun x -> List.mem x.name module_names) available_modules let module_filename aspcc_mod = "runtime/modules/" ^ aspcc_mod.name ^ ".ml" let unique li = let rec unique_r ?(so_far = []) li = match li with | [] -> List.rev so_far | entry :: rest -> if List.mem entry rest then unique_r ~so_far rest else unique_r ~so_far:(entry :: so_far) rest in unique_r li let findlib_names = ["str"; "netstring"; "pcre"] @ (List.flatten (List.map (fun x -> x.findlibs) selected_modules)) let all_findlibs = List.map (fun libname -> Conf.findlib_check libname) (unique findlib_names) let findlib_conf = Conf.configure all_findlibs open AutoMake;; let prepend li item = li := item :: !li ;; let module_sources = List.map module_filename selected_modules ;; let _ = print_string (findlib_conf # summarize); print_string (module_conf # summarize_params); print_endline "Now 'make' to build the utilities, and 'make install' to install them.\n" let _ = output_makefile ~configuration:(module_conf :> AutoMake.configuration) (package ~package:"aspcc" ~version:"0.1" ~sources:(split "frontends/MyArg.mli frontends/MyArg.ml parsed/Symbol.mli parsed/Symbol.ml runtime/Tables.mli runtime/Tables.ml parsed/AspAst.ml runtime/VbTypes.ml parsed/Opcode.ml runtime/VbValues.mli runtime/VbValues.ml output/vb.mli output/vb.ml output/opcodeDump.ml parsing/aspParser.mly parsing/aspLexer.mll typing/Typing.ml runtime/Runtime.mli runtime/Runtime.ml runtime/VbClass.mli runtime/VbClass.ml runtime/AstRun.mli runtime/AstRun.ml runtime/OpcodeRun.ml output/lexDump.mli output/lexDump.ml output/astDump.mli output/astDump.ml") ~findlibs:findlib_names ~includes:["parsed"; "parsing"; "runtime"; "output"; "frontends"; "compile"; "typing"] ~flags:[ [`document], ["-I ml -colorize-code -sort -keep-code"]; [`mly], ["-v"]; [`compile; `byte], ["-g"]; ] [ documentation "docs" ~sources:(split "runtime/modules/vbStdLib.ml runtime/modules/scripting.ml runtime/modules/msXml_pxp.ml runtime/modules/msXml_gdome2.ml runtime/modules/aspConsole.ml frontends/aspcc.ml frontends/mod_aspcc.ml"); executable "aspcc" ~sources:(module_sources @ (split "compile/compile.ml frontends/aspcc.ml")); executable "asptop" ~sources:(module_sources @ (split "compile/compile.ml frontends/asptop.ml")); executable "aspdoc" ~sources:(split "parsed/doc.mli parsed/doc.ml output/HtmlDoc.mli output/HtmlDoc.ml frontends/aspdoc.ml"); executable "aspcheck" ~sources:["frontends/aspcheck.ml"] ] ) ;;
47ca77cd37d13094eb622b21809f222e0ad8388f1c353bc4920d92ce1ce9654b
CodyReichert/qi
regex-class-util.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*- $ Header : /usr / local / cvsrep / cl - ppcre / regex - class - util.lisp , v 1.9 2009/09/17 19:17:31 edi Exp $ ;;; This file contains some utility methods for REGEX objects. Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-ppcre) The following four methods allow a VOID object to behave like a zero - length STR object ( only readers needed ) (defmethod len ((void void)) (declare #.*standard-optimize-settings*) 0) (defmethod str ((void void)) (declare #.*standard-optimize-settings*) "") (defmethod skip ((void void)) (declare #.*standard-optimize-settings*) nil) (defmethod start-of-end-string-p ((void void)) (declare #.*standard-optimize-settings*) nil) (defgeneric case-mode (regex old-case-mode) (declare #.*standard-optimize-settings*) (:documentation "Utility function used by the optimizer (see GATHER-STRINGS). Returns a keyword denoting the case-(in)sensitivity of a STR or its second argument if the STR has length 0. Returns NIL for REGEX objects which are not of type STR.")) (defmethod case-mode ((str str) old-case-mode) (declare #.*standard-optimize-settings*) (cond ((zerop (len str)) old-case-mode) ((case-insensitive-p str) :case-insensitive) (t :case-sensitive))) (defmethod case-mode ((regex regex) old-case-mode) (declare #.*standard-optimize-settings*) (declare (ignore old-case-mode)) nil) (defgeneric copy-regex (regex) (declare #.*standard-optimize-settings*) (:documentation "Implements a deep copy of a REGEX object.")) (defmethod copy-regex ((anchor anchor)) (declare #.*standard-optimize-settings*) (make-instance 'anchor :startp (startp anchor) :multi-line-p (multi-line-p anchor) :no-newline-p (no-newline-p anchor))) (defmethod copy-regex ((everything everything)) (declare #.*standard-optimize-settings*) (make-instance 'everything :single-line-p (single-line-p everything))) (defmethod copy-regex ((word-boundary word-boundary)) (declare #.*standard-optimize-settings*) (make-instance 'word-boundary :negatedp (negatedp word-boundary))) (defmethod copy-regex ((void void)) (declare #.*standard-optimize-settings*) (make-instance 'void)) (defmethod copy-regex ((lookahead lookahead)) (declare #.*standard-optimize-settings*) (make-instance 'lookahead :regex (copy-regex (regex lookahead)) :positivep (positivep lookahead))) (defmethod copy-regex ((seq seq)) (declare #.*standard-optimize-settings*) (make-instance 'seq :elements (mapcar #'copy-regex (elements seq)))) (defmethod copy-regex ((alternation alternation)) (declare #.*standard-optimize-settings*) (make-instance 'alternation :choices (mapcar #'copy-regex (choices alternation)))) (defmethod copy-regex ((branch branch)) (declare #.*standard-optimize-settings*) (with-slots (test) branch (make-instance 'branch :test (if (typep test 'regex) (copy-regex test) test) :then-regex (copy-regex (then-regex branch)) :else-regex (copy-regex (else-regex branch))))) (defmethod copy-regex ((lookbehind lookbehind)) (declare #.*standard-optimize-settings*) (make-instance 'lookbehind :regex (copy-regex (regex lookbehind)) :positivep (positivep lookbehind) :len (len lookbehind))) (defmethod copy-regex ((repetition repetition)) (declare #.*standard-optimize-settings*) (make-instance 'repetition :regex (copy-regex (regex repetition)) :greedyp (greedyp repetition) :minimum (minimum repetition) :maximum (maximum repetition) :min-len (min-len repetition) :len (len repetition) :contains-register-p (contains-register-p repetition))) (defmethod copy-regex ((register register)) (declare #.*standard-optimize-settings*) (make-instance 'register :regex (copy-regex (regex register)) :num (num register) :name (name register))) (defmethod copy-regex ((standalone standalone)) (declare #.*standard-optimize-settings*) (make-instance 'standalone :regex (copy-regex (regex standalone)))) (defmethod copy-regex ((back-reference back-reference)) (declare #.*standard-optimize-settings*) (make-instance 'back-reference :num (num back-reference) :case-insensitive-p (case-insensitive-p back-reference))) (defmethod copy-regex ((char-class char-class)) (declare #.*standard-optimize-settings*) (make-instance 'char-class :test-function (test-function char-class))) (defmethod copy-regex ((str str)) (declare #.*standard-optimize-settings*) (make-instance 'str :str (str str) :case-insensitive-p (case-insensitive-p str))) (defmethod copy-regex ((filter filter)) (declare #.*standard-optimize-settings*) (make-instance 'filter :fn (fn filter) :len (len filter))) ;;; Note that COPY-REGEX and REMOVE-REGISTERS could have easily been wrapped into one function . Maybe in the next release ... Further note that this function is used by CONVERT to factor out ;;; complicated repetitions, i.e. cases like ( a ) * - > ( ? : a*(a ) ) ? ;;; This won't work for, say, ;;; ((a)|(b))* -> (?:(?:a|b)*((a)|(b)))? and therefore we stop REGISTER removal once we see an ALTERNATION . (defgeneric remove-registers (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns a deep copy of a REGEX (see COPY-REGEX) and optionally removes embedded REGISTER objects if possible and if the special variable REMOVE-REGISTERS-P is true.")) (defmethod remove-registers ((register register)) (declare #.*standard-optimize-settings*) (declare (special remove-registers-p reg-seen)) (cond (remove-registers-p (remove-registers (regex register))) (t mark REG - SEEN as true so enclosing REPETITION objects ;; (see method below) know if they contain a register or not (setq reg-seen t) (copy-regex register)))) (defmethod remove-registers ((repetition repetition)) (declare #.*standard-optimize-settings*) (let* (reg-seen (inner-regex (remove-registers (regex repetition)))) REMOVE - REGISTERS will set REG - SEEN ( see method above ) if ( REGEX REPETITION ) contains a REGISTER (declare (special reg-seen)) (make-instance 'repetition :regex inner-regex :greedyp (greedyp repetition) :minimum (minimum repetition) :maximum (maximum repetition) :min-len (min-len repetition) :len (len repetition) :contains-register-p reg-seen))) (defmethod remove-registers ((standalone standalone)) (declare #.*standard-optimize-settings*) (make-instance 'standalone :regex (remove-registers (regex standalone)))) (defmethod remove-registers ((lookahead lookahead)) (declare #.*standard-optimize-settings*) (make-instance 'lookahead :regex (remove-registers (regex lookahead)) :positivep (positivep lookahead))) (defmethod remove-registers ((lookbehind lookbehind)) (declare #.*standard-optimize-settings*) (make-instance 'lookbehind :regex (remove-registers (regex lookbehind)) :positivep (positivep lookbehind) :len (len lookbehind))) (defmethod remove-registers ((branch branch)) (declare #.*standard-optimize-settings*) (with-slots (test) branch (make-instance 'branch :test (if (typep test 'regex) (remove-registers test) test) :then-regex (remove-registers (then-regex branch)) :else-regex (remove-registers (else-regex branch))))) (defmethod remove-registers ((alternation alternation)) (declare #.*standard-optimize-settings*) (declare (special remove-registers-p)) an ALTERNATION , so we ca n't remove REGISTER objects further down (setq remove-registers-p nil) (copy-regex alternation)) (defmethod remove-registers ((regex regex)) (declare #.*standard-optimize-settings*) (copy-regex regex)) (defmethod remove-registers ((seq seq)) (declare #.*standard-optimize-settings*) (make-instance 'seq :elements (mapcar #'remove-registers (elements seq)))) (defgeneric everythingp (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns an EVERYTHING object if REGEX is equivalent to this object, otherwise NIL. So, \"(.){1}\" would return true \(i.e. the object corresponding to \".\", for example.")) (defmethod everythingp ((seq seq)) (declare #.*standard-optimize-settings*) we might have degenerate cases like (: : VOID ... ) ;; due to the parsing process (let ((cleaned-elements (remove-if #'(lambda (element) (typep element 'void)) (elements seq)))) (and (= 1 (length cleaned-elements)) (everythingp (first cleaned-elements))))) (defmethod everythingp ((alternation alternation)) (declare #.*standard-optimize-settings*) (with-slots (choices) alternation (and (= 1 (length choices)) ;; this is unlikely to happen for human-generated regexes, ;; but machine-generated ones might look like this (everythingp (first choices))))) (defmethod everythingp ((repetition repetition)) (declare #.*standard-optimize-settings*) (with-slots (maximum minimum regex) repetition (and maximum (= 1 minimum maximum) ;; treat "<regex>{1,1}" like "<regex>" (everythingp regex)))) (defmethod everythingp ((register register)) (declare #.*standard-optimize-settings*) (everythingp (regex register))) (defmethod everythingp ((standalone standalone)) (declare #.*standard-optimize-settings*) (everythingp (regex standalone))) (defmethod everythingp ((everything everything)) (declare #.*standard-optimize-settings*) everything) (defmethod everythingp ((regex regex)) (declare #.*standard-optimize-settings*) the general case for ANCHOR , BACK - REFERENCE , BRANCH , CHAR - CLASS , LOOKAHEAD , LOOKBEHIND , STR , VOID , FILTER , and WORD - BOUNDARY nil) (defgeneric regex-length (regex) (declare #.*standard-optimize-settings*) (:documentation "Return the length of REGEX if it is fixed, NIL otherwise.")) (defmethod regex-length ((seq seq)) (declare #.*standard-optimize-settings*) simply add all inner lengths unless one of them is NIL (loop for sub-regex in (elements seq) for len = (regex-length sub-regex) if (not len) do (return nil) sum len)) (defmethod regex-length ((alternation alternation)) (declare #.*standard-optimize-settings*) ;; only return a true value if all inner lengths are non-NIL and ;; mutually equal (loop for sub-regex in (choices alternation) for old-len = nil then len for len = (regex-length sub-regex) if (or (not len) (and old-len (/= len old-len))) do (return nil) finally (return len))) (defmethod regex-length ((branch branch)) (declare #.*standard-optimize-settings*) ;; only return a true value if both alternations have a length and ;; if they're equal (let ((then-length (regex-length (then-regex branch)))) (and then-length (eql then-length (regex-length (else-regex branch))) then-length))) (defmethod regex-length ((repetition repetition)) (declare #.*standard-optimize-settings*) ;; we can only compute the length of a REPETITION object if the ;; number of repetitions is fixed; note that we don't call ;; REGEX-LENGTH for the inner regex, we assume that the LEN slot is ;; always set correctly (with-slots (len minimum maximum) repetition (if (and len (eql minimum maximum)) (* minimum len) nil))) (defmethod regex-length ((register register)) (declare #.*standard-optimize-settings*) (regex-length (regex register))) (defmethod regex-length ((standalone standalone)) (declare #.*standard-optimize-settings*) (regex-length (regex standalone))) (defmethod regex-length ((back-reference back-reference)) (declare #.*standard-optimize-settings*) ;; with enough effort we could possibly do better here, but ;; currently we just give up and return NIL nil) (defmethod regex-length ((char-class char-class)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-length ((everything everything)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-length ((str str)) (declare #.*standard-optimize-settings*) (len str)) (defmethod regex-length ((filter filter)) (declare #.*standard-optimize-settings*) (len filter)) (defmethod regex-length ((regex regex)) (declare #.*standard-optimize-settings*) ;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and WORD - BOUNDARY ( which all have zero - length ) 0) (defgeneric regex-min-length (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns the minimal length of REGEX.")) (defmethod regex-min-length ((seq seq)) (declare #.*standard-optimize-settings*) ;; simply add all inner minimal lengths (loop for sub-regex in (elements seq) for len = (regex-min-length sub-regex) sum len)) (defmethod regex-min-length ((alternation alternation)) (declare #.*standard-optimize-settings*) ;; minimal length of an alternation is the minimal length of the ;; "shortest" element (loop for sub-regex in (choices alternation) for len = (regex-min-length sub-regex) minimize len)) (defmethod regex-min-length ((branch branch)) (declare #.*standard-optimize-settings*) ;; minimal length of both alternations (min (regex-min-length (then-regex branch)) (regex-min-length (else-regex branch)))) (defmethod regex-min-length ((repetition repetition)) (declare #.*standard-optimize-settings*) ;; obviously the product of the inner minimal length and the minimal ;; number of repetitions (* (minimum repetition) (min-len repetition))) (defmethod regex-min-length ((register register)) (declare #.*standard-optimize-settings*) (regex-min-length (regex register))) (defmethod regex-min-length ((standalone standalone)) (declare #.*standard-optimize-settings*) (regex-min-length (regex standalone))) (defmethod regex-min-length ((char-class char-class)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-min-length ((everything everything)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-min-length ((str str)) (declare #.*standard-optimize-settings*) (len str)) (defmethod regex-min-length ((filter filter)) (declare #.*standard-optimize-settings*) (or (len filter) 0)) (defmethod regex-min-length ((regex regex)) (declare #.*standard-optimize-settings*) ;; the general case for ANCHOR, BACK-REFERENCE, LOOKAHEAD, ;; LOOKBEHIND, VOID, and WORD-BOUNDARY 0) (defgeneric compute-offsets (regex start-pos) (declare #.*standard-optimize-settings*) (:documentation "Returns the offset the following regex would have relative to START-POS or NIL if we can't compute it. Sets the OFFSET slot of REGEX to START-POS if REGEX is a STR. May also affect OFFSET slots of STR objects further down the tree.")) ;; note that we're actually only interested in the offset of " top - level " STR objects ( see ADVANCE - FN in the SCAN function ) so we ;; can stop at variable-length alternations and don't need to descend ;; into repetitions (defmethod compute-offsets ((seq seq) start-pos) (declare #.*standard-optimize-settings*) (loop for element in (elements seq) ;; advance offset argument for next call while looping through ;; the elements for pos = start-pos then curr-offset for curr-offset = (compute-offsets element pos) while curr-offset finally (return curr-offset))) (defmethod compute-offsets ((alternation alternation) start-pos) (declare #.*standard-optimize-settings*) (loop for choice in (choices alternation) for old-offset = nil then curr-offset for curr-offset = (compute-offsets choice start-pos) we stop immediately if two alternations do n't result in the ;; same offset if (or (not curr-offset) (and old-offset (/= curr-offset old-offset))) do (return nil) finally (return curr-offset))) (defmethod compute-offsets ((branch branch) start-pos) (declare #.*standard-optimize-settings*) ;; only return offset if both alternations have equal value (let ((then-offset (compute-offsets (then-regex branch) start-pos))) (and then-offset (eql then-offset (compute-offsets (else-regex branch) start-pos)) then-offset))) (defmethod compute-offsets ((repetition repetition) start-pos) (declare #.*standard-optimize-settings*) ;; no need to descend into the inner regex (with-slots (len minimum maximum) repetition (if (and len (eq minimum maximum)) ;; fixed number of repetitions, so we know how to proceed (+ start-pos (* minimum len)) ;; otherwise return NIL nil))) (defmethod compute-offsets ((register register) start-pos) (declare #.*standard-optimize-settings*) (compute-offsets (regex register) start-pos)) (defmethod compute-offsets ((standalone standalone) start-pos) (declare #.*standard-optimize-settings*) (compute-offsets (regex standalone) start-pos)) (defmethod compute-offsets ((char-class char-class) start-pos) (declare #.*standard-optimize-settings*) (1+ start-pos)) (defmethod compute-offsets ((everything everything) start-pos) (declare #.*standard-optimize-settings*) (1+ start-pos)) (defmethod compute-offsets ((str str) start-pos) (declare #.*standard-optimize-settings*) (setf (offset str) start-pos) (+ start-pos (len str))) (defmethod compute-offsets ((back-reference back-reference) start-pos) (declare #.*standard-optimize-settings*) ;; with enough effort we could possibly do better here, but ;; currently we just give up and return NIL (declare (ignore start-pos)) nil) (defmethod compute-offsets ((filter filter) start-pos) (declare #.*standard-optimize-settings*) (let ((len (len filter))) (if len (+ start-pos len) nil))) (defmethod compute-offsets ((regex regex) start-pos) (declare #.*standard-optimize-settings*) ;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and WORD - BOUNDARY ( which all have zero - length ) start-pos)
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/cl-ppcre-master/regex-class-util.lisp
lisp
Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*- This file contains some utility methods for REGEX objects. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Note that COPY-REGEX and REMOVE-REGISTERS could have easily been complicated repetitions, i.e. cases like This won't work for, say, ((a)|(b))* -> (?:(?:a|b)*((a)|(b)))? (see method below) know if they contain a register or not due to the parsing process this is unlikely to happen for human-generated regexes, but machine-generated ones might look like this treat "<regex>{1,1}" like "<regex>" only return a true value if all inner lengths are non-NIL and mutually equal only return a true value if both alternations have a length and if they're equal we can only compute the length of a REPETITION object if the number of repetitions is fixed; note that we don't call REGEX-LENGTH for the inner regex, we assume that the LEN slot is always set correctly with enough effort we could possibly do better here, but currently we just give up and return NIL the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and simply add all inner minimal lengths minimal length of an alternation is the minimal length of the "shortest" element minimal length of both alternations obviously the product of the inner minimal length and the minimal number of repetitions the general case for ANCHOR, BACK-REFERENCE, LOOKAHEAD, LOOKBEHIND, VOID, and WORD-BOUNDARY note that we're actually only interested in the offset of can stop at variable-length alternations and don't need to descend into repetitions advance offset argument for next call while looping through the elements same offset only return offset if both alternations have equal value no need to descend into the inner regex fixed number of repetitions, so we know how to proceed otherwise return NIL with enough effort we could possibly do better here, but currently we just give up and return NIL the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and
$ Header : /usr / local / cvsrep / cl - ppcre / regex - class - util.lisp , v 1.9 2009/09/17 19:17:31 edi Exp $ Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :cl-ppcre) The following four methods allow a VOID object to behave like a zero - length STR object ( only readers needed ) (defmethod len ((void void)) (declare #.*standard-optimize-settings*) 0) (defmethod str ((void void)) (declare #.*standard-optimize-settings*) "") (defmethod skip ((void void)) (declare #.*standard-optimize-settings*) nil) (defmethod start-of-end-string-p ((void void)) (declare #.*standard-optimize-settings*) nil) (defgeneric case-mode (regex old-case-mode) (declare #.*standard-optimize-settings*) (:documentation "Utility function used by the optimizer (see GATHER-STRINGS). Returns a keyword denoting the case-(in)sensitivity of a STR or its second argument if the STR has length 0. Returns NIL for REGEX objects which are not of type STR.")) (defmethod case-mode ((str str) old-case-mode) (declare #.*standard-optimize-settings*) (cond ((zerop (len str)) old-case-mode) ((case-insensitive-p str) :case-insensitive) (t :case-sensitive))) (defmethod case-mode ((regex regex) old-case-mode) (declare #.*standard-optimize-settings*) (declare (ignore old-case-mode)) nil) (defgeneric copy-regex (regex) (declare #.*standard-optimize-settings*) (:documentation "Implements a deep copy of a REGEX object.")) (defmethod copy-regex ((anchor anchor)) (declare #.*standard-optimize-settings*) (make-instance 'anchor :startp (startp anchor) :multi-line-p (multi-line-p anchor) :no-newline-p (no-newline-p anchor))) (defmethod copy-regex ((everything everything)) (declare #.*standard-optimize-settings*) (make-instance 'everything :single-line-p (single-line-p everything))) (defmethod copy-regex ((word-boundary word-boundary)) (declare #.*standard-optimize-settings*) (make-instance 'word-boundary :negatedp (negatedp word-boundary))) (defmethod copy-regex ((void void)) (declare #.*standard-optimize-settings*) (make-instance 'void)) (defmethod copy-regex ((lookahead lookahead)) (declare #.*standard-optimize-settings*) (make-instance 'lookahead :regex (copy-regex (regex lookahead)) :positivep (positivep lookahead))) (defmethod copy-regex ((seq seq)) (declare #.*standard-optimize-settings*) (make-instance 'seq :elements (mapcar #'copy-regex (elements seq)))) (defmethod copy-regex ((alternation alternation)) (declare #.*standard-optimize-settings*) (make-instance 'alternation :choices (mapcar #'copy-regex (choices alternation)))) (defmethod copy-regex ((branch branch)) (declare #.*standard-optimize-settings*) (with-slots (test) branch (make-instance 'branch :test (if (typep test 'regex) (copy-regex test) test) :then-regex (copy-regex (then-regex branch)) :else-regex (copy-regex (else-regex branch))))) (defmethod copy-regex ((lookbehind lookbehind)) (declare #.*standard-optimize-settings*) (make-instance 'lookbehind :regex (copy-regex (regex lookbehind)) :positivep (positivep lookbehind) :len (len lookbehind))) (defmethod copy-regex ((repetition repetition)) (declare #.*standard-optimize-settings*) (make-instance 'repetition :regex (copy-regex (regex repetition)) :greedyp (greedyp repetition) :minimum (minimum repetition) :maximum (maximum repetition) :min-len (min-len repetition) :len (len repetition) :contains-register-p (contains-register-p repetition))) (defmethod copy-regex ((register register)) (declare #.*standard-optimize-settings*) (make-instance 'register :regex (copy-regex (regex register)) :num (num register) :name (name register))) (defmethod copy-regex ((standalone standalone)) (declare #.*standard-optimize-settings*) (make-instance 'standalone :regex (copy-regex (regex standalone)))) (defmethod copy-regex ((back-reference back-reference)) (declare #.*standard-optimize-settings*) (make-instance 'back-reference :num (num back-reference) :case-insensitive-p (case-insensitive-p back-reference))) (defmethod copy-regex ((char-class char-class)) (declare #.*standard-optimize-settings*) (make-instance 'char-class :test-function (test-function char-class))) (defmethod copy-regex ((str str)) (declare #.*standard-optimize-settings*) (make-instance 'str :str (str str) :case-insensitive-p (case-insensitive-p str))) (defmethod copy-regex ((filter filter)) (declare #.*standard-optimize-settings*) (make-instance 'filter :fn (fn filter) :len (len filter))) wrapped into one function . Maybe in the next release ... Further note that this function is used by CONVERT to factor out ( a ) * - > ( ? : a*(a ) ) ? and therefore we stop REGISTER removal once we see an ALTERNATION . (defgeneric remove-registers (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns a deep copy of a REGEX (see COPY-REGEX) and optionally removes embedded REGISTER objects if possible and if the special variable REMOVE-REGISTERS-P is true.")) (defmethod remove-registers ((register register)) (declare #.*standard-optimize-settings*) (declare (special remove-registers-p reg-seen)) (cond (remove-registers-p (remove-registers (regex register))) (t mark REG - SEEN as true so enclosing REPETITION objects (setq reg-seen t) (copy-regex register)))) (defmethod remove-registers ((repetition repetition)) (declare #.*standard-optimize-settings*) (let* (reg-seen (inner-regex (remove-registers (regex repetition)))) REMOVE - REGISTERS will set REG - SEEN ( see method above ) if ( REGEX REPETITION ) contains a REGISTER (declare (special reg-seen)) (make-instance 'repetition :regex inner-regex :greedyp (greedyp repetition) :minimum (minimum repetition) :maximum (maximum repetition) :min-len (min-len repetition) :len (len repetition) :contains-register-p reg-seen))) (defmethod remove-registers ((standalone standalone)) (declare #.*standard-optimize-settings*) (make-instance 'standalone :regex (remove-registers (regex standalone)))) (defmethod remove-registers ((lookahead lookahead)) (declare #.*standard-optimize-settings*) (make-instance 'lookahead :regex (remove-registers (regex lookahead)) :positivep (positivep lookahead))) (defmethod remove-registers ((lookbehind lookbehind)) (declare #.*standard-optimize-settings*) (make-instance 'lookbehind :regex (remove-registers (regex lookbehind)) :positivep (positivep lookbehind) :len (len lookbehind))) (defmethod remove-registers ((branch branch)) (declare #.*standard-optimize-settings*) (with-slots (test) branch (make-instance 'branch :test (if (typep test 'regex) (remove-registers test) test) :then-regex (remove-registers (then-regex branch)) :else-regex (remove-registers (else-regex branch))))) (defmethod remove-registers ((alternation alternation)) (declare #.*standard-optimize-settings*) (declare (special remove-registers-p)) an ALTERNATION , so we ca n't remove REGISTER objects further down (setq remove-registers-p nil) (copy-regex alternation)) (defmethod remove-registers ((regex regex)) (declare #.*standard-optimize-settings*) (copy-regex regex)) (defmethod remove-registers ((seq seq)) (declare #.*standard-optimize-settings*) (make-instance 'seq :elements (mapcar #'remove-registers (elements seq)))) (defgeneric everythingp (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns an EVERYTHING object if REGEX is equivalent to this object, otherwise NIL. So, \"(.){1}\" would return true \(i.e. the object corresponding to \".\", for example.")) (defmethod everythingp ((seq seq)) (declare #.*standard-optimize-settings*) we might have degenerate cases like (: : VOID ... ) (let ((cleaned-elements (remove-if #'(lambda (element) (typep element 'void)) (elements seq)))) (and (= 1 (length cleaned-elements)) (everythingp (first cleaned-elements))))) (defmethod everythingp ((alternation alternation)) (declare #.*standard-optimize-settings*) (with-slots (choices) alternation (and (= 1 (length choices)) (everythingp (first choices))))) (defmethod everythingp ((repetition repetition)) (declare #.*standard-optimize-settings*) (with-slots (maximum minimum regex) repetition (and maximum (= 1 minimum maximum) (everythingp regex)))) (defmethod everythingp ((register register)) (declare #.*standard-optimize-settings*) (everythingp (regex register))) (defmethod everythingp ((standalone standalone)) (declare #.*standard-optimize-settings*) (everythingp (regex standalone))) (defmethod everythingp ((everything everything)) (declare #.*standard-optimize-settings*) everything) (defmethod everythingp ((regex regex)) (declare #.*standard-optimize-settings*) the general case for ANCHOR , BACK - REFERENCE , BRANCH , CHAR - CLASS , LOOKAHEAD , LOOKBEHIND , STR , VOID , FILTER , and WORD - BOUNDARY nil) (defgeneric regex-length (regex) (declare #.*standard-optimize-settings*) (:documentation "Return the length of REGEX if it is fixed, NIL otherwise.")) (defmethod regex-length ((seq seq)) (declare #.*standard-optimize-settings*) simply add all inner lengths unless one of them is NIL (loop for sub-regex in (elements seq) for len = (regex-length sub-regex) if (not len) do (return nil) sum len)) (defmethod regex-length ((alternation alternation)) (declare #.*standard-optimize-settings*) (loop for sub-regex in (choices alternation) for old-len = nil then len for len = (regex-length sub-regex) if (or (not len) (and old-len (/= len old-len))) do (return nil) finally (return len))) (defmethod regex-length ((branch branch)) (declare #.*standard-optimize-settings*) (let ((then-length (regex-length (then-regex branch)))) (and then-length (eql then-length (regex-length (else-regex branch))) then-length))) (defmethod regex-length ((repetition repetition)) (declare #.*standard-optimize-settings*) (with-slots (len minimum maximum) repetition (if (and len (eql minimum maximum)) (* minimum len) nil))) (defmethod regex-length ((register register)) (declare #.*standard-optimize-settings*) (regex-length (regex register))) (defmethod regex-length ((standalone standalone)) (declare #.*standard-optimize-settings*) (regex-length (regex standalone))) (defmethod regex-length ((back-reference back-reference)) (declare #.*standard-optimize-settings*) nil) (defmethod regex-length ((char-class char-class)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-length ((everything everything)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-length ((str str)) (declare #.*standard-optimize-settings*) (len str)) (defmethod regex-length ((filter filter)) (declare #.*standard-optimize-settings*) (len filter)) (defmethod regex-length ((regex regex)) (declare #.*standard-optimize-settings*) WORD - BOUNDARY ( which all have zero - length ) 0) (defgeneric regex-min-length (regex) (declare #.*standard-optimize-settings*) (:documentation "Returns the minimal length of REGEX.")) (defmethod regex-min-length ((seq seq)) (declare #.*standard-optimize-settings*) (loop for sub-regex in (elements seq) for len = (regex-min-length sub-regex) sum len)) (defmethod regex-min-length ((alternation alternation)) (declare #.*standard-optimize-settings*) (loop for sub-regex in (choices alternation) for len = (regex-min-length sub-regex) minimize len)) (defmethod regex-min-length ((branch branch)) (declare #.*standard-optimize-settings*) (min (regex-min-length (then-regex branch)) (regex-min-length (else-regex branch)))) (defmethod regex-min-length ((repetition repetition)) (declare #.*standard-optimize-settings*) (* (minimum repetition) (min-len repetition))) (defmethod regex-min-length ((register register)) (declare #.*standard-optimize-settings*) (regex-min-length (regex register))) (defmethod regex-min-length ((standalone standalone)) (declare #.*standard-optimize-settings*) (regex-min-length (regex standalone))) (defmethod regex-min-length ((char-class char-class)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-min-length ((everything everything)) (declare #.*standard-optimize-settings*) 1) (defmethod regex-min-length ((str str)) (declare #.*standard-optimize-settings*) (len str)) (defmethod regex-min-length ((filter filter)) (declare #.*standard-optimize-settings*) (or (len filter) 0)) (defmethod regex-min-length ((regex regex)) (declare #.*standard-optimize-settings*) 0) (defgeneric compute-offsets (regex start-pos) (declare #.*standard-optimize-settings*) (:documentation "Returns the offset the following regex would have relative to START-POS or NIL if we can't compute it. Sets the OFFSET slot of REGEX to START-POS if REGEX is a STR. May also affect OFFSET slots of STR objects further down the tree.")) " top - level " STR objects ( see ADVANCE - FN in the SCAN function ) so we (defmethod compute-offsets ((seq seq) start-pos) (declare #.*standard-optimize-settings*) (loop for element in (elements seq) for pos = start-pos then curr-offset for curr-offset = (compute-offsets element pos) while curr-offset finally (return curr-offset))) (defmethod compute-offsets ((alternation alternation) start-pos) (declare #.*standard-optimize-settings*) (loop for choice in (choices alternation) for old-offset = nil then curr-offset for curr-offset = (compute-offsets choice start-pos) we stop immediately if two alternations do n't result in the if (or (not curr-offset) (and old-offset (/= curr-offset old-offset))) do (return nil) finally (return curr-offset))) (defmethod compute-offsets ((branch branch) start-pos) (declare #.*standard-optimize-settings*) (let ((then-offset (compute-offsets (then-regex branch) start-pos))) (and then-offset (eql then-offset (compute-offsets (else-regex branch) start-pos)) then-offset))) (defmethod compute-offsets ((repetition repetition) start-pos) (declare #.*standard-optimize-settings*) (with-slots (len minimum maximum) repetition (if (and len (eq minimum maximum)) (+ start-pos (* minimum len)) nil))) (defmethod compute-offsets ((register register) start-pos) (declare #.*standard-optimize-settings*) (compute-offsets (regex register) start-pos)) (defmethod compute-offsets ((standalone standalone) start-pos) (declare #.*standard-optimize-settings*) (compute-offsets (regex standalone) start-pos)) (defmethod compute-offsets ((char-class char-class) start-pos) (declare #.*standard-optimize-settings*) (1+ start-pos)) (defmethod compute-offsets ((everything everything) start-pos) (declare #.*standard-optimize-settings*) (1+ start-pos)) (defmethod compute-offsets ((str str) start-pos) (declare #.*standard-optimize-settings*) (setf (offset str) start-pos) (+ start-pos (len str))) (defmethod compute-offsets ((back-reference back-reference) start-pos) (declare #.*standard-optimize-settings*) (declare (ignore start-pos)) nil) (defmethod compute-offsets ((filter filter) start-pos) (declare #.*standard-optimize-settings*) (let ((len (len filter))) (if len (+ start-pos len) nil))) (defmethod compute-offsets ((regex regex) start-pos) (declare #.*standard-optimize-settings*) WORD - BOUNDARY ( which all have zero - length ) start-pos)
5c7656d490ea904077dbbda6dd1159ecf094c45ab3c8dc7ab08010973066cd27
WorksHub/client
db.cljs
(ns wh.logged-in.personalised-jobs.db)
null
https://raw.githubusercontent.com/WorksHub/client/a51729585c2b9d7692e57b3edcd5217c228cf47c/client/src/wh/logged_in/personalised_jobs/db.cljs
clojure
(ns wh.logged-in.personalised-jobs.db)
343e0eb7d055422f9a553dca4163d6d5f48e62f05f26e8489c8e306af81012a4
haskell-mafia/projector
Check.hs
# LANGUAGE CPP # # LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TupleSections # module Projector.Core.Check ( -- * Interface TypeError (..) , typeCheckIncremental , typeCheckAll , typeCheck , typeTree -- * Guts , generateConstraints , solveConstraints , Substitutions (..) ) where import Control.Monad.ST (ST, runST) import Control.Monad.Trans.Class (MonadTrans(..)) import Control.Monad.Trans.State.Strict (State, StateT, evalStateT, runState, runStateT, get, gets, modify', put) import Data.Char (chr, ord) import Data.DList (DList) import qualified Data.DList as D import qualified Data.List as L import Data.Map.Strict (Map) import qualified Data.Map.Strict as M #if MIN_VERSION_containers(0, 5, 9) import qualified Data.Map.Merge.Strict as M #else import qualified Data.Map.Strict.Merge as M #endif import qualified Data.Set as S import Data.STRef (STRef) import qualified Data.STRef as ST import qualified Data.Text as T import qualified Data.UnionFind.ST as UF import P import Projector.Core.Syntax import Projector.Core.Type import X.Control.Monad.Trans.Either (EitherT, left, runEitherT) import qualified X.Control.Monad.Trans.Either as ET data TypeError l a = UnificationError (Type l, a) (Type l, a) | FreeVariable Name a | UndeclaredType TypeName a | BadConstructorName Constructor TypeName (Decl l) a | BadConstructorArity Constructor Int Int a | BadPatternArity Constructor (Type l) Int Int a | BadPatternConstructor Constructor a | MissingRecordField TypeName FieldName (Type l, a) a | ExtraRecordField TypeName FieldName (Type l, a) a | DuplicateRecordFields TypeName [FieldName] a | InferenceError a | TypeHole (Type l, a) a | RecordInferenceError [(FieldName, Type l)] a | InfiniteType (Type l, a) (Type l, a) | Annotated a (TypeError l a) deriving instance (Ground l, Eq a) => Eq (TypeError l a) deriving instance (Ground l, Show a) => Show (TypeError l a) deriving instance (Ground l, Ord a) => Ord (TypeError l a) -- | Like 'typeCheckAll', but accepting a map of expressions of known -- type. This is appropriate for use in a left fold for incremental -- (dependency-ordered) typechecking. typeCheckIncremental :: Ground l => TypeDecls l -> Map Name (Type l, a) -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckIncremental decls known exprs = typeCheckAll' decls (fmap (\(t,a) -> hoistType decls a t) known) exprs | an interdependent set of named expressions . -- This is essentially top-level letrec. -- -- TODO: This admits general recursion. We need to write a totality checker. -- -- We cannot cache the intermediate results here, so we need to -- recheck everything each time. To support incremental builds we need -- to group expressions into "modules", figure out the module dependency DAG , and traverse only the dirty subtrees of that DAG . typeCheckAll :: Ground l => TypeDecls l -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckAll decls exprs = typeCheckAll' decls mempty exprs typeCheckAll' :: forall l a . Ground l => TypeDecls l -> Map Name (IType l a) -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckAll' decls known exprs = do -- for each declaration, generate constraints and assumptions (annotated, sstate) <- runCheck (sequenceCheck (fmap (generateConstraints' decls) exprs)) -- build up new global set of constraints from the assumptions let -- the inferred types (thus far) for our exprs exprTypes :: Map Name (IType l a) exprTypes = fmap extractType annotated -- constraints we figured out in generateConstraints localConstraints :: DList (Constraint l a) localConstraints = sConstraints sstate -- constraints provided by the user in type signatures -- FIXME these should be ImplicitInstance constraints (so 'a' matches 'Int', etc) userConstraints :: DList (Constraint l a) userConstraints = D.fromList . M.elems $ M.merge M.dropMissing M.dropMissing (M.zipWithMatched (const (Equal Nothing))) known exprTypes -- assumptions we made about free variables assums :: Map Name [(a, IType l a)] Assumptions assums = sAssumptions sstate -- types biased towards 'known' over 'inferred', since they may be user constraints types :: Map Name (IType l a) types = known <> exprTypes -- constraints for free variables we know stuff about globalConstraints :: DList (Constraint l a) globalConstraints = D.fromList . fold . M.elems . flip M.mapWithKey assums $ \n itys -> maybe mempty (with itys . (\global (a, ty) -> ExplicitInstance (Just a) global ty)) (M.lookup n types) -- all the constraints mashed together in a dlist constraints :: [Constraint l a] constraints = D.toList (localConstraints <> userConstraints <> globalConstraints) -- all variables let-bound bound :: S.Set Name bound = S.fromList (M.keys known <> M.keys exprs) -- all variables we have lingering assumptions about used :: S.Set Name used = S.fromList (M.keys (M.filter (not . null) assums)) -- all mystery free variables free :: S.Set Name free = used `S.difference` bound -- annotating mystery free variables with location info freeAt :: [(Name, a)] freeAt = foldMap (\n -> maybe [] (fmap ((n,) . fst)) (M.lookup n assums)) (toList free) -- throw errors for any undefined variables if free == mempty then pure () else Left (fmap (uncurry FreeVariable) freeAt) -- solve all our constraints at once subs <- solveConstraints constraints -- substitute solved types, all at once let subbed = fmap (substitute subs) annotated lower them from IType into Type , all at once first D.toList (ET.sequenceEither (fmap lowerExpr subbed)) typeCheck :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Type l) typeCheck decls = fmap extractType . typeTree decls typeTree :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Expr l (Type l, a)) typeTree decls expr = do (expr', constraints, Assumptions assums) <- generateConstraints decls expr -- Any unresolved assumptions are from free variables if M.keys (M.filter (not . null) assums) == mempty then pure () else Left (foldMap (\(n, itys) -> fmap (FreeVariable n . fst) itys) (M.toList assums)) subs <- solveConstraints constraints let subbed = substitute subs expr' first D.toList (lowerExpr subbed) -- ----------------------------------------------------------------------------- -- Types -- Unification variables. -- These can come from the constraint set or the solver, -- and I don't really want to thread a name supply around between them. data Var = C {-# UNPACK #-} !Int | S {-# UNPACK #-} !Int deriving (Eq, Ord, Show) -- | We have an internal notion of type inside the checker. -- Looks a bit like regular types, extended with unification variables. data IType l a = IDunno a Var | IHole a Var (Maybe (IType l a)) | IVar a TypeName -- maybe remove? | ILit a l | IArrow a (IType l a) (IType l a) | IClosedRecord a TypeName (Fields l a) | IOpenRecord a Var (Fields l a) | IList a (IType l a) | IForall a [TypeName] (IType l a) | IApp a (IType l a) (IType l a) deriving (Eq, Ord, Show) newtype Fields l a = Fields { _unFields :: Map FieldName (IType l a) } deriving (Eq, Ord, Show) field :: FieldName -> IType l a -> Fields l a field fn ty = Fields (M.fromList [(fn, ty)]) | Lift a known type into an ' IType ' , with an annotation . hoistType :: Ground l => TypeDecls l -> a -> Type l -> IType l a hoistType decls a (Type ty) = case ty of TLitF l -> ILit a l TVarF tn -> case lookupType tn decls of Just (DVariant _ps _cns) -> IVar a tn Just (DRecord _ps fts) -> -- FIXME hmmmm what should happen here IClosedRecord a tn (hoistFields decls a fts) Nothing -> -- 'a' or an unknown type. FIXME should be threading type bindings around so we know can handle bindings properly -- in practice not a big deal unless you're doing Forall [TypeName "List"] or something IVar a tn TArrowF f g -> IArrow a (hoistType decls a f) (hoistType decls a g) TListF f -> IList a (hoistType decls a f) TForallF ps t -> IForall a ps (hoistType decls a t) TAppF f g -> IApp a (hoistType decls a f) (hoistType decls a g) hoistFields :: Ground l => TypeDecls l -> a -> [(FieldName, Type l)] -> Fields l a hoistFields decls a = Fields . M.fromList . fmap (fmap (hoistType decls a)) substFields :: Map TypeName (IType l a) -> Fields l a -> Fields l a substFields subs (Fields m) = Fields (fmap (subst subs) m) -- | Convert our internal type representation back to the concrete. lowerIType :: IType l a -> Either (TypeError l a) (Type l) lowerIType ity' = do (ty, (_, ms)) <- flip runStateT (0, mempty) (go ity') pure $ case M.elems ms of [] -> ty ps -> TForall ps ty where go ity = case ity of IDunno _ x -> do FIX this does n't do the right thing for nested foralls - need to figure out free variables first tv <- freeTVar x pure (TVar tv) IHole a _ Nothing -> lift $ Left (InferenceError a) IHole a _ (Just i) -> lift $ Left (TypeHole (flattenIType i) a) ILit _ l -> pure (TLit l) IVar _ tn -> pure (TVar tn) IArrow _ f g -> TArrow <$> go f <*> go g IClosedRecord _ tn _fs -> pure (TVar tn) IOpenRecord a _x (Fields fs) -> do fs' <- traverse (traverse go) (M.toList fs) lift $ Left (RecordInferenceError fs' a) IList _ f -> TList <$> go f IForall _ bs t -> TForall bs <$> go t IApp _ f g -> TApp <$> go f <*> go g freeTVar :: Var -> StateT (Int, Map Var TypeName) (Either (TypeError l a)) TypeName freeTVar x = do (y, m) <- get case M.lookup x m of Just tn -> pure tn Nothing -> do let tv = dunnoTypeVar (C y) put (y+1, M.insert x tv m) pure tv -- Produce concrete type name for a fresh variable. dunnoTypeVar :: Var -> TypeName dunnoTypeVar v = case v of C x -> dunnoTypeVar' "" x S x -> dunnoTypeVar' "s" x dunnoTypeVar' :: Text -> Int -> TypeName dunnoTypeVar' p x = let letter j = chr (ord 'a' + j) in case (x `mod` 26, x `div` 26) of (i, 0) -> TypeName (p <> T.pack [letter i]) (m, n) -> TypeName (p <> T.pack [letter m] <> renderIntegral n) -- Produce a regular type, concretising fresh variables. -- This is currently used for error reporting. flattenIType :: IType l a -> (Type l, a) flattenIType ity = ( flattenIType' ity , case ity of IDunno a _ -> a IHole a _ _ -> a ILit a _ -> a IVar a _ -> a IArrow a _ _ -> a IClosedRecord a _ _ -> a IOpenRecord a _ _ -> a IList a _ -> a IForall a _ _ -> a IApp a _ _ -> a) flattenIType' :: IType l a -> Type l flattenIType' ity = case ity of IDunno _ x -> TVar (dunnoTypeVar x) IHole _ x _ -> TVar (dunnoTypeVar x) IVar _ tn -> TVar tn ILit _ l -> TLit l IArrow _ f g -> TArrow (flattenIType' f) (flattenIType' g) IOpenRecord _ x _ -> TVar (dunnoTypeVar x) IClosedRecord _ tn _ -> TVar tn IList _ ty -> TList (flattenIType' ty) IForall _ ps t -> TForall ps (flattenIType' t) IApp _ f g -> TApp (flattenIType' f) (flattenIType' g) -- | Report a unification error. unificationError :: IType l a -> IType l a -> TypeError l a unificationError = UnificationError `on` flattenIType lowerExpr :: Expr l (IType l a, a) -> Either (DList (TypeError l a)) (Expr l (Type l, a)) lowerExpr = ET.sequenceEither . fmap (\(ity, a) -> fmap (,a) (first D.singleton (lowerIType ity))) typeVar :: IType l a -> Maybe Var typeVar ty = case ty of IDunno _ x -> pure x IOpenRecord _ x _ -> pure x -- FIXME do we need IHole here? _ -> Nothing -- ----------------------------------------------------------------------------- Monad stack -- | 'Check' permits multiple errors via 'EitherT', lexically-scoped state via ' ReaderT ' , and global accumulating state via ' State ' . newtype Check l a b = Check { unCheck :: EitherT (DList (TypeError l a)) (State (SolverState l a)) b } deriving (Functor, Applicative, Monad) runCheck :: Check l a b -> Either [TypeError l a] (b, SolverState l a) runCheck f = unCheck f & runEitherT & flip runState initialSolverState & \(e, st) -> fmap (,st) (first D.toList e) data SolverState l a = SolverState { sConstraints :: DList (Constraint l a) , sAssumptions :: Assumptions l a , sSupply :: NameSupply } deriving (Eq, Ord, Show) initialSolverState :: SolverState l a initialSolverState = SolverState { sConstraints = mempty , sAssumptions = mempty , sSupply = emptyNameSupply } newtype Assumptions l a = Assumptions { unAssumptions :: Map Name [(a, IType l a)] } deriving (Eq, Ord, Show, Monoid) throwError :: TypeError l a -> Check l a b throwError = Check . left . D.singleton sequenceCheck :: Traversable t => t (Check l a b) -> Check l a (t b) sequenceCheck = Check . ET.sequenceEitherT . fmap unCheck -- ----------------------------------------------------------------------------- -- Name supply -- | Supply of fresh unification variables. newtype NameSupply = NameSupply { nextVar :: Int } deriving (Eq, Ord, Show) emptyNameSupply :: NameSupply emptyNameSupply = NameSupply 0 nextUnificationVar :: Check l a Var nextUnificationVar = Check . lift $ do v <- gets (nextVar . sSupply) modify' (\s -> s { sSupply = NameSupply (v + 1) }) pure (C v) -- | Grab a fresh type variable. freshTypeVar :: a -> Check l a (IType l a) freshTypeVar a = IDunno a <$> nextUnificationVar freshTypeHole :: a -> Check l a (IType l a) freshTypeHole a = IHole a <$> nextUnificationVar <*> pure Nothing freshOpenRecord :: a -> Fields l a -> Check l a (IType l a) freshOpenRecord a fs = IOpenRecord a <$> nextUnificationVar <*> pure fs -- ----------------------------------------------------------------------------- -- Constraints data Constraint l a = Equal (Maybe a) (IType l a) (IType l a) | ExplicitInstance (Maybe a) (IType l a) (IType l a) deriving (Eq, Ord, Show) -- | Record a new constraint. addConstraint :: Constraint l a -> Check l a () addConstraint c = Check . lift $ modify' (\s -> s { sConstraints = D.cons c (sConstraints s) }) -- ----------------------------------------------------------------------------- -- Assumptions -- | Add an assumed type for some variable we've encountered. addAssumption :: Name -> a -> IType l a -> Check l a () addAssumption n a ty = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.insertWith (<>) n [(a, ty)] (unAssumptions (sAssumptions s))) }) -- | Clobber the assumption set for some variable. setAssumptions :: Name -> [(a, IType l a)] -> Check l a () setAssumptions n assums = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.insert n assums (unAssumptions (sAssumptions s))) }) -- | Delete all assumptions for some variable. -- -- This is called when leaving the lexical scope in which the variable was bound. deleteAssumptions :: Name -> Check l a () deleteAssumptions n = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.delete n (unAssumptions (sAssumptions s))) }) -- | Look up all assumptions for a given name. Returns the empty set if there are none. lookupAssumptions :: Name -> Check l a [(a, IType l a)] lookupAssumptions n = Check . lift $ fmap (fromMaybe mempty) (gets (M.lookup n . unAssumptions . sAssumptions)) -- | Run some continuation with lexically-scoped assumptions. -- This is sorta like 'local', but we need to keep changes to other keys in the map. withBindings :: Traversable f => f Name -> Check l a b -> Check l a (Map Name [(a, IType l a)], b) withBindings xs k = do old <- fmap (M.fromList . toList) . for xs $ \n -> do as <- lookupAssumptions n deleteAssumptions n pure (n, as) res <- k new <- fmap (M.fromList . toList) . for xs $ \n -> do as <- lookupAssumptions n setAssumptions n (fromMaybe mempty (M.lookup n old)) pure (n, as) pure (new, res) withBinding :: Name -> Check l a b -> Check l a ([(a, IType l a)], b) withBinding x k = do (as, b) <- withBindings [x] k pure (fromMaybe mempty (M.lookup x as), b) -- ----------------------------------------------------------------------------- Constraint generation generateConstraints :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Expr l (IType l a, a), [Constraint l a], Assumptions l a) generateConstraints decls expr = do (e, st) <- runCheck (generateConstraints' decls expr) pure (e, D.toList (sConstraints st), sAssumptions st) generateConstraints' :: Ground l => TypeDecls l -> Expr l a -> Check l a (Expr l (IType l a, a)) generateConstraints' decls expr = case expr of ELit a v -> -- We know the type of literals instantly. let ty = TLit (typeOf v) in pure (ELit (hoistType decls a ty, a) v) EVar a v -> do -- We introduce a new type variable representing the type of this expression. -- Add it to the assumption set. t <- freshTypeVar a addAssumption v a t pure (EVar (t, a) v) ELam a n mta e -> do -- Proceed bottom-up, generating constraints for 'e'. -- Gather the assumed types of 'n', and constrain them to be the known (annotated) type. -- This expression's type is an arrow from the known type to the inferred type of 'e'. (as, e') <- withBinding n (generateConstraints' decls e) ta <- maybe (freshTypeVar a) (pure . hoistType decls a) mta for_ (fmap snd as) (addConstraint . Equal (Just a) ta) let ty = IArrow a ta (extractType e') pure (ELam (ty, a) n mta e') EApp a f g -> do -- Proceed bottom-up, generating constraints for 'f' and 'g'. -- Introduce a new type variable for the result of the expression. -- Constrain 'f' to be an arrow from the type of 'g' to this type. f' <- generateConstraints' decls f g' <- generateConstraints' decls g t <- freshTypeVar a addConstraint (ExplicitInstance (Just a) (IArrow a (extractType g') t) (extractType f')) pure (EApp (t, a) f' g') EList a es -> do -- Proceed bottom-up, inferring types for each expression in the list. -- Constrain each type to be the annotated 'ty'. es' <- for es (generateConstraints' decls) te <- freshTypeVar a for_ es' (addConstraint . Equal (Just a) te . extractType) let ty = IList a te pure (EList (ty, a) es') EMap a f g -> do -- Special case polymorphic map. g must be List a, f must be (a -> b) f' <- generateConstraints' decls f g' <- generateConstraints' decls g ta <- freshTypeVar a tb <- freshTypeVar a addConstraint (Equal (Just a) (IArrow a ta tb) (extractType f')) addConstraint (Equal (Just a) (IList a ta) (extractType g')) let ty = IList a tb pure (EMap (ty, a) f' g') ECon a c tn es -> case lookupType tn decls of Just ty@(DVariant ps cns) -> do -- Look up the constructor, check its arity, and introduce -- constraints for each of its subterms, for which we expect certain types. ts <- maybe (throwError (BadConstructorName c tn ty a)) pure (L.lookup c cns) unless (length ts == length es) (throwError (BadConstructorArity c (length ts) (length es) a)) -- Generate fresh type variables for each type parameter ps' <- for ps (\p -> (p,) <$> freshTypeVar a) -- Put them in a map so we can substitute let typeParams = M.fromList ps' -- Generate constraints for each subexpression es' <- for es (generateConstraints' decls) for_ (L.zip (fmap (hoistType decls a) ts) (fmap extractType es')) -- Add constraints linking subexpression inferred types to the type definition ( Substitute the type parameters for instantiated versions first ) (\(expected, inferred) -> addConstraint (Equal (Just a) (subst typeParams expected) inferred)) let ty' = foldl' (IApp a) (IVar a tn) (fmap snd ps') pure (ECon (ty', a) c tn es') Records should be constructed via ERec , not ECon Just ty@(DRecord _ _) -> do throwError (BadConstructorName c tn ty a) Nothing -> throwError (UndeclaredType tn a) ECase a e pes -> do -- The body of the case expression should be the same type for each branch. -- We introduce a new unification variable for that type. -- Patterns introduce new constraints and bindings, managed in 'patternConstraints'. e' <- generateConstraints' decls e ty <- freshTypeVar a pes' <- for pes $ \(pat, pe) -> do let bnds = patternBinds pat (_, res) <- withBindings (S.toList bnds) $ do -- Order matters here, patCons consumes the assumptions from genCons. pe' <- generateConstraints' decls pe pat' <- patternConstraints decls (extractType e') pat addConstraint (Equal (Just a) ty (extractType pe')) pure (pat', pe') pure res pure (ECase (ty, a) e' pes') ERec a tn fes -> do case lookupType tn decls of Just (DRecord ps fts) -> do -- Generate fresh type variables for each type parameter ps' <- for ps (\p -> (p,) <$> freshTypeVar a) -- Put them in a map so we can substitute let typeParams = M.fromList ps' -- recurse into each field fes' <- traverse (traverse (generateConstraints' decls)) fes let need = M.fromList (fmap (fmap (hoistType decls a)) fts) have = M.fromList (fmap (fmap extractType) fes') _ <- M.mergeA -- What to do when a required field is missing (M.traverseMissing (\fn ty -> throwError (MissingRecordField tn fn (flattenIType ty) a))) -- When an extraneous field is present (M.traverseMissing (\fn ty -> throwError (ExtraRecordField tn fn (flattenIType ty) a))) -- When present in both, add a constraint (M.zipWithAMatched (\_fn twant thave -> addConstraint (Equal (Just a) (subst typeParams twant) thave))) need have -- catch duplicate fields too when (length fes /= length fts) $ throwError (DuplicateRecordFields tn (fmap fst fes L.\\ fmap fst fts) a) -- set type as the closed record let ty' = foldl' (IApp a) (IClosedRecord a tn (substFields typeParams (hoistFields decls a fts))) (fmap snd ps') pure (ERec (ty', a) tn fes') Variants should be constructed via ECon , not Just ty@(DVariant _ _) -> do throwError (BadConstructorName (Constructor (unTypeName tn)) tn ty a) Nothing -> throwError (UndeclaredType tn a) EPrj a e fn -> do e' <- generateConstraints' decls e tp <- freshTypeVar a rt <- freshOpenRecord a (field fn tp) addConstraint (Equal (Just a) rt (extractType e')) pure (EPrj (tp, a) e' fn) EForeign a n ty -> do -- We know the type of foreign expressions immediately, because they're annotated. pure (EForeign (hoistType decls a ty, a) n ty) EHole a -> do ty <- freshTypeHole a pure (EHole (ty, a)) -- | Patterns are binding sites that also introduce lots of new constraints. patternConstraints :: Ground l => TypeDecls l -> IType l a -> Pattern a -> Check l a (Pattern (IType l a, a)) patternConstraints decls ty pat = case pat of PVar a x -> do as <- lookupAssumptions x for_ (fmap snd as) (addConstraint . Equal (Just a) ty) pure (PVar (ty, a) x) PCon a c pats -> case lookupConstructor c decls of Just (tn, ps, ts) -> do unless (length ts == length pats) (throwError (BadPatternArity c (TVar tn) (length ts) (length pats) a)) ps' <- for ps (\p -> (p,) <$> freshTypeVar a) let ty' = foldl' (IApp a) (hoistType decls a (TVar tn)) (fmap snd ps') typeParams = M.fromList ps' pats' <- for (L.zip (fmap (hoistType decls a) ts) pats) $ \(ty2, pat2) -> patternConstraints decls (subst typeParams ty2) pat2 addConstraint (Equal (Just a) ty' (subst typeParams ty)) pure (PCon (ty', a) c pats') Nothing -> throwError (BadPatternConstructor c a) PWildcard a -> pure (PWildcard (ty, a)) extractType :: Expr l (c, a) -> c extractType = fst . extractAnnotation -- ----------------------------------------------------------------------------- Constraint solving newtype Substitutions l a = Substitutions { unSubstitutions :: Map Var (IType l a) } deriving (Eq, Ord, Show) substitute :: Ground l => Substitutions l a -> Expr l (IType l a, a) -> Expr l (IType l a, a) substitute subs expr = with expr $ \(ty, a) -> (substituteType subs True ty, a) substituteType :: Ground l => Substitutions l a -> Bool -> IType l a -> IType l a substituteType subs top ty = case ty of IDunno _ x -> maybe ty (substituteType subs False) (M.lookup x (unSubstitutions subs)) IHole a x _ -> maybe ty (\sty -> let res = substituteType subs False sty in if top then IHole a x (Just res) else res) (M.lookup x (unSubstitutions subs)) IArrow a t1 t2 -> IArrow a (substituteType subs False t1) (substituteType subs False t2) IApp a t1 t2 -> IApp a (substituteType subs False t1) (substituteType subs False t2) IList a t -> IList a (substituteType subs False t) IOpenRecord _ x _ -> maybe ty (substituteType subs False) (M.lookup x (unSubstitutions subs)) IForall a bs t -> IForall a bs (substituteType subs False t) IClosedRecord _ _ _ -> ty ILit _ _ -> ty IVar _ _ -> ty # INLINE substituteType # newtype Points s l a = Points { unPoints :: Map Var (UF.Point s (IType l a)) } mostGeneralUnifierST :: Ground l => STRef s (Points s l a) -> IType l a -> IType l a -> ST s (Either [TypeError l a] ()) mostGeneralUnifierST points t1 t2 = runEitherT (void (mguST points t1 t2)) mguST :: Ground l => STRef s (Points s l a) -> IType l a -> IType l a -> EitherT [TypeError l a] (ST s) (IType l a) mguST points t1 t2 = case (t1, t2) of (IDunno a x, _) -> do unifyVar points a x t2 (_, IDunno a x) -> do unifyVar points a x t1 (IHole a x _, _) -> do unifyVar points a x t2 (_, IHole a x _) -> do unifyVar points a x t1 (IOpenRecord a x fs, IOpenRecord b y gs) -> do hs <- unifyOpenFields points fs gs unifyVar points a x (IOpenRecord b y hs) (IOpenRecord a x fs, IClosedRecord _ tn gs) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t2 (IOpenRecord a x fs, IApp _ (IClosedRecord _ tn gs) _) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t2 (IClosedRecord _ tn gs, IOpenRecord a x fs) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t1 (IClosedRecord _ x _fs1, IClosedRecord _ y _fs2) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (IVar _ x, IVar _ y) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (ILit _ x, ILit _ y) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (IArrow a f g, IArrow _ h i) -> do -- Would be nice to have an applicative newtype for this... [j, k] <- ET.sequenceEitherT [mguST points f h, mguST points g i] pure (IArrow a j k) (IApp a f g, IApp _ h i) -> do [j, k] <- ET.sequenceEitherT [mguST points f h, mguST points g i] pure (IApp a j k) (IList k a, IList _ b) -> do c <- mguST points a b pure (IList k c) (IForall a ts1 ot1, IForall b ts2 ot2) -> case (normalise a ts1 ot1, normalise b ts2 ot2) of (IForall _ ps1 tt1, IForall _ ps2 tt2) -> do unless (ps1 == ps2) (left [unificationError t1 t2]) c <- mguST points tt1 tt2 pure (IForall a ps1 c) (tt1, tt2) -> left [unificationError tt1 tt2] (_, _) -> left [unificationError t1 t2] unifyVar :: Ground l => STRef s (Points s l a) -> a -> Var -> IType l a -> EitherT [TypeError l a] (ST s) (IType l a) unifyVar points a x t2 = do mt1 <- lift (getRepr points x) let safeUnion c z u2 = do unless (typeVar u2 == Just z) (ET.hoistEither (occurs c z u2) *> lift (union points (IDunno c z) u2)) pure u2 case mt1 of -- special case if the var is its class representative Just t1@(IDunno b y) -> if x == y then firstT pure (safeUnion b y t2) else mguST points t1 t2 Just t1 -> mguST points t1 t2 Nothing -> firstT pure (safeUnion a x t2) -- | Check that a given unification variable isn't present inside the -- type it's being unified with. This is necessary for typechecking -- to be sound, it prevents us from constructing the infinite type. occurs :: a -> Var -> IType l a -> Either (TypeError l a) () occurs a q ity = go q ity where go x i = case i of IDunno _ y -> when (x == y) (Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity))) IHole _ y _ -> when (x == y) (Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity))) IVar _ _ -> pure () ILit _ _ -> pure () IArrow _ f g -> go x f *> go x g IApp _ f g -> go x f *> go x g IClosedRecord _ _ (Fields fs) -> traverse_ (go x) fs IOpenRecord _ y (Fields fs) -> if x == y then Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity)) else traverse_ (go x) fs IList _ f -> go x f IForall _ _ t -> go x t # INLINE occurs # unifyOpenFields :: Ground l => STRef s (Points s l a) -> Fields l a -> Fields l a -> EitherT [TypeError l a] (ST s) (Fields l a) unifyOpenFields points (Fields fs1) (Fields fs2) = do fmap Fields . ET.sequenceEitherT $ M.merge -- missing fields either side just get propagated (M.mapMissing (const (firstT pure . pure))) (M.mapMissing (const (firstT pure . pure))) -- unify any matching fields normally (M.zipWithMatched (\_fn t1 t2 -> mguST points t1 t2)) fs1 fs2 unifyClosedFields :: Ground l => STRef s (Points s l a) -> Fields l a -> TypeName -> Fields l a -> EitherT [TypeError l a] (ST s) (Fields l a) unifyClosedFields points (Fields have) tn (Fields want) = do fmap Fields . ET.sequenceEitherT $ M.merge -- invocation order really matters here -- extra fields in 'have' are very bad (M.mapMissing (\fn t1 -> left [ExtraRecordField tn fn (flattenIType t1) (snd (flattenIType t1))])) -- extra fields in 'want' are to be expected (M.mapMissing (const (firstT pure . pure))) -- unify all the other fields (M.zipWithMatched (\_fn t1 t2 -> mguST points t1 t2)) have want solveConstraints :: Ground l => Traversable f => f (Constraint l a) -> Either [TypeError l a] (Substitutions l a) solveConstraints constraints = runST $ flip evalStateT (NameSupply 0) $ do Initialise mutable state . points <- lift $ ST.newSTRef (Points M.empty) let mgu ma t1 t2 = fmap (first (D.fromList . fmap (maybe id Annotated ma))) (lift $ mostGeneralUnifierST points t1 t2) -- Solve all the constraints independently. es <- fmap ET.sequenceEither . for constraints $ \c -> case c of Equal ma t1 t2 -> mgu ma t1 t2 ExplicitInstance ma want have -> do inst1 <- instantiate want inst2 <- instantiate have mgu ma inst1 inst2 -- Retrieve the remaining points and produce a substitution map solvedPoints <- lift $ ST.readSTRef points lift . for (first D.toList es) $ \_ -> do substitutionMap solvedPoints instantiate :: (Monad m) => IType l a -> StateT NameSupply m (IType l a) instantiate ty = case ty of IForall a vars ity -> do bnds <- traverse (fmap (IDunno a) . const nextSVar) (M.fromList (fmap (\v -> (v, ())) vars)) pure (subst bnds ity) _ -> pure ty normalise :: a -> [TypeName] -> IType l a -> IType l a normalise a ps t = let vars = with [0..length ps] (dunnoTypeVar' "") bnds = M.fromList $ with (L.zip ps vars) (\(n, x) -> (n, IVar a x)) in IForall a vars (subst bnds t) subst :: Map TypeName (IType l a) -> IType l a -> IType l a subst bnds' ty' | null bnds' = ty' | otherwise = go bnds' ty' where go bnds ity = case ity of IVar _a tn -> fromMaybe ity (M.lookup tn bnds) IForall a bs t -> IForall a bs (go (foldl' (flip M.delete) bnds bs) t) IArrow a t1 t2 -> IArrow a (go bnds t1) (go bnds t2) IApp a t1 t2 -> IApp a (go bnds t1) (go bnds t2) IList a t1 -> IList a (go bnds t1) IHole a x mty -> IHole a x (fmap (go bnds) mty) ILit _ _ -> ity IDunno _ _ -> ity IClosedRecord _ _ _ -> ity -- FIXME not sure about this one IOpenRecord _ _ _ -> ity nextSVar :: Monad m => StateT NameSupply m Var nextSVar = do NameSupply x <- get put (NameSupply (x + 1)) pure (S x) substitutionMap :: Points s l a -> ST s (Substitutions l a) substitutionMap points = do subs <- for (unPoints points) (UF.descriptor <=< UF.repr) pure (Substitutions (M.filterWithKey (\k v -> case v of IDunno _ x -> k /= x; _ -> True) subs)) union :: STRef s (Points s l a) -> IType l a -> IType l a -> ST s () union points t1 t2 = do p1 <- getPoint points t1 p2 <- getPoint points t2 UF.union p1 p2 -- | Fills the 'lookup' API hole in the union-find package. getPoint :: STRef s (Points s l a) -> IType l a -> ST s (UF.Point s (IType l a)) getPoint mref ty = case ty of IDunno _ x -> do ps <- ST.readSTRef mref case M.lookup x (unPoints ps) of Just point -> pure point Nothing -> do point <- UF.fresh ty ST.modifySTRef' mref (Points . M.insert x point . unPoints) pure point -- TODO maybe this is a bad idea... _ -> UF.fresh ty # INLINE getPoint # getRepr :: STRef s (Points s l a) -> Var -> ST s (Maybe (IType l a)) getRepr points x = do ps <- ST.readSTRef points for (M.lookup x (unPoints ps)) (UF.descriptor <=< UF.repr)
null
https://raw.githubusercontent.com/haskell-mafia/projector/6af7c7f1e8a428b14c2c5a508f7d4a3ac2decd52/projector-core/src/Projector/Core/Check.hs
haskell
# LANGUAGE DeriveTraversable # # LANGUAGE OverloadedStrings # * Interface * Guts | Like 'typeCheckAll', but accepting a map of expressions of known type. This is appropriate for use in a left fold for incremental (dependency-ordered) typechecking. This is essentially top-level letrec. TODO: This admits general recursion. We need to write a totality checker. We cannot cache the intermediate results here, so we need to recheck everything each time. To support incremental builds we need to group expressions into "modules", figure out the module for each declaration, generate constraints and assumptions build up new global set of constraints from the assumptions the inferred types (thus far) for our exprs constraints we figured out in generateConstraints constraints provided by the user in type signatures FIXME these should be ImplicitInstance constraints (so 'a' matches 'Int', etc) assumptions we made about free variables types biased towards 'known' over 'inferred', since they may be user constraints constraints for free variables we know stuff about all the constraints mashed together in a dlist all variables let-bound all variables we have lingering assumptions about all mystery free variables annotating mystery free variables with location info throw errors for any undefined variables solve all our constraints at once substitute solved types, all at once Any unresolved assumptions are from free variables ----------------------------------------------------------------------------- Types Unification variables. These can come from the constraint set or the solver, and I don't really want to thread a name supply around between them. # UNPACK # # UNPACK # | We have an internal notion of type inside the checker. Looks a bit like regular types, extended with unification variables. maybe remove? FIXME hmmmm what should happen here 'a' or an unknown type. in practice not a big deal unless you're doing Forall [TypeName "List"] or something | Convert our internal type representation back to the concrete. Produce concrete type name for a fresh variable. Produce a regular type, concretising fresh variables. This is currently used for error reporting. | Report a unification error. FIXME do we need IHole here? ----------------------------------------------------------------------------- | 'Check' permits multiple errors via 'EitherT', lexically-scoped ----------------------------------------------------------------------------- Name supply | Supply of fresh unification variables. | Grab a fresh type variable. ----------------------------------------------------------------------------- Constraints | Record a new constraint. ----------------------------------------------------------------------------- Assumptions | Add an assumed type for some variable we've encountered. | Clobber the assumption set for some variable. | Delete all assumptions for some variable. This is called when leaving the lexical scope in which the variable was bound. | Look up all assumptions for a given name. Returns the empty set if there are none. | Run some continuation with lexically-scoped assumptions. This is sorta like 'local', but we need to keep changes to other keys in the map. ----------------------------------------------------------------------------- We know the type of literals instantly. We introduce a new type variable representing the type of this expression. Add it to the assumption set. Proceed bottom-up, generating constraints for 'e'. Gather the assumed types of 'n', and constrain them to be the known (annotated) type. This expression's type is an arrow from the known type to the inferred type of 'e'. Proceed bottom-up, generating constraints for 'f' and 'g'. Introduce a new type variable for the result of the expression. Constrain 'f' to be an arrow from the type of 'g' to this type. Proceed bottom-up, inferring types for each expression in the list. Constrain each type to be the annotated 'ty'. Special case polymorphic map. g must be List a, f must be (a -> b) Look up the constructor, check its arity, and introduce constraints for each of its subterms, for which we expect certain types. Generate fresh type variables for each type parameter Put them in a map so we can substitute Generate constraints for each subexpression Add constraints linking subexpression inferred types to the type definition The body of the case expression should be the same type for each branch. We introduce a new unification variable for that type. Patterns introduce new constraints and bindings, managed in 'patternConstraints'. Order matters here, patCons consumes the assumptions from genCons. Generate fresh type variables for each type parameter Put them in a map so we can substitute recurse into each field What to do when a required field is missing When an extraneous field is present When present in both, add a constraint catch duplicate fields too set type as the closed record We know the type of foreign expressions immediately, because they're annotated. | Patterns are binding sites that also introduce lots of new constraints. ----------------------------------------------------------------------------- Would be nice to have an applicative newtype for this... special case if the var is its class representative | Check that a given unification variable isn't present inside the type it's being unified with. This is necessary for typechecking to be sound, it prevents us from constructing the infinite type. missing fields either side just get propagated unify any matching fields normally invocation order really matters here extra fields in 'have' are very bad extra fields in 'want' are to be expected unify all the other fields Solve all the constraints independently. Retrieve the remaining points and produce a substitution map FIXME not sure about this one | Fills the 'lookup' API hole in the union-find package. TODO maybe this is a bad idea...
# LANGUAGE CPP # # LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TupleSections # module Projector.Core.Check ( TypeError (..) , typeCheckIncremental , typeCheckAll , typeCheck , typeTree , generateConstraints , solveConstraints , Substitutions (..) ) where import Control.Monad.ST (ST, runST) import Control.Monad.Trans.Class (MonadTrans(..)) import Control.Monad.Trans.State.Strict (State, StateT, evalStateT, runState, runStateT, get, gets, modify', put) import Data.Char (chr, ord) import Data.DList (DList) import qualified Data.DList as D import qualified Data.List as L import Data.Map.Strict (Map) import qualified Data.Map.Strict as M #if MIN_VERSION_containers(0, 5, 9) import qualified Data.Map.Merge.Strict as M #else import qualified Data.Map.Strict.Merge as M #endif import qualified Data.Set as S import Data.STRef (STRef) import qualified Data.STRef as ST import qualified Data.Text as T import qualified Data.UnionFind.ST as UF import P import Projector.Core.Syntax import Projector.Core.Type import X.Control.Monad.Trans.Either (EitherT, left, runEitherT) import qualified X.Control.Monad.Trans.Either as ET data TypeError l a = UnificationError (Type l, a) (Type l, a) | FreeVariable Name a | UndeclaredType TypeName a | BadConstructorName Constructor TypeName (Decl l) a | BadConstructorArity Constructor Int Int a | BadPatternArity Constructor (Type l) Int Int a | BadPatternConstructor Constructor a | MissingRecordField TypeName FieldName (Type l, a) a | ExtraRecordField TypeName FieldName (Type l, a) a | DuplicateRecordFields TypeName [FieldName] a | InferenceError a | TypeHole (Type l, a) a | RecordInferenceError [(FieldName, Type l)] a | InfiniteType (Type l, a) (Type l, a) | Annotated a (TypeError l a) deriving instance (Ground l, Eq a) => Eq (TypeError l a) deriving instance (Ground l, Show a) => Show (TypeError l a) deriving instance (Ground l, Ord a) => Ord (TypeError l a) typeCheckIncremental :: Ground l => TypeDecls l -> Map Name (Type l, a) -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckIncremental decls known exprs = typeCheckAll' decls (fmap (\(t,a) -> hoistType decls a t) known) exprs | an interdependent set of named expressions . dependency DAG , and traverse only the dirty subtrees of that DAG . typeCheckAll :: Ground l => TypeDecls l -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckAll decls exprs = typeCheckAll' decls mempty exprs typeCheckAll' :: forall l a . Ground l => TypeDecls l -> Map Name (IType l a) -> Map Name (Expr l a) -> Either [TypeError l a] (Map Name (Expr l (Type l, a))) typeCheckAll' decls known exprs = do (annotated, sstate) <- runCheck (sequenceCheck (fmap (generateConstraints' decls) exprs)) exprTypes :: Map Name (IType l a) exprTypes = fmap extractType annotated localConstraints :: DList (Constraint l a) localConstraints = sConstraints sstate userConstraints :: DList (Constraint l a) userConstraints = D.fromList . M.elems $ M.merge M.dropMissing M.dropMissing (M.zipWithMatched (const (Equal Nothing))) known exprTypes assums :: Map Name [(a, IType l a)] Assumptions assums = sAssumptions sstate types :: Map Name (IType l a) types = known <> exprTypes globalConstraints :: DList (Constraint l a) globalConstraints = D.fromList . fold . M.elems . flip M.mapWithKey assums $ \n itys -> maybe mempty (with itys . (\global (a, ty) -> ExplicitInstance (Just a) global ty)) (M.lookup n types) constraints :: [Constraint l a] constraints = D.toList (localConstraints <> userConstraints <> globalConstraints) bound :: S.Set Name bound = S.fromList (M.keys known <> M.keys exprs) used :: S.Set Name used = S.fromList (M.keys (M.filter (not . null) assums)) free :: S.Set Name free = used `S.difference` bound freeAt :: [(Name, a)] freeAt = foldMap (\n -> maybe [] (fmap ((n,) . fst)) (M.lookup n assums)) (toList free) if free == mempty then pure () else Left (fmap (uncurry FreeVariable) freeAt) subs <- solveConstraints constraints let subbed = fmap (substitute subs) annotated lower them from IType into Type , all at once first D.toList (ET.sequenceEither (fmap lowerExpr subbed)) typeCheck :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Type l) typeCheck decls = fmap extractType . typeTree decls typeTree :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Expr l (Type l, a)) typeTree decls expr = do (expr', constraints, Assumptions assums) <- generateConstraints decls expr if M.keys (M.filter (not . null) assums) == mempty then pure () else Left (foldMap (\(n, itys) -> fmap (FreeVariable n . fst) itys) (M.toList assums)) subs <- solveConstraints constraints let subbed = substitute subs expr' first D.toList (lowerExpr subbed) data Var = deriving (Eq, Ord, Show) data IType l a = IDunno a Var | IHole a Var (Maybe (IType l a)) | ILit a l | IArrow a (IType l a) (IType l a) | IClosedRecord a TypeName (Fields l a) | IOpenRecord a Var (Fields l a) | IList a (IType l a) | IForall a [TypeName] (IType l a) | IApp a (IType l a) (IType l a) deriving (Eq, Ord, Show) newtype Fields l a = Fields { _unFields :: Map FieldName (IType l a) } deriving (Eq, Ord, Show) field :: FieldName -> IType l a -> Fields l a field fn ty = Fields (M.fromList [(fn, ty)]) | Lift a known type into an ' IType ' , with an annotation . hoistType :: Ground l => TypeDecls l -> a -> Type l -> IType l a hoistType decls a (Type ty) = case ty of TLitF l -> ILit a l TVarF tn -> case lookupType tn decls of Just (DVariant _ps _cns) -> IVar a tn Just (DRecord _ps fts) -> IClosedRecord a tn (hoistFields decls a fts) Nothing -> FIXME should be threading type bindings around so we know can handle bindings properly IVar a tn TArrowF f g -> IArrow a (hoistType decls a f) (hoistType decls a g) TListF f -> IList a (hoistType decls a f) TForallF ps t -> IForall a ps (hoistType decls a t) TAppF f g -> IApp a (hoistType decls a f) (hoistType decls a g) hoistFields :: Ground l => TypeDecls l -> a -> [(FieldName, Type l)] -> Fields l a hoistFields decls a = Fields . M.fromList . fmap (fmap (hoistType decls a)) substFields :: Map TypeName (IType l a) -> Fields l a -> Fields l a substFields subs (Fields m) = Fields (fmap (subst subs) m) lowerIType :: IType l a -> Either (TypeError l a) (Type l) lowerIType ity' = do (ty, (_, ms)) <- flip runStateT (0, mempty) (go ity') pure $ case M.elems ms of [] -> ty ps -> TForall ps ty where go ity = case ity of IDunno _ x -> do FIX this does n't do the right thing for nested foralls - need to figure out free variables first tv <- freeTVar x pure (TVar tv) IHole a _ Nothing -> lift $ Left (InferenceError a) IHole a _ (Just i) -> lift $ Left (TypeHole (flattenIType i) a) ILit _ l -> pure (TLit l) IVar _ tn -> pure (TVar tn) IArrow _ f g -> TArrow <$> go f <*> go g IClosedRecord _ tn _fs -> pure (TVar tn) IOpenRecord a _x (Fields fs) -> do fs' <- traverse (traverse go) (M.toList fs) lift $ Left (RecordInferenceError fs' a) IList _ f -> TList <$> go f IForall _ bs t -> TForall bs <$> go t IApp _ f g -> TApp <$> go f <*> go g freeTVar :: Var -> StateT (Int, Map Var TypeName) (Either (TypeError l a)) TypeName freeTVar x = do (y, m) <- get case M.lookup x m of Just tn -> pure tn Nothing -> do let tv = dunnoTypeVar (C y) put (y+1, M.insert x tv m) pure tv dunnoTypeVar :: Var -> TypeName dunnoTypeVar v = case v of C x -> dunnoTypeVar' "" x S x -> dunnoTypeVar' "s" x dunnoTypeVar' :: Text -> Int -> TypeName dunnoTypeVar' p x = let letter j = chr (ord 'a' + j) in case (x `mod` 26, x `div` 26) of (i, 0) -> TypeName (p <> T.pack [letter i]) (m, n) -> TypeName (p <> T.pack [letter m] <> renderIntegral n) flattenIType :: IType l a -> (Type l, a) flattenIType ity = ( flattenIType' ity , case ity of IDunno a _ -> a IHole a _ _ -> a ILit a _ -> a IVar a _ -> a IArrow a _ _ -> a IClosedRecord a _ _ -> a IOpenRecord a _ _ -> a IList a _ -> a IForall a _ _ -> a IApp a _ _ -> a) flattenIType' :: IType l a -> Type l flattenIType' ity = case ity of IDunno _ x -> TVar (dunnoTypeVar x) IHole _ x _ -> TVar (dunnoTypeVar x) IVar _ tn -> TVar tn ILit _ l -> TLit l IArrow _ f g -> TArrow (flattenIType' f) (flattenIType' g) IOpenRecord _ x _ -> TVar (dunnoTypeVar x) IClosedRecord _ tn _ -> TVar tn IList _ ty -> TList (flattenIType' ty) IForall _ ps t -> TForall ps (flattenIType' t) IApp _ f g -> TApp (flattenIType' f) (flattenIType' g) unificationError :: IType l a -> IType l a -> TypeError l a unificationError = UnificationError `on` flattenIType lowerExpr :: Expr l (IType l a, a) -> Either (DList (TypeError l a)) (Expr l (Type l, a)) lowerExpr = ET.sequenceEither . fmap (\(ity, a) -> fmap (,a) (first D.singleton (lowerIType ity))) typeVar :: IType l a -> Maybe Var typeVar ty = case ty of IDunno _ x -> pure x IOpenRecord _ x _ -> pure x _ -> Nothing Monad stack state via ' ReaderT ' , and global accumulating state via ' State ' . newtype Check l a b = Check { unCheck :: EitherT (DList (TypeError l a)) (State (SolverState l a)) b } deriving (Functor, Applicative, Monad) runCheck :: Check l a b -> Either [TypeError l a] (b, SolverState l a) runCheck f = unCheck f & runEitherT & flip runState initialSolverState & \(e, st) -> fmap (,st) (first D.toList e) data SolverState l a = SolverState { sConstraints :: DList (Constraint l a) , sAssumptions :: Assumptions l a , sSupply :: NameSupply } deriving (Eq, Ord, Show) initialSolverState :: SolverState l a initialSolverState = SolverState { sConstraints = mempty , sAssumptions = mempty , sSupply = emptyNameSupply } newtype Assumptions l a = Assumptions { unAssumptions :: Map Name [(a, IType l a)] } deriving (Eq, Ord, Show, Monoid) throwError :: TypeError l a -> Check l a b throwError = Check . left . D.singleton sequenceCheck :: Traversable t => t (Check l a b) -> Check l a (t b) sequenceCheck = Check . ET.sequenceEitherT . fmap unCheck newtype NameSupply = NameSupply { nextVar :: Int } deriving (Eq, Ord, Show) emptyNameSupply :: NameSupply emptyNameSupply = NameSupply 0 nextUnificationVar :: Check l a Var nextUnificationVar = Check . lift $ do v <- gets (nextVar . sSupply) modify' (\s -> s { sSupply = NameSupply (v + 1) }) pure (C v) freshTypeVar :: a -> Check l a (IType l a) freshTypeVar a = IDunno a <$> nextUnificationVar freshTypeHole :: a -> Check l a (IType l a) freshTypeHole a = IHole a <$> nextUnificationVar <*> pure Nothing freshOpenRecord :: a -> Fields l a -> Check l a (IType l a) freshOpenRecord a fs = IOpenRecord a <$> nextUnificationVar <*> pure fs data Constraint l a = Equal (Maybe a) (IType l a) (IType l a) | ExplicitInstance (Maybe a) (IType l a) (IType l a) deriving (Eq, Ord, Show) addConstraint :: Constraint l a -> Check l a () addConstraint c = Check . lift $ modify' (\s -> s { sConstraints = D.cons c (sConstraints s) }) addAssumption :: Name -> a -> IType l a -> Check l a () addAssumption n a ty = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.insertWith (<>) n [(a, ty)] (unAssumptions (sAssumptions s))) }) setAssumptions :: Name -> [(a, IType l a)] -> Check l a () setAssumptions n assums = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.insert n assums (unAssumptions (sAssumptions s))) }) deleteAssumptions :: Name -> Check l a () deleteAssumptions n = Check . lift $ modify' (\s -> s { sAssumptions = Assumptions (M.delete n (unAssumptions (sAssumptions s))) }) lookupAssumptions :: Name -> Check l a [(a, IType l a)] lookupAssumptions n = Check . lift $ fmap (fromMaybe mempty) (gets (M.lookup n . unAssumptions . sAssumptions)) withBindings :: Traversable f => f Name -> Check l a b -> Check l a (Map Name [(a, IType l a)], b) withBindings xs k = do old <- fmap (M.fromList . toList) . for xs $ \n -> do as <- lookupAssumptions n deleteAssumptions n pure (n, as) res <- k new <- fmap (M.fromList . toList) . for xs $ \n -> do as <- lookupAssumptions n setAssumptions n (fromMaybe mempty (M.lookup n old)) pure (n, as) pure (new, res) withBinding :: Name -> Check l a b -> Check l a ([(a, IType l a)], b) withBinding x k = do (as, b) <- withBindings [x] k pure (fromMaybe mempty (M.lookup x as), b) Constraint generation generateConstraints :: Ground l => TypeDecls l -> Expr l a -> Either [TypeError l a] (Expr l (IType l a, a), [Constraint l a], Assumptions l a) generateConstraints decls expr = do (e, st) <- runCheck (generateConstraints' decls expr) pure (e, D.toList (sConstraints st), sAssumptions st) generateConstraints' :: Ground l => TypeDecls l -> Expr l a -> Check l a (Expr l (IType l a, a)) generateConstraints' decls expr = case expr of ELit a v -> let ty = TLit (typeOf v) in pure (ELit (hoistType decls a ty, a) v) EVar a v -> do t <- freshTypeVar a addAssumption v a t pure (EVar (t, a) v) ELam a n mta e -> do (as, e') <- withBinding n (generateConstraints' decls e) ta <- maybe (freshTypeVar a) (pure . hoistType decls a) mta for_ (fmap snd as) (addConstraint . Equal (Just a) ta) let ty = IArrow a ta (extractType e') pure (ELam (ty, a) n mta e') EApp a f g -> do f' <- generateConstraints' decls f g' <- generateConstraints' decls g t <- freshTypeVar a addConstraint (ExplicitInstance (Just a) (IArrow a (extractType g') t) (extractType f')) pure (EApp (t, a) f' g') EList a es -> do es' <- for es (generateConstraints' decls) te <- freshTypeVar a for_ es' (addConstraint . Equal (Just a) te . extractType) let ty = IList a te pure (EList (ty, a) es') EMap a f g -> do f' <- generateConstraints' decls f g' <- generateConstraints' decls g ta <- freshTypeVar a tb <- freshTypeVar a addConstraint (Equal (Just a) (IArrow a ta tb) (extractType f')) addConstraint (Equal (Just a) (IList a ta) (extractType g')) let ty = IList a tb pure (EMap (ty, a) f' g') ECon a c tn es -> case lookupType tn decls of Just ty@(DVariant ps cns) -> do ts <- maybe (throwError (BadConstructorName c tn ty a)) pure (L.lookup c cns) unless (length ts == length es) (throwError (BadConstructorArity c (length ts) (length es) a)) ps' <- for ps (\p -> (p,) <$> freshTypeVar a) let typeParams = M.fromList ps' es' <- for es (generateConstraints' decls) for_ (L.zip (fmap (hoistType decls a) ts) (fmap extractType es')) ( Substitute the type parameters for instantiated versions first ) (\(expected, inferred) -> addConstraint (Equal (Just a) (subst typeParams expected) inferred)) let ty' = foldl' (IApp a) (IVar a tn) (fmap snd ps') pure (ECon (ty', a) c tn es') Records should be constructed via ERec , not ECon Just ty@(DRecord _ _) -> do throwError (BadConstructorName c tn ty a) Nothing -> throwError (UndeclaredType tn a) ECase a e pes -> do e' <- generateConstraints' decls e ty <- freshTypeVar a pes' <- for pes $ \(pat, pe) -> do let bnds = patternBinds pat (_, res) <- withBindings (S.toList bnds) $ do pe' <- generateConstraints' decls pe pat' <- patternConstraints decls (extractType e') pat addConstraint (Equal (Just a) ty (extractType pe')) pure (pat', pe') pure res pure (ECase (ty, a) e' pes') ERec a tn fes -> do case lookupType tn decls of Just (DRecord ps fts) -> do ps' <- for ps (\p -> (p,) <$> freshTypeVar a) let typeParams = M.fromList ps' fes' <- traverse (traverse (generateConstraints' decls)) fes let need = M.fromList (fmap (fmap (hoistType decls a)) fts) have = M.fromList (fmap (fmap extractType) fes') _ <- M.mergeA (M.traverseMissing (\fn ty -> throwError (MissingRecordField tn fn (flattenIType ty) a))) (M.traverseMissing (\fn ty -> throwError (ExtraRecordField tn fn (flattenIType ty) a))) (M.zipWithAMatched (\_fn twant thave -> addConstraint (Equal (Just a) (subst typeParams twant) thave))) need have when (length fes /= length fts) $ throwError (DuplicateRecordFields tn (fmap fst fes L.\\ fmap fst fts) a) let ty' = foldl' (IApp a) (IClosedRecord a tn (substFields typeParams (hoistFields decls a fts))) (fmap snd ps') pure (ERec (ty', a) tn fes') Variants should be constructed via ECon , not Just ty@(DVariant _ _) -> do throwError (BadConstructorName (Constructor (unTypeName tn)) tn ty a) Nothing -> throwError (UndeclaredType tn a) EPrj a e fn -> do e' <- generateConstraints' decls e tp <- freshTypeVar a rt <- freshOpenRecord a (field fn tp) addConstraint (Equal (Just a) rt (extractType e')) pure (EPrj (tp, a) e' fn) EForeign a n ty -> do pure (EForeign (hoistType decls a ty, a) n ty) EHole a -> do ty <- freshTypeHole a pure (EHole (ty, a)) patternConstraints :: Ground l => TypeDecls l -> IType l a -> Pattern a -> Check l a (Pattern (IType l a, a)) patternConstraints decls ty pat = case pat of PVar a x -> do as <- lookupAssumptions x for_ (fmap snd as) (addConstraint . Equal (Just a) ty) pure (PVar (ty, a) x) PCon a c pats -> case lookupConstructor c decls of Just (tn, ps, ts) -> do unless (length ts == length pats) (throwError (BadPatternArity c (TVar tn) (length ts) (length pats) a)) ps' <- for ps (\p -> (p,) <$> freshTypeVar a) let ty' = foldl' (IApp a) (hoistType decls a (TVar tn)) (fmap snd ps') typeParams = M.fromList ps' pats' <- for (L.zip (fmap (hoistType decls a) ts) pats) $ \(ty2, pat2) -> patternConstraints decls (subst typeParams ty2) pat2 addConstraint (Equal (Just a) ty' (subst typeParams ty)) pure (PCon (ty', a) c pats') Nothing -> throwError (BadPatternConstructor c a) PWildcard a -> pure (PWildcard (ty, a)) extractType :: Expr l (c, a) -> c extractType = fst . extractAnnotation Constraint solving newtype Substitutions l a = Substitutions { unSubstitutions :: Map Var (IType l a) } deriving (Eq, Ord, Show) substitute :: Ground l => Substitutions l a -> Expr l (IType l a, a) -> Expr l (IType l a, a) substitute subs expr = with expr $ \(ty, a) -> (substituteType subs True ty, a) substituteType :: Ground l => Substitutions l a -> Bool -> IType l a -> IType l a substituteType subs top ty = case ty of IDunno _ x -> maybe ty (substituteType subs False) (M.lookup x (unSubstitutions subs)) IHole a x _ -> maybe ty (\sty -> let res = substituteType subs False sty in if top then IHole a x (Just res) else res) (M.lookup x (unSubstitutions subs)) IArrow a t1 t2 -> IArrow a (substituteType subs False t1) (substituteType subs False t2) IApp a t1 t2 -> IApp a (substituteType subs False t1) (substituteType subs False t2) IList a t -> IList a (substituteType subs False t) IOpenRecord _ x _ -> maybe ty (substituteType subs False) (M.lookup x (unSubstitutions subs)) IForall a bs t -> IForall a bs (substituteType subs False t) IClosedRecord _ _ _ -> ty ILit _ _ -> ty IVar _ _ -> ty # INLINE substituteType # newtype Points s l a = Points { unPoints :: Map Var (UF.Point s (IType l a)) } mostGeneralUnifierST :: Ground l => STRef s (Points s l a) -> IType l a -> IType l a -> ST s (Either [TypeError l a] ()) mostGeneralUnifierST points t1 t2 = runEitherT (void (mguST points t1 t2)) mguST :: Ground l => STRef s (Points s l a) -> IType l a -> IType l a -> EitherT [TypeError l a] (ST s) (IType l a) mguST points t1 t2 = case (t1, t2) of (IDunno a x, _) -> do unifyVar points a x t2 (_, IDunno a x) -> do unifyVar points a x t1 (IHole a x _, _) -> do unifyVar points a x t2 (_, IHole a x _) -> do unifyVar points a x t1 (IOpenRecord a x fs, IOpenRecord b y gs) -> do hs <- unifyOpenFields points fs gs unifyVar points a x (IOpenRecord b y hs) (IOpenRecord a x fs, IClosedRecord _ tn gs) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t2 (IOpenRecord a x fs, IApp _ (IClosedRecord _ tn gs) _) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t2 (IClosedRecord _ tn gs, IOpenRecord a x fs) -> do _hs <- unifyClosedFields points fs tn gs unifyVar points a x t1 (IClosedRecord _ x _fs1, IClosedRecord _ y _fs2) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (IVar _ x, IVar _ y) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (ILit _ x, ILit _ y) -> do unless (x == y) (left [unificationError t1 t2]) pure t1 (IArrow a f g, IArrow _ h i) -> do [j, k] <- ET.sequenceEitherT [mguST points f h, mguST points g i] pure (IArrow a j k) (IApp a f g, IApp _ h i) -> do [j, k] <- ET.sequenceEitherT [mguST points f h, mguST points g i] pure (IApp a j k) (IList k a, IList _ b) -> do c <- mguST points a b pure (IList k c) (IForall a ts1 ot1, IForall b ts2 ot2) -> case (normalise a ts1 ot1, normalise b ts2 ot2) of (IForall _ ps1 tt1, IForall _ ps2 tt2) -> do unless (ps1 == ps2) (left [unificationError t1 t2]) c <- mguST points tt1 tt2 pure (IForall a ps1 c) (tt1, tt2) -> left [unificationError tt1 tt2] (_, _) -> left [unificationError t1 t2] unifyVar :: Ground l => STRef s (Points s l a) -> a -> Var -> IType l a -> EitherT [TypeError l a] (ST s) (IType l a) unifyVar points a x t2 = do mt1 <- lift (getRepr points x) let safeUnion c z u2 = do unless (typeVar u2 == Just z) (ET.hoistEither (occurs c z u2) *> lift (union points (IDunno c z) u2)) pure u2 case mt1 of Just t1@(IDunno b y) -> if x == y then firstT pure (safeUnion b y t2) else mguST points t1 t2 Just t1 -> mguST points t1 t2 Nothing -> firstT pure (safeUnion a x t2) occurs :: a -> Var -> IType l a -> Either (TypeError l a) () occurs a q ity = go q ity where go x i = case i of IDunno _ y -> when (x == y) (Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity))) IHole _ y _ -> when (x == y) (Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity))) IVar _ _ -> pure () ILit _ _ -> pure () IArrow _ f g -> go x f *> go x g IApp _ f g -> go x f *> go x g IClosedRecord _ _ (Fields fs) -> traverse_ (go x) fs IOpenRecord _ y (Fields fs) -> if x == y then Left (InfiniteType (flattenIType (IDunno a x)) (flattenIType ity)) else traverse_ (go x) fs IList _ f -> go x f IForall _ _ t -> go x t # INLINE occurs # unifyOpenFields :: Ground l => STRef s (Points s l a) -> Fields l a -> Fields l a -> EitherT [TypeError l a] (ST s) (Fields l a) unifyOpenFields points (Fields fs1) (Fields fs2) = do fmap Fields . ET.sequenceEitherT $ M.merge (M.mapMissing (const (firstT pure . pure))) (M.mapMissing (const (firstT pure . pure))) (M.zipWithMatched (\_fn t1 t2 -> mguST points t1 t2)) fs1 fs2 unifyClosedFields :: Ground l => STRef s (Points s l a) -> Fields l a -> TypeName -> Fields l a -> EitherT [TypeError l a] (ST s) (Fields l a) unifyClosedFields points (Fields have) tn (Fields want) = do fmap Fields . ET.sequenceEitherT $ M.merge (M.mapMissing (\fn t1 -> left [ExtraRecordField tn fn (flattenIType t1) (snd (flattenIType t1))])) (M.mapMissing (const (firstT pure . pure))) (M.zipWithMatched (\_fn t1 t2 -> mguST points t1 t2)) have want solveConstraints :: Ground l => Traversable f => f (Constraint l a) -> Either [TypeError l a] (Substitutions l a) solveConstraints constraints = runST $ flip evalStateT (NameSupply 0) $ do Initialise mutable state . points <- lift $ ST.newSTRef (Points M.empty) let mgu ma t1 t2 = fmap (first (D.fromList . fmap (maybe id Annotated ma))) (lift $ mostGeneralUnifierST points t1 t2) es <- fmap ET.sequenceEither . for constraints $ \c -> case c of Equal ma t1 t2 -> mgu ma t1 t2 ExplicitInstance ma want have -> do inst1 <- instantiate want inst2 <- instantiate have mgu ma inst1 inst2 solvedPoints <- lift $ ST.readSTRef points lift . for (first D.toList es) $ \_ -> do substitutionMap solvedPoints instantiate :: (Monad m) => IType l a -> StateT NameSupply m (IType l a) instantiate ty = case ty of IForall a vars ity -> do bnds <- traverse (fmap (IDunno a) . const nextSVar) (M.fromList (fmap (\v -> (v, ())) vars)) pure (subst bnds ity) _ -> pure ty normalise :: a -> [TypeName] -> IType l a -> IType l a normalise a ps t = let vars = with [0..length ps] (dunnoTypeVar' "") bnds = M.fromList $ with (L.zip ps vars) (\(n, x) -> (n, IVar a x)) in IForall a vars (subst bnds t) subst :: Map TypeName (IType l a) -> IType l a -> IType l a subst bnds' ty' | null bnds' = ty' | otherwise = go bnds' ty' where go bnds ity = case ity of IVar _a tn -> fromMaybe ity (M.lookup tn bnds) IForall a bs t -> IForall a bs (go (foldl' (flip M.delete) bnds bs) t) IArrow a t1 t2 -> IArrow a (go bnds t1) (go bnds t2) IApp a t1 t2 -> IApp a (go bnds t1) (go bnds t2) IList a t1 -> IList a (go bnds t1) IHole a x mty -> IHole a x (fmap (go bnds) mty) ILit _ _ -> ity IDunno _ _ -> ity IClosedRecord _ _ _ -> ity IOpenRecord _ _ _ -> ity nextSVar :: Monad m => StateT NameSupply m Var nextSVar = do NameSupply x <- get put (NameSupply (x + 1)) pure (S x) substitutionMap :: Points s l a -> ST s (Substitutions l a) substitutionMap points = do subs <- for (unPoints points) (UF.descriptor <=< UF.repr) pure (Substitutions (M.filterWithKey (\k v -> case v of IDunno _ x -> k /= x; _ -> True) subs)) union :: STRef s (Points s l a) -> IType l a -> IType l a -> ST s () union points t1 t2 = do p1 <- getPoint points t1 p2 <- getPoint points t2 UF.union p1 p2 getPoint :: STRef s (Points s l a) -> IType l a -> ST s (UF.Point s (IType l a)) getPoint mref ty = case ty of IDunno _ x -> do ps <- ST.readSTRef mref case M.lookup x (unPoints ps) of Just point -> pure point Nothing -> do point <- UF.fresh ty ST.modifySTRef' mref (Points . M.insert x point . unPoints) pure point _ -> UF.fresh ty # INLINE getPoint # getRepr :: STRef s (Points s l a) -> Var -> ST s (Maybe (IType l a)) getRepr points x = do ps <- ST.readSTRef points for (M.lookup x (unPoints ps)) (UF.descriptor <=< UF.repr)
38ae3b8d37967b2b3f2ceb1d8112cededf904f93ad6628e4e2ad6ba2ae96522d
matteoredaelli/ebot
ebot_html.erl
EBOT , an erlang web crawler . Copyright ( C ) 2010 ~ matteo DOT AT libero DOT it %% / %% %% 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 </>. %% %%%------------------------------------------------------------------- %%% File : ebot_html.erl %%% Author : matteo <<matteo.redaelli@@libero.it> %%% Description : %%% Created : 19 Jun 2010 by matteo < > %%%------------------------------------------------------------------- -module(ebot_html). -author(""). -define(SERVER, ?MODULE). -define(TIMEOUT, 5000). -define(WORKER_TYPE, html). -include("ebot.hrl"). -behaviour(gen_server). %% API -export([ analyze_url/2, analyze_url_body_plugins/2, check_recover_workers/0, run/1, info/0, remove_worker/1, get_workers/0, start_workers/0, start_workers/2, start_link/0, statistics/0 ]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state,{ workers = ebot_worker_util:create_workers(?WORKER_TYPE) }). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], [{timeout,?TIMEOUT}]). check_recover_workers() -> gen_server:call(?MODULE, {check_recover_workers}). info() -> gen_server:call(?MODULE, {info}). get_workers() -> gen_server:call(?MODULE, {get_workers}). start_workers() -> gen_server:cast(?MODULE, {start_workers}). start_workers(Depth, Tot) -> gen_server:cast(?MODULE, {start_workers, Depth, Tot}). statistics() -> gen_server:call(?MODULE, {statistics}). remove_worker(Worker) -> gen_server:cast(?MODULE, {remove_worker, Worker}). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> case ebot_util:get_env(start_workers_at_boot) of {ok, true} -> State = start_workers(#state{}); {ok, false} -> State = #state{} end, {ok, State}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({check_recover_workers}, _From, State) -> Workers = ebot_worker_util:check_recover_workers(State#state.workers), NewState = State#state{ workers = Workers }, {reply, Workers, NewState}; handle_call({info}, _From, State) -> {reply, ok, State}; handle_call({statistics}, _From, State) -> Reply = ebot_worker_util:statistics(State#state.workers), {reply, Reply, State}; handle_call({get_workers}, _From, State) -> {?WORKER_TYPE, Reply} = State#state.workers, {reply, Reply, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast({remove_worker, Worker}, State) -> NewState = State#state{ workers = ebot_worker_util:remove_worker(Worker, State#state.workers) }, {noreply, NewState}; handle_cast({start_workers}, State) -> NewState = start_workers(State), {noreply, NewState}; handle_cast({start_workers, Depth, Tot}, State) -> NewState = State#state{ workers = ebot_worker_util:start_workers(Depth,Tot, State#state.workers) }, {noreply, NewState}; handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: 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 Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. run(Depth) -> case ebot_mq:receive_url_fetched(Depth) of {ok, {Url, Result}} -> analyze_url(Url, Result); {error, _} -> error_logger:info_report({?MODULE, ?LINE, {run, no_queued_urls, waiting}}), timer:sleep( ?EBOT_EMPTY_QUEUE_TIMEOUT ) end, case ebot_crawler:workers_status() of started -> {ok, Sleep} = ebot_util:get_env(workers_sleep_time), timer:sleep( Sleep ), run(Depth); stopped -> error_logger:warning_report({?MODULE, ?LINE, {stopping_worker, self()}}), remove_worker( {Depth, self()} ) end. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- analyze_url(Url,{error, Reason}) -> error_logger:error_report({?MODULE, ?LINE, {analyze_url, Url, skipping_url, Reason}}), Options = [{update_counter, <<"ebot_errors_count">>}, {update_value, <<"ebot_head_error">>, list_to_binary(atom_to_list(Reason))} ], TODO : instead of only Url , it would be nice to send { Url , Reason } %% like <<"/,https_through_proxy_is_not_currently_supported">> ebot_mq:send_url_refused({Url,Reason}), ebot_db:update_doc(Url, Options), {error, Reason}; analyze_url(Url,{ok, {Status, Headers, Body}}) -> analyze_url_head(Url, {Status, Headers, empty}), analyze_url_body(Url, {empty, empty, Body}). analyze_url_head(Url, Result = {_Status, _Headers, empty}) -> {ok, H} = ebot_util:get_env(tobe_saved_headers), Options = [{head, Result, H}, {update_timestamp,<<"ebot_head_visited">>}, {update_counter, <<"ebot_visits_count">>}, {update_value, <<"ebot_errors_count">>, 0} ], ebot_db:update_doc(Url, Options). analyze_url_body(Url, {_Status, _Headers, empty}) -> error_logger:info_report({?MODULE, ?LINE, {analyze_url_body, Url, empty_body}}); analyze_url_body(Url, {_Status, _Headers, Body}) -> Tokens = mochiweb_html:tokens(Body), spawn(?MODULE, analyze_url_body_plugins, [Url, Tokens]), error_logger:info_report({?MODULE, ?LINE, {analyze_body_plugins, Url}}), Links = ebot_html_util:get_links_from_tokens(Tokens, Url), analyze_url_body_links(Url, Links), ebot_mq:send_url_processed({Url, empty}). analyze_url_body_links(Url, Links) -> error_logger:info_report({?MODULE, ?LINE, {getting_links_of, Url}}), LinksCount = length(ebot_url_util:filter_external_links(Url, Links)), %% normalizing Links error_logger:info_report({?MODULE, ?LINE, {normalizing_links_of, Url}}), NormalizedLinks = lists:map( fun(U) -> {ok, ListNormalizeOptions} = ebot_util:get_env(normalize_url), {ok, NormalizeOptions} = get_env_normalize_url(Url, ListNormalizeOptions), ebot_url_util:normalize_url(U, NormalizeOptions) end, Links), %% removing duplicates UniqueLinks = ebot_util:remove_duplicates(NormalizedLinks), TODO %% removing unwanted urls %% %% removing already visited urls and not valid NotVisitedLinks = lists:filter( fun(U) -> (not ebot_crawler:is_visited_url(U)) andalso ebot_url_util:is_valid_url(U) end, UniqueLinks), %% retrive Url from DB lists:foreach( fun(U) -> %% creating the url in the database if it doen't exists error_logger:info_report({?MODULE, ?LINE, {adding, U, from_referral, Url}}), ebot_db:open_or_create_url(U), ebot_crawler:add_new_url(U), case needed_update_url_referral( ebot_url_util:is_same_main_domain(Url, U), ebot_url_util:is_same_domain(Url, U)) of true -> Options = [{referral, Url}], ebot_db:update_doc(U, Options); false -> ok end end, NotVisitedLinks), %% UPDATE ebot-body-visited Options = [{update_timestamp, <<"ebot_body_visited">>}, {update_value, <<"ebot_links_count">>, LinksCount} ], ebot_db:update_doc(Url, Options), ok. analyze_url_body_plugins(Url, Tokens) -> error_logger:info_report({?MODULE, ?LINE, {analyze_url_body_plugins, Url}}), lists:foreach( fun({Module, Function}) -> analyze_url_body_plugin(Url, Tokens, Module, Function) end, ?EBOT_BODY_ANALYZER_PLUGINS ). analyze_url_body_plugin(Url, Tokens, Module, Function) -> Options = Module:Function(Url, Tokens), error_logger:info_report({?MODULE, ?LINE, {analyze_url_body_plugin, Url, Module, Function, Options}}), ebot_db:update_doc(Url, Options). get_env_normalize_url(Url, [{RE,Options}|L]) -> case re:run(Url, RE, [{capture, none},caseless]) of match -> {ok, Options}; nomatch -> get_env_normalize_url(Url, L) end; get_env_normalize_url(_Url, []) -> undefined. needed_update_url_referral(SameMainDomain, SameDomain) -> {ok, SaveReferralsOptions} = ebot_util:get_env(save_referrals), lists:any( fun(Option) -> needed_update_url_referral(SameMainDomain, SameDomain, Option) end, SaveReferralsOptions ). needed_update_url_referral(SameMainDomain , SameDomain , domain|subdomain|external ) needed_update_url_referral(false, false, external) -> true; needed_update_url_referral(true, false, subdomain) -> true; needed_update_url_referral(_, true, domain) -> true; needed_update_url_referral(_,_,_) -> false. start_workers(State) -> {ok, Pool} = ebot_util:get_env(workers_pool), State#state{ workers = ebot_worker_util:start_workers(Pool, State#state.workers) }. %%==================================================================== EUNIT TESTS %%==================================================================== -include_lib("eunit/include/eunit.hrl"). -ifdef(TEST). ebot_html_test() -> <<"/">>. -endif.
null
https://raw.githubusercontent.com/matteoredaelli/ebot/6a6af4eb345adfa05b4508ed2dec529413d97da8/src/ebot_html.erl
erlang
/ This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. ------------------------------------------------------------------- File : ebot_html.erl Author : matteo <<matteo.redaelli@@libero.it> Description : ------------------------------------------------------------------- API gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: 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 Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- like <<"/,https_through_proxy_is_not_currently_supported">> normalizing Links removing duplicates removing unwanted urls removing already visited urls and not valid retrive Url from DB creating the url in the database if it doen't exists UPDATE ebot-body-visited ==================================================================== ====================================================================
EBOT , an erlang web crawler . Copyright ( C ) 2010 ~ matteo DOT AT libero DOT it 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 Created : 19 Jun 2010 by matteo < > -module(ebot_html). -author(""). -define(SERVER, ?MODULE). -define(TIMEOUT, 5000). -define(WORKER_TYPE, html). -include("ebot.hrl"). -behaviour(gen_server). -export([ analyze_url/2, analyze_url_body_plugins/2, check_recover_workers/0, run/1, info/0, remove_worker/1, get_workers/0, start_workers/0, start_workers/2, start_link/0, statistics/0 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state,{ workers = ebot_worker_util:create_workers(?WORKER_TYPE) }). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], [{timeout,?TIMEOUT}]). check_recover_workers() -> gen_server:call(?MODULE, {check_recover_workers}). info() -> gen_server:call(?MODULE, {info}). get_workers() -> gen_server:call(?MODULE, {get_workers}). start_workers() -> gen_server:cast(?MODULE, {start_workers}). start_workers(Depth, Tot) -> gen_server:cast(?MODULE, {start_workers, Depth, Tot}). statistics() -> gen_server:call(?MODULE, {statistics}). remove_worker(Worker) -> gen_server:cast(?MODULE, {remove_worker, Worker}). { ok , State , Timeout } | init([]) -> case ebot_util:get_env(start_workers_at_boot) of {ok, true} -> State = start_workers(#state{}); {ok, false} -> State = #state{} end, {ok, State}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({check_recover_workers}, _From, State) -> Workers = ebot_worker_util:check_recover_workers(State#state.workers), NewState = State#state{ workers = Workers }, {reply, Workers, NewState}; handle_call({info}, _From, State) -> {reply, ok, State}; handle_call({statistics}, _From, State) -> Reply = ebot_worker_util:statistics(State#state.workers), {reply, Reply, State}; handle_call({get_workers}, _From, State) -> {?WORKER_TYPE, Reply} = State#state.workers, {reply, Reply, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast({remove_worker, Worker}, State) -> NewState = State#state{ workers = ebot_worker_util:remove_worker(Worker, State#state.workers) }, {noreply, NewState}; handle_cast({start_workers}, State) -> NewState = start_workers(State), {noreply, NewState}; handle_cast({start_workers, Depth, Tot}, State) -> NewState = State#state{ workers = ebot_worker_util:start_workers(Depth,Tot, State#state.workers) }, {noreply, NewState}; handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. run(Depth) -> case ebot_mq:receive_url_fetched(Depth) of {ok, {Url, Result}} -> analyze_url(Url, Result); {error, _} -> error_logger:info_report({?MODULE, ?LINE, {run, no_queued_urls, waiting}}), timer:sleep( ?EBOT_EMPTY_QUEUE_TIMEOUT ) end, case ebot_crawler:workers_status() of started -> {ok, Sleep} = ebot_util:get_env(workers_sleep_time), timer:sleep( Sleep ), run(Depth); stopped -> error_logger:warning_report({?MODULE, ?LINE, {stopping_worker, self()}}), remove_worker( {Depth, self()} ) end. Internal functions analyze_url(Url,{error, Reason}) -> error_logger:error_report({?MODULE, ?LINE, {analyze_url, Url, skipping_url, Reason}}), Options = [{update_counter, <<"ebot_errors_count">>}, {update_value, <<"ebot_head_error">>, list_to_binary(atom_to_list(Reason))} ], TODO : instead of only Url , it would be nice to send { Url , Reason } ebot_mq:send_url_refused({Url,Reason}), ebot_db:update_doc(Url, Options), {error, Reason}; analyze_url(Url,{ok, {Status, Headers, Body}}) -> analyze_url_head(Url, {Status, Headers, empty}), analyze_url_body(Url, {empty, empty, Body}). analyze_url_head(Url, Result = {_Status, _Headers, empty}) -> {ok, H} = ebot_util:get_env(tobe_saved_headers), Options = [{head, Result, H}, {update_timestamp,<<"ebot_head_visited">>}, {update_counter, <<"ebot_visits_count">>}, {update_value, <<"ebot_errors_count">>, 0} ], ebot_db:update_doc(Url, Options). analyze_url_body(Url, {_Status, _Headers, empty}) -> error_logger:info_report({?MODULE, ?LINE, {analyze_url_body, Url, empty_body}}); analyze_url_body(Url, {_Status, _Headers, Body}) -> Tokens = mochiweb_html:tokens(Body), spawn(?MODULE, analyze_url_body_plugins, [Url, Tokens]), error_logger:info_report({?MODULE, ?LINE, {analyze_body_plugins, Url}}), Links = ebot_html_util:get_links_from_tokens(Tokens, Url), analyze_url_body_links(Url, Links), ebot_mq:send_url_processed({Url, empty}). analyze_url_body_links(Url, Links) -> error_logger:info_report({?MODULE, ?LINE, {getting_links_of, Url}}), LinksCount = length(ebot_url_util:filter_external_links(Url, Links)), error_logger:info_report({?MODULE, ?LINE, {normalizing_links_of, Url}}), NormalizedLinks = lists:map( fun(U) -> {ok, ListNormalizeOptions} = ebot_util:get_env(normalize_url), {ok, NormalizeOptions} = get_env_normalize_url(Url, ListNormalizeOptions), ebot_url_util:normalize_url(U, NormalizeOptions) end, Links), UniqueLinks = ebot_util:remove_duplicates(NormalizedLinks), TODO NotVisitedLinks = lists:filter( fun(U) -> (not ebot_crawler:is_visited_url(U)) andalso ebot_url_util:is_valid_url(U) end, UniqueLinks), lists:foreach( fun(U) -> error_logger:info_report({?MODULE, ?LINE, {adding, U, from_referral, Url}}), ebot_db:open_or_create_url(U), ebot_crawler:add_new_url(U), case needed_update_url_referral( ebot_url_util:is_same_main_domain(Url, U), ebot_url_util:is_same_domain(Url, U)) of true -> Options = [{referral, Url}], ebot_db:update_doc(U, Options); false -> ok end end, NotVisitedLinks), Options = [{update_timestamp, <<"ebot_body_visited">>}, {update_value, <<"ebot_links_count">>, LinksCount} ], ebot_db:update_doc(Url, Options), ok. analyze_url_body_plugins(Url, Tokens) -> error_logger:info_report({?MODULE, ?LINE, {analyze_url_body_plugins, Url}}), lists:foreach( fun({Module, Function}) -> analyze_url_body_plugin(Url, Tokens, Module, Function) end, ?EBOT_BODY_ANALYZER_PLUGINS ). analyze_url_body_plugin(Url, Tokens, Module, Function) -> Options = Module:Function(Url, Tokens), error_logger:info_report({?MODULE, ?LINE, {analyze_url_body_plugin, Url, Module, Function, Options}}), ebot_db:update_doc(Url, Options). get_env_normalize_url(Url, [{RE,Options}|L]) -> case re:run(Url, RE, [{capture, none},caseless]) of match -> {ok, Options}; nomatch -> get_env_normalize_url(Url, L) end; get_env_normalize_url(_Url, []) -> undefined. needed_update_url_referral(SameMainDomain, SameDomain) -> {ok, SaveReferralsOptions} = ebot_util:get_env(save_referrals), lists:any( fun(Option) -> needed_update_url_referral(SameMainDomain, SameDomain, Option) end, SaveReferralsOptions ). needed_update_url_referral(SameMainDomain , SameDomain , domain|subdomain|external ) needed_update_url_referral(false, false, external) -> true; needed_update_url_referral(true, false, subdomain) -> true; needed_update_url_referral(_, true, domain) -> true; needed_update_url_referral(_,_,_) -> false. start_workers(State) -> {ok, Pool} = ebot_util:get_env(workers_pool), State#state{ workers = ebot_worker_util:start_workers(Pool, State#state.workers) }. EUNIT TESTS -include_lib("eunit/include/eunit.hrl"). -ifdef(TEST). ebot_html_test() -> <<"/">>. -endif.
c42ad9af0d2877f89dbd0357135d3c8045e3ce3a4f5c9786af79980870413314
martintrojer/datalog
rules.clj
Copyright ( c ) . All rights reserved . The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; rules.clj ;; A Clojure implementation of Datalog -- Rules Engine ;; straszheimjeffrey ( gmail ) Created 2 Feburary 2009 Converted to Clojure1.4 by 2012 . (ns datalog.rules (:use [datalog.util] [datalog.literals] [datalog.database]) (:use [clojure.set :only (union intersection difference subset?)])) (defrecord DatalogRule [head body]) (defn display-rule "Return the rule in a readable format." [rule] (list* '<- (-> rule :head display-literal) (map display-literal (:body rule)))) (defn display-query "Return a query in a readable format." [query] (list* '?- (display-literal query))) ;; ============================= ;; Check rule safety (defn is-safe? "Is the rule safe according to the datalog protocol?" [rule] (let [hv (literal-vars (:head rule)) bpv (apply union (map positive-vars (:body rule))) bnv (apply union (map negative-vars (:body rule))) ehv (difference hv bpv) env (difference bnv bpv)] (when-not (empty? ehv) (throw (Exception. (str "Head vars" ehv "not bound in body of rule" rule)))) (when-not (empty? env) (throw (Exception. (str "Body vars" env "not bound in negative positions of rule" rule)))) rule)) ;; ============================= ;; Rule creation and printing (defn build-rule [hd bd] (with-meta (->DatalogRule hd bd) {:type ::datalog-rule})) (defmacro <- "Build a datalog rule. Like this: (<- (:head :x ?x :y ?y) (:body-1 :x ?x :y ?y) (:body-2 :z ?z) (not! :body-3 :x ?x) (if > ?y ?z))" [hd & body] (let [head (build-atom hd :datalog.literals/literal) body (map build-literal body)] `(is-safe? (build-rule ~head [~@body])))) (defmethod print-method ::datalog-rule [rule ^java.io.Writer writer] (print-method (display-rule rule) writer)) (defn return-rule-data "Returns an untypted rule that will be fully printed" [rule] (with-meta rule {})) (defmacro ?- "Define a datalog query" [& q] (let [qq (build-atom q :datalog.literals/literal)] `(with-meta ~qq {:type ::datalog-query}))) (defmethod print-method ::datalog-query [query ^java.io.Writer writer] (print-method (display-query query) writer)) ;; ============================= ;; SIP (defn compute-sip "Given a set of bound column names, return an adorned sip for this rule. A set of intensional predicates should be provided to determine what should be adorned." [bindings i-preds rule] (let [next-lit (fn [bv body] (or (first (drop-while #(not (literal-appropriate? bv %)) body)) (first (drop-while (complement positive?) body)))) adorn (fn [lit bvs] (if (i-preds (literal-predicate lit)) (let [bnds (union (get-cs-from-vs lit bvs) (get-self-bound-cs lit))] (adorned-literal lit bnds)) lit)) new-h (adorned-literal (:head rule) bindings)] (loop [bound-vars (get-vs-from-cs (:head rule) bindings) body (:body rule) sip []] (if-let [next (next-lit bound-vars body)] (recur (union bound-vars (literal-vars next)) (remove #(= % next) body) (conj sip (adorn next bound-vars))) (build-rule new-h (concat sip body)))))) ;; ============================= ;; Rule sets (defn make-rules-set "Given an existing set of rules, make it a 'rules-set' for printing." [rs] (with-meta rs {:type ::datalog-rules-set})) (def empty-rules-set (make-rules-set #{})) (defn rules-set "Given a collection of rules return a rules set" [& rules] (reduce conj empty-rules-set rules)) (defmethod print-method ::datalog-rules-set [rules ^java.io.Writer writer] (binding [*out* writer] (do (print "(rules-set") (doseq [rule rules] (println) (print " ") (print rule)) (println ")")))) (defn predicate-map "Given a rules-set, return a map of rules keyed by their predicates. Each value will be a set of rules." [rs] (let [add-rule (fn [m r] (let [pred (-> r :head literal-predicate) os (get m pred #{})] (assoc m pred (conj os r))))] (reduce add-rule {} rs))) (defn all-predicates "Given a rules-set, return all defined predicates" [rs] (set (map literal-predicate (map :head rs)))) (defn non-base-rules "Return a collection of rules that depend, somehow, on other rules" [rs] (let [pred (all-predicates rs) non-base (fn [r] (if (some #(pred %) (map literal-predicate (:body r))) r nil))] (remove nil? (map non-base rs)))) ;; ============================= ;; Database operations (def empty-bindings [{}]) (defn apply-rule "Apply the rule against db-1, adding the results to the appropriate relation in db-2. The relation will be created if needed." ([db rule] (apply-rule db db rule)) ([db-1 db-2 rule] (trace-datalog (println) (println) (println "--------------- Begin Rule ---------------") (println rule)) (let [head (:head rule) body (:body rule) step (fn [bs lit] (trace-datalog (println bs) (println lit)) (join-literal db-1 lit bs)) bs (reduce step empty-bindings body)] (do (trace-datalog (println bs)) (project-literal db-2 head bs))))) (defn apply-rules-set [db rs] (reduce (fn [rdb rule] (apply-rule db rdb rule)) db rs))
null
https://raw.githubusercontent.com/martintrojer/datalog/bd64e76ceb02c0494a654010c0221ada5fc2a002/src/datalog/rules.clj
clojure
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. rules.clj ============================= Check rule safety ============================= Rule creation and printing ============================= SIP ============================= Rule sets ============================= Database operations
Copyright ( c ) . All rights reserved . The use and A Clojure implementation of Datalog -- Rules Engine straszheimjeffrey ( gmail ) Created 2 Feburary 2009 Converted to Clojure1.4 by 2012 . (ns datalog.rules (:use [datalog.util] [datalog.literals] [datalog.database]) (:use [clojure.set :only (union intersection difference subset?)])) (defrecord DatalogRule [head body]) (defn display-rule "Return the rule in a readable format." [rule] (list* '<- (-> rule :head display-literal) (map display-literal (:body rule)))) (defn display-query "Return a query in a readable format." [query] (list* '?- (display-literal query))) (defn is-safe? "Is the rule safe according to the datalog protocol?" [rule] (let [hv (literal-vars (:head rule)) bpv (apply union (map positive-vars (:body rule))) bnv (apply union (map negative-vars (:body rule))) ehv (difference hv bpv) env (difference bnv bpv)] (when-not (empty? ehv) (throw (Exception. (str "Head vars" ehv "not bound in body of rule" rule)))) (when-not (empty? env) (throw (Exception. (str "Body vars" env "not bound in negative positions of rule" rule)))) rule)) (defn build-rule [hd bd] (with-meta (->DatalogRule hd bd) {:type ::datalog-rule})) (defmacro <- "Build a datalog rule. Like this: (<- (:head :x ?x :y ?y) (:body-1 :x ?x :y ?y) (:body-2 :z ?z) (not! :body-3 :x ?x) (if > ?y ?z))" [hd & body] (let [head (build-atom hd :datalog.literals/literal) body (map build-literal body)] `(is-safe? (build-rule ~head [~@body])))) (defmethod print-method ::datalog-rule [rule ^java.io.Writer writer] (print-method (display-rule rule) writer)) (defn return-rule-data "Returns an untypted rule that will be fully printed" [rule] (with-meta rule {})) (defmacro ?- "Define a datalog query" [& q] (let [qq (build-atom q :datalog.literals/literal)] `(with-meta ~qq {:type ::datalog-query}))) (defmethod print-method ::datalog-query [query ^java.io.Writer writer] (print-method (display-query query) writer)) (defn compute-sip "Given a set of bound column names, return an adorned sip for this rule. A set of intensional predicates should be provided to determine what should be adorned." [bindings i-preds rule] (let [next-lit (fn [bv body] (or (first (drop-while #(not (literal-appropriate? bv %)) body)) (first (drop-while (complement positive?) body)))) adorn (fn [lit bvs] (if (i-preds (literal-predicate lit)) (let [bnds (union (get-cs-from-vs lit bvs) (get-self-bound-cs lit))] (adorned-literal lit bnds)) lit)) new-h (adorned-literal (:head rule) bindings)] (loop [bound-vars (get-vs-from-cs (:head rule) bindings) body (:body rule) sip []] (if-let [next (next-lit bound-vars body)] (recur (union bound-vars (literal-vars next)) (remove #(= % next) body) (conj sip (adorn next bound-vars))) (build-rule new-h (concat sip body)))))) (defn make-rules-set "Given an existing set of rules, make it a 'rules-set' for printing." [rs] (with-meta rs {:type ::datalog-rules-set})) (def empty-rules-set (make-rules-set #{})) (defn rules-set "Given a collection of rules return a rules set" [& rules] (reduce conj empty-rules-set rules)) (defmethod print-method ::datalog-rules-set [rules ^java.io.Writer writer] (binding [*out* writer] (do (print "(rules-set") (doseq [rule rules] (println) (print " ") (print rule)) (println ")")))) (defn predicate-map "Given a rules-set, return a map of rules keyed by their predicates. Each value will be a set of rules." [rs] (let [add-rule (fn [m r] (let [pred (-> r :head literal-predicate) os (get m pred #{})] (assoc m pred (conj os r))))] (reduce add-rule {} rs))) (defn all-predicates "Given a rules-set, return all defined predicates" [rs] (set (map literal-predicate (map :head rs)))) (defn non-base-rules "Return a collection of rules that depend, somehow, on other rules" [rs] (let [pred (all-predicates rs) non-base (fn [r] (if (some #(pred %) (map literal-predicate (:body r))) r nil))] (remove nil? (map non-base rs)))) (def empty-bindings [{}]) (defn apply-rule "Apply the rule against db-1, adding the results to the appropriate relation in db-2. The relation will be created if needed." ([db rule] (apply-rule db db rule)) ([db-1 db-2 rule] (trace-datalog (println) (println) (println "--------------- Begin Rule ---------------") (println rule)) (let [head (:head rule) body (:body rule) step (fn [bs lit] (trace-datalog (println bs) (println lit)) (join-literal db-1 lit bs)) bs (reduce step empty-bindings body)] (do (trace-datalog (println bs)) (project-literal db-2 head bs))))) (defn apply-rules-set [db rs] (reduce (fn [rdb rule] (apply-rule db rdb rule)) db rs))
f205da0f19769ee2dec555c62cb1e26166924f2b521da7e93b63d87724b2d4d2
bsaleil/lc
do.scm
;;--------------------------------------------------------------------------- ;; Copyright ( c ) 2015 , . All rights reserved . ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are ;; met: ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; 3. The name of the author may not be used to endorse or promote ;; products derived from this software without specific prior written ;; permission. ;; THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN ;; NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT ;; NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; ;;--------------------------------------------------------------------------- ;;; Simple do (do ((i 0 (+ i 1))) ((= i 4) (println #t)) (println i)) ;;; No step (do ((i 0)) ((= i 4) (println #t)) (println i) (set! i (+ i 1))) ;;; No command (do ((i 0)) ((= (begin (set! i (+ i 1)) (println (- i 1)) i) 4) (println #t))) ;;; More complex form (pp (do ((vec (make-vector 4)) (i 0 (+ i 100)) (j 0 (+ j 1))) ((= i 400) (println #t) vec) (println j) (vector-set! vec j i)) ) 0 1 2 3 ;#t 0 1 2 3 ;#t 0 1 2 3 ;#t 0 1 2 3 ;#t ;#(0 100 200 300)
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/unit-tests/do.scm
scheme
--------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- Simple do No step No command More complex form #t #t #t #t #(0 100 200 300)
Copyright ( c ) 2015 , . All rights reserved . THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (do ((i 0 (+ i 1))) ((= i 4) (println #t)) (println i)) (do ((i 0)) ((= i 4) (println #t)) (println i) (set! i (+ i 1))) (do ((i 0)) ((= (begin (set! i (+ i 1)) (println (- i 1)) i) 4) (println #t))) (pp (do ((vec (make-vector 4)) (i 0 (+ i 100)) (j 0 (+ j 1))) ((= i 400) (println #t) vec) (println j) (vector-set! vec j i)) ) 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
320a457ff249acad8d31a8bce3e56645d04f0716f12eb93ba5d82de6c1509fc2
nvim-treesitter/nvim-treesitter
injections.scm
(preproc_arg) @c (comment) @comment
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/67f08570152792c6a4f0815e71a0093ad97f2725/queries/c/injections.scm
scheme
(preproc_arg) @c (comment) @comment
a7a842a3b5de029406fcc253066c9d5f3cd9e6d5d10d8160f2e521c60f6bf3f3
macchiato-framework/examples
config.cljs
(ns file-upload.config (:require [macchiato.env :as config] [mount.core :refer [defstate]])) (defstate env :start (config/env))
null
https://raw.githubusercontent.com/macchiato-framework/examples/946bdf1a04f5ef787fc83affdcbf6603bbf29b5c/file-upload/src/file_upload/config.cljs
clojure
(ns file-upload.config (:require [macchiato.env :as config] [mount.core :refer [defstate]])) (defstate env :start (config/env))
b6c4d32745481699d3839a83148b66dfb16add425a2650c36e8cac40ab28ffdc
nineties-retro/sps
sps-io.scm
(define sps:io:stdout current-output-port) (define (sps:io:write port string length) (if (= length (string-length string)) (display string port) (display (substring string 0 length) port))) (define (sps:io:write-substring port string start end) (display (substring string start end) port)) (define (sps:io:read port string length) (uniform-array-read! string port)) (define (sps:io:close port) (close-port port)) (define (sps:io:open-input file-name) (open-input-file (sps:string:literal file-name))) (define (sps:io:open-output file-name) (open-output-file (sps:string:literal file-name))) (define (sps:io:print:string port string) (display string port) #t) (define (sps:io:print:int port int) (display int port) #t) (define (sps:io:print:hex-int port int) (display int port) #t) (define (sps:io:print:char port char) (display char port) #t) (define (sps:io:print:bool port bool) (display (if bool "1" "0") port) #t) (define (sps:io:newline port) (newline port) #t)
null
https://raw.githubusercontent.com/nineties-retro/sps/bf15b415f4cdf5d6d69ae2f39c250db2090c0817/scm/sps-io.scm
scheme
(define sps:io:stdout current-output-port) (define (sps:io:write port string length) (if (= length (string-length string)) (display string port) (display (substring string 0 length) port))) (define (sps:io:write-substring port string start end) (display (substring string start end) port)) (define (sps:io:read port string length) (uniform-array-read! string port)) (define (sps:io:close port) (close-port port)) (define (sps:io:open-input file-name) (open-input-file (sps:string:literal file-name))) (define (sps:io:open-output file-name) (open-output-file (sps:string:literal file-name))) (define (sps:io:print:string port string) (display string port) #t) (define (sps:io:print:int port int) (display int port) #t) (define (sps:io:print:hex-int port int) (display int port) #t) (define (sps:io:print:char port char) (display char port) #t) (define (sps:io:print:bool port bool) (display (if bool "1" "0") port) #t) (define (sps:io:newline port) (newline port) #t)
aaec73b0634ae6b2aa4075c2a927085e8f132328df085ab2e2a92a54204cbe4f
TheLortex/mirage-monorepo
header.ml
{ { { Copyright ( c ) 2012 Anil Madhavapeddy < > * Copyright ( c ) 2011 - 2012 < > * Copyright ( c ) 2010 * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * } } } * Copyright (c) 2011-2012 Martin Jambon <> * Copyright (c) 2010 Mika Illouz * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) include Http.Header let media_type_re = let re = Re.Emacs.re ~case:true "[ \t]*\\([^ \t;]+\\)" in Re.(compile (seq [ start; re ])) let get_first_match _re s = try let subs = Re.exec ~pos:0 media_type_re s in let start, stop = Re.Group.offset subs 1 in Some (String.sub s start (stop - start)) with Not_found -> None (* Grab "foo/bar" from " foo/bar ; charset=UTF-8" *) let get_media_type headers = match get headers "content-type" with | Some s -> get_first_match media_type_re s | None -> None let get_acceptable_media_ranges headers = Accept.media_ranges (get_multi_concat ~list_value_only:true headers "accept") let get_acceptable_charsets headers = Accept.charsets (get_multi_concat ~list_value_only:true headers "accept-charset") let get_acceptable_encodings headers = Accept.encodings (get_multi_concat ~list_value_only:true headers "accept-encoding") let get_acceptable_languages headers = Accept.languages (get_multi_concat ~list_value_only:true headers "accept-language") Parse the transfer - encoding and content - length headers to * determine how to decode a body * determine how to decode a body *) let get_transfer_encoding headers = (* It should actually be [get] as the interresting value is actually the last.*) match get_multi_concat ~list_value_only:true headers "transfer-encoding" with | Some "chunked" -> Transfer.Chunked | Some _ | None -> ( match get_content_range headers with | Some len -> Transfer.Fixed len | None -> Transfer.Unknown) let add_transfer_encoding headers enc = let open Transfer in (* Only add a header if one doesnt already exist, e.g. from the app *) match (get_transfer_encoding headers, enc) with App has supplied a content length , so use that -> headers (* TODO: this is a protocol violation *) | Unknown, Chunked -> add headers "transfer-encoding" "chunked" | Unknown, Fixed len -> add headers "content-length" (Int64.to_string len) | Unknown, Unknown -> headers let add_authorization_req headers challenge = add headers "www-authenticate" (Auth.string_of_challenge challenge) let add_authorization headers cred = add headers "authorization" (Auth.string_of_credential cred) let get_authorization headers = match get headers "authorization" with | None -> None | Some v -> Some (Auth.credential_of_string v) let is_form headers = get_media_type headers = Some "application/x-www-form-urlencoded" let get_location headers = match get_location headers with | None -> None | Some u -> Some (Uri.of_string u) let get_links headers = List.rev (List.fold_left (fun list link_s -> List.rev_append (Link.of_string link_s) list) [] (get_multi headers "link")) let add_links headers links = add_multi headers "link" (List.map Link.to_string links) let user_agent = Printf.sprintf "ocaml-cohttp/%s" Conf.version let prepend_user_agent headers user_agent = let k = "user-agent" in match get headers k with | Some ua -> replace headers k (user_agent ^ " " ^ ua) | None -> add headers k user_agent let connection h = match get h "connection" with | Some v when v = "keep-alive" -> Some `Keep_alive | Some v when v = "close" -> Some `Close | Some x -> Some (`Unknown x) | _ -> None open Sexplib0.Sexp_conv let sexp_of_t t = sexp_of_list (sexp_of_pair sexp_of_string sexp_of_string) (to_list t) let t_of_sexp s = of_list (list_of_sexp (pair_of_sexp string_of_sexp string_of_sexp) s) let pp_hum ppf h = Format.fprintf ppf "%s" (h |> sexp_of_t |> Sexplib0.Sexp.to_string_hum)
null
https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ocaml-cohttp/cohttp/src/header.ml
ocaml
Grab "foo/bar" from " foo/bar ; charset=UTF-8" It should actually be [get] as the interresting value is actually the last. Only add a header if one doesnt already exist, e.g. from the app TODO: this is a protocol violation
{ { { Copyright ( c ) 2012 Anil Madhavapeddy < > * Copyright ( c ) 2011 - 2012 < > * Copyright ( c ) 2010 * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * } } } * Copyright (c) 2011-2012 Martin Jambon <> * Copyright (c) 2010 Mika Illouz * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) include Http.Header let media_type_re = let re = Re.Emacs.re ~case:true "[ \t]*\\([^ \t;]+\\)" in Re.(compile (seq [ start; re ])) let get_first_match _re s = try let subs = Re.exec ~pos:0 media_type_re s in let start, stop = Re.Group.offset subs 1 in Some (String.sub s start (stop - start)) with Not_found -> None let get_media_type headers = match get headers "content-type" with | Some s -> get_first_match media_type_re s | None -> None let get_acceptable_media_ranges headers = Accept.media_ranges (get_multi_concat ~list_value_only:true headers "accept") let get_acceptable_charsets headers = Accept.charsets (get_multi_concat ~list_value_only:true headers "accept-charset") let get_acceptable_encodings headers = Accept.encodings (get_multi_concat ~list_value_only:true headers "accept-encoding") let get_acceptable_languages headers = Accept.languages (get_multi_concat ~list_value_only:true headers "accept-language") Parse the transfer - encoding and content - length headers to * determine how to decode a body * determine how to decode a body *) let get_transfer_encoding headers = match get_multi_concat ~list_value_only:true headers "transfer-encoding" with | Some "chunked" -> Transfer.Chunked | Some _ | None -> ( match get_content_range headers with | Some len -> Transfer.Fixed len | None -> Transfer.Unknown) let add_transfer_encoding headers enc = let open Transfer in match (get_transfer_encoding headers, enc) with App has supplied a content length , so use that -> | Unknown, Chunked -> add headers "transfer-encoding" "chunked" | Unknown, Fixed len -> add headers "content-length" (Int64.to_string len) | Unknown, Unknown -> headers let add_authorization_req headers challenge = add headers "www-authenticate" (Auth.string_of_challenge challenge) let add_authorization headers cred = add headers "authorization" (Auth.string_of_credential cred) let get_authorization headers = match get headers "authorization" with | None -> None | Some v -> Some (Auth.credential_of_string v) let is_form headers = get_media_type headers = Some "application/x-www-form-urlencoded" let get_location headers = match get_location headers with | None -> None | Some u -> Some (Uri.of_string u) let get_links headers = List.rev (List.fold_left (fun list link_s -> List.rev_append (Link.of_string link_s) list) [] (get_multi headers "link")) let add_links headers links = add_multi headers "link" (List.map Link.to_string links) let user_agent = Printf.sprintf "ocaml-cohttp/%s" Conf.version let prepend_user_agent headers user_agent = let k = "user-agent" in match get headers k with | Some ua -> replace headers k (user_agent ^ " " ^ ua) | None -> add headers k user_agent let connection h = match get h "connection" with | Some v when v = "keep-alive" -> Some `Keep_alive | Some v when v = "close" -> Some `Close | Some x -> Some (`Unknown x) | _ -> None open Sexplib0.Sexp_conv let sexp_of_t t = sexp_of_list (sexp_of_pair sexp_of_string sexp_of_string) (to_list t) let t_of_sexp s = of_list (list_of_sexp (pair_of_sexp string_of_sexp string_of_sexp) s) let pp_hum ppf h = Format.fprintf ppf "%s" (h |> sexp_of_t |> Sexplib0.Sexp.to_string_hum)
9b39201ef23f25b5b0f491afeb5cee194a33fc0d99a699de1f868e9d6f6651db
2600hz-archive/whistle
j5_acctmgr.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 , VoIP INC %%% @doc %%% Handle serializing account access for crossbar accounts TODO : convert to gen_listener %%% @end Created : 16 Jul 2011 by < > %%%------------------------------------------------------------------- -module(j5_acctmgr). -behaviour(gen_server). %% API -export([start_link/1, authz_trunk/3, authz_trunk/4, known_calls/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("jonny5.hrl"). -define(SERVER, ?MODULE). -record(state, { my_q = undefined :: binary() | undefined ,is_amqp_up = true :: boolean() ,cache = undefined :: undefined | pid() ,cache_ref = make_ref() :: reference() ,acct_id = <<>> :: binary() ,acct_rev = <<>> :: binary() ,acct_type = account :: account | ts ,max_two_way = 0 :: non_neg_integer() ,max_inbound = 0 :: non_neg_integer() ,two_way = 0 :: non_neg_integer() ,inbound = 0 :: non_neg_integer() ,prepay = 0.0 :: float() ,trunks_in_use = dict:new() :: dict() %% {CallID, Type :: inbound | two_way} }). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- -spec start_link/1 :: (AcctID) -> {ok, pid()} | ignore | {error, term()} when AcctID :: binary(). start_link(AcctID) -> gen_server:start_link(?MODULE, [AcctID], []). -spec authz_trunk/3 :: (Pid, JObj, CallDir) -> {boolean(), proplist()} when Pid :: pid(), JObj :: json_object(), CallDir :: inbound | outbound. authz_trunk(Pid, JObj, CallDir) when is_pid(Pid) -> gen_server:call(Pid, {authz, JObj, CallDir}). -spec authz_trunk/4 :: (AcctID, JObj, CallDir, CPid) -> {boolean(), proplist()} when AcctID :: binary(), JObj :: json_object(), CallDir :: inbound | outbound, CPid :: pid(). authz_trunk(AcctID, JObj, CallDir, CPid) -> case wh_cache:fetch_local(CPid, {j5_authz, AcctID}) of {ok, AcctPID} -> case erlang:is_process_alive(AcctPID) of true -> ?LOG_SYS("Account(~s) AuthZ proc ~p found", [AcctID, AcctPID]), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir); false -> ?LOG_SYS("Account(~s) AuthZ proc ~p not alive", [AcctID, AcctPID]), {ok, AcctPID} = jonny5_acct_sup:start_proc(AcctID), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir) end; {error, not_found} -> ?LOG_SYS("No AuthZ proc for account ~s, starting", [AcctID]), try {ok, AcctPID} = jonny5_acct_sup:start_proc(AcctID), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir) catch E:R -> ST = erlang:get_stacktrace(), ?LOG_SYS("Error: ~p: ~p", [E, R]), _ = [ ?LOG_SYS("Stacktrace: ~p", [ST1]) || ST1 <- ST], {false, []} end end. known_calls(Pid) when is_pid(Pid) -> gen_server:call(Pid, known_calls); known_calls(AcctID) when is_binary(AcctID) -> case wh_cache:fetch_local(whereis(j5_cache), {j5_authz, AcctID}) of {error, _}=E -> E; {ok, AcctPid} -> known_calls(AcctPid) end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([AcctID]) -> CPid = whereis(j5_cache), Ref = erlang:monitor(process, CPid), 1 day Q = amqp_util:new_queue(), case get_trunks_available(AcctID, account) of {error, not_found} -> ?LOG_SYS("No account found for ~s", [AcctID]), {stop, no_account}; {TwoWay, Inbound, Prepay, ts} -> ?LOG_SYS("Init for ts ~s complete", [AcctID]), couch_mgr:add_change_handler(<<"ts">>, AcctID), {ok, Rev} = couch_mgr:lookup_doc_rev(<<"ts">>, AcctID), {ok, #state{my_q=Q, is_amqp_up=is_binary(Q) ,cache=CPid, cache_ref=Ref, prepay=Prepay ,two_way=TwoWay, inbound=Inbound ,max_two_way=TwoWay, max_inbound=Inbound ,acct_rev=Rev, acct_id=AcctID, acct_type=ts }}; {TwoWay, Inbound, Prepay, account} -> {ok, #state{my_q=Q, is_amqp_up=is_binary(Q) ,cache=CPid, cache_ref=Ref, prepay=Prepay ,two_way=TwoWay, inbound=Inbound ,max_two_way=TwoWay, max_inbound=Inbound ,acct_id=AcctID, acct_type=account }} end. %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(known_calls, _, #state{trunks_in_use=Dict}=State) -> {reply, dict:to_list(Dict), State}; %% pull from inbound, then two_way, then prepay handle_call({authz, JObj, inbound}, _From, #state{}=State) -> CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG_START(CallID, "Authorizing inbound call...", []), ToDID = case binary:split(wh_json:get_value(<<"To">>, JObj), <<"@">>) of [<<"nouser">>, _] -> [RUser, _] = binary:split(wh_json:get_value(<<"Request">>, JObj, <<"nouser">>), <<"@">>), wh_util:to_e164(RUser); [ToUser, _] -> wh_util:to_e164(ToUser) end, ?LOG("ToDID: ~s", [ToDID]), {Resp, State1} = case is_us48(ToDID) of true -> try_inbound_then_twoway(CallID, State); false -> try_prepay(CallID, State) end, {reply, Resp, State1, hibernate}; handle_call({authz, JObj, outbound}, _From, State) -> CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG_START(CallID, "Authorizing outbound call...", []), ToDID = case binary:split(wh_json:get_value(<<"To">>, JObj), <<"@">>) of [<<"nouser">>, _] -> [RUser, _] = binary:split(wh_json:get_value(<<"Request">>, JObj, <<"nouser">>), <<"@">>), wh_util:to_e164(RUser); [ToUser, _] -> wh_util:to_e164(ToUser) end, ?LOG("ToDID: ~s", [ToDID]), {Resp, State1} = case is_us48(ToDID) of true -> try_twoway(CallID, State); false -> try_prepay(CallID, State) end, {reply, Resp, State1, hibernate}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info({_, #amqp_msg{payload=Payload}}, #state{my_q=Q, two_way=Two, inbound=In, trunks_in_use=Dict ,max_inbound=MaxIn, max_two_way=MaxTwo }=State) -> JObj = mochijson2:decode(Payload), CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG(CallID, "Recv JSON payload: ~s", [Payload]), case process_call_event(CallID, JObj, Dict) of {release, inbound, Dict1} -> ?LOG_END(CallID, "Releasing inbound trunk", []), unmonitor_call(Q, CallID), NewIn = case (In+1) of I when I > MaxIn -> MaxIn; I -> I end, {noreply, State#state{inbound=NewIn, trunks_in_use=Dict1}, hibernate}; {release, twoway, Dict2} -> ?LOG_END(CallID, "Releasing two-way trunk", []), unmonitor_call(Q, CallID), NewTwo = case (Two+1) of T when T > MaxTwo -> MaxTwo; T -> T end, {noreply, State#state{two_way=NewTwo, trunks_in_use=Dict2}, hibernate}; ignore -> ?LOG_END(CallID, "Ignoring event", []), {noreply, State} end; handle_info({document_changes, AcctID, Changes}, #state{acct_rev=Rev, acct_id=AcctID, acct_type=AcctType}=State) -> ?LOG_SYS("change to account ~s to be processed", [AcctID]), State1 = lists:foldl(fun(Prop, State0) -> case props:get_value(<<"rev">>, Prop) of undefined -> State0; Rev -> State0; _NewRev -> ?LOG_SYS("Updating account ~s from ~s to ~s", [AcctID, Rev, _NewRev]), {Two, In, _, _} = get_trunks_available(AcctID, AcctType), State0#state{max_two_way=Two, max_inbound=In} end end, State, Changes), {noreply, State1, hibernate}; handle_info({document_deleted, DocID}, State) -> ?LOG_SYS("account ~s deleted, going down", [DocID]), {stop, normal, State}; handle_info(#'basic.consume_ok'{}, State) -> {noreply, State}; handle_info(_Info, State) -> ?LOG_SYS("Unhandled message: ~p", [_Info]), {noreply, State}. %%-------------------------------------------------------------------- @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 . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== -spec get_trunks_available/2 :: (AcctID, Type) -> {error, not_found} | {non_neg_integer(), non_neg_integer(), float(), account | ts} when AcctID :: binary(), Type :: account | ts. get_trunks_available(AcctID, account) -> case couch_mgr:open_doc(whapps_util:get_db_name(AcctID, encoded), AcctID) of {error, not_found} -> ?LOG_SYS("Account ~s not found, trying ts", [AcctID]), get_trunks_available(AcctID, ts); {ok, JObj} -> Trunks = wh_util:to_integer(wh_json:get_value(<<"trunks">>, JObj, 0)), InboundTrunks = wh_util:to_integer(wh_json:get_value(<<"inbound_trunks">>, JObj, 0)), Prepay = wh_util:to_float(wh_json:get_value(<<"prepay">>, JObj, 0.0)), %% Balance = ?DOLLARS_TO_UNITS(), ?LOG_SYS("Found trunk levels for ~s: ~b two way, ~b inbound, and $ ~p prepay", [AcctID, Trunks, InboundTrunks, Prepay]), {Trunks, InboundTrunks, Prepay, account} end; get_trunks_available(AcctID, ts) -> case couch_mgr:open_doc(<<"ts">>, AcctID) of {error, not_found}=E -> ?LOG_SYS("No account found in ts: ~s", [AcctID]), E; {ok, JObj} -> Acct = wh_json:get_value(<<"account">>, JObj, ?EMPTY_JSON_OBJECT), Credits = wh_json:get_value(<<"credits">>, Acct, ?EMPTY_JSON_OBJECT), Trunks = wh_util:to_integer(wh_json:get_value(<<"trunks">>, Acct, 0)), InboundTrunks = wh_util:to_integer(wh_json:get_value(<<"inbound_trunks">>, Acct, 0)), Prepay = wh_util:to_float(wh_json:get_value(<<"prepay">>, Credits, 0.0)), %% Balance = ?DOLLARS_TO_UNITS(), ?LOG_SYS("Found trunk levels for ~s: ~b two way, ~b inbound, and $ ~p prepay", [AcctID, Trunks, InboundTrunks, Prepay]), {Trunks, InboundTrunks, Prepay, ts} end. -spec try_inbound_then_twoway/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_inbound_then_twoway(CallID, State) -> case try_inbound(CallID, State) of {{true, _}, _}=Resp -> ?LOG_END(CallID, "Inbound call authorized with inbound trunk", []), Resp; {{false, _}, State2} -> case try_twoway(CallID, State2) of {{true, _}, _}=Resp -> ?LOG_END(CallID, "Inbound call authorized using a two-way trunk", []), Resp; {{false, _}, State3} -> try_prepay(CallID, State3) end end. -spec try_twoway/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_twoway(_CallID, #state{two_way=T}=State) when T < 1 -> ?LOG_SYS(_CallID, "Failed to authz a two-way trunk", []), {{false, []}, State#state{two_way=0}}; try_twoway(CallID, #state{my_q=Q, two_way=Two, trunks_in_use=Dict}=State) -> ?LOG_SYS(CallID, "Authz a two-way trunk", []), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"two_way">>}]} ,State#state{two_way=Two-1, trunks_in_use=dict:store(CallID, twoway, Dict)} }. -spec try_inbound/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_inbound(_CallID, #state{inbound=I}=State) when I < 1 -> ?LOG_SYS(_CallID, "Failed to authz an inbound_only trunk", []), {{false, []}, State#state{inbound=0}}; try_inbound(CallID, #state{my_q=Q, inbound=In, trunks_in_use=Dict}=State) -> ?LOG_SYS(CallID, "Authz an inbound_only trunk", []), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"inbound">>}]} ,State#state{inbound=In-1, trunks_in_use=dict:store(CallID, inbound, Dict)} }. -spec try_prepay/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_prepay(_CallID, #state{prepay=Pre}=State) when Pre =< 0.0 -> ?LOG_SYS(_CallID, "Failed to authz a per_min trunk", []), {{false, [{<<"Error">>, <<"Insufficient Funds">>}]}, State}; try_prepay(CallID, #state{acct_id=AcctId, my_q=Q, prepay=_Pre, trunks_in_use=Dict}=State) -> case jonny5_listener:is_blacklisted(AcctId) of {true, Reason} -> ?LOG_SYS(CallID, "Authz false for per_min: ~s", [Reason]), {{false, [{<<"Error">>, Reason}]}, State}; false -> ?LOG_SYS(CallID, "Authz a per_min trunk with $~p prepay", [_Pre]), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"per_min">>}]} ,State#state{trunks_in_use=dict:store(CallID, per_min, Dict)} } end. -spec monitor_call/2 :: (Q, CallID) -> ok when Q :: binary(), CallID :: binary(). monitor_call(Q, CallID) -> _ = amqp_util:bind_q_to_callevt(Q, CallID), _ = amqp_util:bind_q_to_callevt(Q, CallID, cdr), ?LOG(CallID, "Monitoring with ~s", [Q]), amqp_util:basic_consume(Q, [{exclusive, false}]). -spec unmonitor_call/2 :: (Q, CallID) -> ok when Q :: binary(), CallID :: binary(). unmonitor_call(Q, CallID) -> amqp_util:unbind_q_from_callevt(Q, CallID), amqp_util:unbind_q_from_callevt(Q, CallID, cdr), ?LOG(CallID, "Un-monitoring", []). -spec process_call_event/3 :: (CallID, JObj, Dict) -> ignore | {release, twoway | inbound, dict()} when CallID :: binary(), JObj :: json_object(), Dict :: dict(). process_call_event(CallID, JObj, Dict) -> case { wh_json:get_value(<<"Application-Name">>, JObj) ,wh_json:get_value(<<"Event-Name">>, JObj) ,wh_json:get_value(<<"Event-Category">>, JObj) } of { <<"bridge">>, <<"CHANNEL_EXECUTE_COMPLETE">>, <<"call_event">> } -> ?LOG(CallID, "Bridge event received", []), case wh_json:get_value(<<"Application-Response">>, JObj) of <<"SUCCESS">> -> ?LOG(CallID, "Bridge event successful", []), ignore; Cause -> ?LOG("Failed to bridge: ~s", [Cause]), release_trunk(CallID, Dict) end; { _, <<"CHANNEL_HANGUP">>, <<"call_event">> } -> ?LOG(CallID, "Channel hungup", []), release_trunk(CallID, Dict); { _, _, <<"error">> } -> ?LOG(CallID, "Execution failed", []), release_trunk(CallID, Dict); {_, <<"CHANNEL_HANGUP_COMPLETE">>, <<"call_event">>} -> ?LOG(CallID, "Channel hungup complete", []), release_trunk(CallID, Dict); { _, <<"cdr">>, <<"call_detail">> } -> ?LOG(CallID, "CDR received", []), release_trunk(CallID, Dict); _E -> ?LOG("Unhandled call event: ~p", [_E]), ignore end. -spec release_trunk/2 :: (CallID, Dict) -> ignore | {release, twoway | inbound, dict()} when CallID :: binary(), Dict :: dict(). release_trunk(CallID, Dict) -> case dict:find(CallID, Dict) of error -> ?LOG_SYS(CallID, "Call is unknown to us", []), ignore; {ok, TrunkType} -> {release, TrunkType, dict:erase(CallID, Dict)} end. Match +1XXXYYYZZZZ as US-48 ; all others are not is_us48(<<"+1", Rest/binary>>) when erlang:byte_size(Rest) =:= 10 -> true; %% extension dialing is_us48(Bin) when erlang:byte_size(Bin) < 7 -> true; is_us48(_) -> false.
null
https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/whistle_apps/apps/jonny5/src/j5_acctmgr.erl
erlang
------------------------------------------------------------------- @doc Handle serializing account access for crossbar accounts @end ------------------------------------------------------------------- API gen_server callbacks {CallID, Type :: inbound | two_way} =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- pull from inbound, then two_way, then prepay -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @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 Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== =================================================================== Balance = ?DOLLARS_TO_UNITS(), Balance = ?DOLLARS_TO_UNITS(), extension dialing
@author < > ( C ) 2011 , VoIP INC TODO : convert to gen_listener Created : 16 Jul 2011 by < > -module(j5_acctmgr). -behaviour(gen_server). -export([start_link/1, authz_trunk/3, authz_trunk/4, known_calls/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("jonny5.hrl"). -define(SERVER, ?MODULE). -record(state, { my_q = undefined :: binary() | undefined ,is_amqp_up = true :: boolean() ,cache = undefined :: undefined | pid() ,cache_ref = make_ref() :: reference() ,acct_id = <<>> :: binary() ,acct_rev = <<>> :: binary() ,acct_type = account :: account | ts ,max_two_way = 0 :: non_neg_integer() ,max_inbound = 0 :: non_neg_integer() ,two_way = 0 :: non_neg_integer() ,inbound = 0 :: non_neg_integer() ,prepay = 0.0 :: float() }). ( ) - > { ok , Pid } | ignore | { error , Error } -spec start_link/1 :: (AcctID) -> {ok, pid()} | ignore | {error, term()} when AcctID :: binary(). start_link(AcctID) -> gen_server:start_link(?MODULE, [AcctID], []). -spec authz_trunk/3 :: (Pid, JObj, CallDir) -> {boolean(), proplist()} when Pid :: pid(), JObj :: json_object(), CallDir :: inbound | outbound. authz_trunk(Pid, JObj, CallDir) when is_pid(Pid) -> gen_server:call(Pid, {authz, JObj, CallDir}). -spec authz_trunk/4 :: (AcctID, JObj, CallDir, CPid) -> {boolean(), proplist()} when AcctID :: binary(), JObj :: json_object(), CallDir :: inbound | outbound, CPid :: pid(). authz_trunk(AcctID, JObj, CallDir, CPid) -> case wh_cache:fetch_local(CPid, {j5_authz, AcctID}) of {ok, AcctPID} -> case erlang:is_process_alive(AcctPID) of true -> ?LOG_SYS("Account(~s) AuthZ proc ~p found", [AcctID, AcctPID]), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir); false -> ?LOG_SYS("Account(~s) AuthZ proc ~p not alive", [AcctID, AcctPID]), {ok, AcctPID} = jonny5_acct_sup:start_proc(AcctID), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir) end; {error, not_found} -> ?LOG_SYS("No AuthZ proc for account ~s, starting", [AcctID]), try {ok, AcctPID} = jonny5_acct_sup:start_proc(AcctID), j5_acctmgr:authz_trunk(AcctPID, JObj, CallDir) catch E:R -> ST = erlang:get_stacktrace(), ?LOG_SYS("Error: ~p: ~p", [E, R]), _ = [ ?LOG_SYS("Stacktrace: ~p", [ST1]) || ST1 <- ST], {false, []} end end. known_calls(Pid) when is_pid(Pid) -> gen_server:call(Pid, known_calls); known_calls(AcctID) when is_binary(AcctID) -> case wh_cache:fetch_local(whereis(j5_cache), {j5_authz, AcctID}) of {error, _}=E -> E; {ok, AcctPid} -> known_calls(AcctPid) end. @private ) - > { ok , State } | { ok , State , Timeout } | init([AcctID]) -> CPid = whereis(j5_cache), Ref = erlang:monitor(process, CPid), 1 day Q = amqp_util:new_queue(), case get_trunks_available(AcctID, account) of {error, not_found} -> ?LOG_SYS("No account found for ~s", [AcctID]), {stop, no_account}; {TwoWay, Inbound, Prepay, ts} -> ?LOG_SYS("Init for ts ~s complete", [AcctID]), couch_mgr:add_change_handler(<<"ts">>, AcctID), {ok, Rev} = couch_mgr:lookup_doc_rev(<<"ts">>, AcctID), {ok, #state{my_q=Q, is_amqp_up=is_binary(Q) ,cache=CPid, cache_ref=Ref, prepay=Prepay ,two_way=TwoWay, inbound=Inbound ,max_two_way=TwoWay, max_inbound=Inbound ,acct_rev=Rev, acct_id=AcctID, acct_type=ts }}; {TwoWay, Inbound, Prepay, account} -> {ok, #state{my_q=Q, is_amqp_up=is_binary(Q) ,cache=CPid, cache_ref=Ref, prepay=Prepay ,two_way=TwoWay, inbound=Inbound ,max_two_way=TwoWay, max_inbound=Inbound ,acct_id=AcctID, acct_type=account }} end. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(known_calls, _, #state{trunks_in_use=Dict}=State) -> {reply, dict:to_list(Dict), State}; handle_call({authz, JObj, inbound}, _From, #state{}=State) -> CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG_START(CallID, "Authorizing inbound call...", []), ToDID = case binary:split(wh_json:get_value(<<"To">>, JObj), <<"@">>) of [<<"nouser">>, _] -> [RUser, _] = binary:split(wh_json:get_value(<<"Request">>, JObj, <<"nouser">>), <<"@">>), wh_util:to_e164(RUser); [ToUser, _] -> wh_util:to_e164(ToUser) end, ?LOG("ToDID: ~s", [ToDID]), {Resp, State1} = case is_us48(ToDID) of true -> try_inbound_then_twoway(CallID, State); false -> try_prepay(CallID, State) end, {reply, Resp, State1, hibernate}; handle_call({authz, JObj, outbound}, _From, State) -> CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG_START(CallID, "Authorizing outbound call...", []), ToDID = case binary:split(wh_json:get_value(<<"To">>, JObj), <<"@">>) of [<<"nouser">>, _] -> [RUser, _] = binary:split(wh_json:get_value(<<"Request">>, JObj, <<"nouser">>), <<"@">>), wh_util:to_e164(RUser); [ToUser, _] -> wh_util:to_e164(ToUser) end, ?LOG("ToDID: ~s", [ToDID]), {Resp, State1} = case is_us48(ToDID) of true -> try_twoway(CallID, State); false -> try_prepay(CallID, State) end, {reply, Resp, State1, hibernate}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({_, #amqp_msg{payload=Payload}}, #state{my_q=Q, two_way=Two, inbound=In, trunks_in_use=Dict ,max_inbound=MaxIn, max_two_way=MaxTwo }=State) -> JObj = mochijson2:decode(Payload), CallID = wh_json:get_value(<<"Call-ID">>, JObj), ?LOG(CallID, "Recv JSON payload: ~s", [Payload]), case process_call_event(CallID, JObj, Dict) of {release, inbound, Dict1} -> ?LOG_END(CallID, "Releasing inbound trunk", []), unmonitor_call(Q, CallID), NewIn = case (In+1) of I when I > MaxIn -> MaxIn; I -> I end, {noreply, State#state{inbound=NewIn, trunks_in_use=Dict1}, hibernate}; {release, twoway, Dict2} -> ?LOG_END(CallID, "Releasing two-way trunk", []), unmonitor_call(Q, CallID), NewTwo = case (Two+1) of T when T > MaxTwo -> MaxTwo; T -> T end, {noreply, State#state{two_way=NewTwo, trunks_in_use=Dict2}, hibernate}; ignore -> ?LOG_END(CallID, "Ignoring event", []), {noreply, State} end; handle_info({document_changes, AcctID, Changes}, #state{acct_rev=Rev, acct_id=AcctID, acct_type=AcctType}=State) -> ?LOG_SYS("change to account ~s to be processed", [AcctID]), State1 = lists:foldl(fun(Prop, State0) -> case props:get_value(<<"rev">>, Prop) of undefined -> State0; Rev -> State0; _NewRev -> ?LOG_SYS("Updating account ~s from ~s to ~s", [AcctID, Rev, _NewRev]), {Two, In, _, _} = get_trunks_available(AcctID, AcctType), State0#state{max_two_way=Two, max_inbound=In} end end, State, Changes), {noreply, State1, hibernate}; handle_info({document_deleted, DocID}, State) -> ?LOG_SYS("account ~s deleted, going down", [DocID]), {stop, normal, State}; handle_info(#'basic.consume_ok'{}, State) -> {noreply, State}; handle_info(_Info, State) -> ?LOG_SYS("Unhandled message: ~p", [_Info]), {noreply, State}. @private with . The return value is ignored . , State ) - > void ( ) terminate(_Reason, _State) -> ok. @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions -spec get_trunks_available/2 :: (AcctID, Type) -> {error, not_found} | {non_neg_integer(), non_neg_integer(), float(), account | ts} when AcctID :: binary(), Type :: account | ts. get_trunks_available(AcctID, account) -> case couch_mgr:open_doc(whapps_util:get_db_name(AcctID, encoded), AcctID) of {error, not_found} -> ?LOG_SYS("Account ~s not found, trying ts", [AcctID]), get_trunks_available(AcctID, ts); {ok, JObj} -> Trunks = wh_util:to_integer(wh_json:get_value(<<"trunks">>, JObj, 0)), InboundTrunks = wh_util:to_integer(wh_json:get_value(<<"inbound_trunks">>, JObj, 0)), Prepay = wh_util:to_float(wh_json:get_value(<<"prepay">>, JObj, 0.0)), ?LOG_SYS("Found trunk levels for ~s: ~b two way, ~b inbound, and $ ~p prepay", [AcctID, Trunks, InboundTrunks, Prepay]), {Trunks, InboundTrunks, Prepay, account} end; get_trunks_available(AcctID, ts) -> case couch_mgr:open_doc(<<"ts">>, AcctID) of {error, not_found}=E -> ?LOG_SYS("No account found in ts: ~s", [AcctID]), E; {ok, JObj} -> Acct = wh_json:get_value(<<"account">>, JObj, ?EMPTY_JSON_OBJECT), Credits = wh_json:get_value(<<"credits">>, Acct, ?EMPTY_JSON_OBJECT), Trunks = wh_util:to_integer(wh_json:get_value(<<"trunks">>, Acct, 0)), InboundTrunks = wh_util:to_integer(wh_json:get_value(<<"inbound_trunks">>, Acct, 0)), Prepay = wh_util:to_float(wh_json:get_value(<<"prepay">>, Credits, 0.0)), ?LOG_SYS("Found trunk levels for ~s: ~b two way, ~b inbound, and $ ~p prepay", [AcctID, Trunks, InboundTrunks, Prepay]), {Trunks, InboundTrunks, Prepay, ts} end. -spec try_inbound_then_twoway/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_inbound_then_twoway(CallID, State) -> case try_inbound(CallID, State) of {{true, _}, _}=Resp -> ?LOG_END(CallID, "Inbound call authorized with inbound trunk", []), Resp; {{false, _}, State2} -> case try_twoway(CallID, State2) of {{true, _}, _}=Resp -> ?LOG_END(CallID, "Inbound call authorized using a two-way trunk", []), Resp; {{false, _}, State3} -> try_prepay(CallID, State3) end end. -spec try_twoway/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_twoway(_CallID, #state{two_way=T}=State) when T < 1 -> ?LOG_SYS(_CallID, "Failed to authz a two-way trunk", []), {{false, []}, State#state{two_way=0}}; try_twoway(CallID, #state{my_q=Q, two_way=Two, trunks_in_use=Dict}=State) -> ?LOG_SYS(CallID, "Authz a two-way trunk", []), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"two_way">>}]} ,State#state{two_way=Two-1, trunks_in_use=dict:store(CallID, twoway, Dict)} }. -spec try_inbound/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_inbound(_CallID, #state{inbound=I}=State) when I < 1 -> ?LOG_SYS(_CallID, "Failed to authz an inbound_only trunk", []), {{false, []}, State#state{inbound=0}}; try_inbound(CallID, #state{my_q=Q, inbound=In, trunks_in_use=Dict}=State) -> ?LOG_SYS(CallID, "Authz an inbound_only trunk", []), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"inbound">>}]} ,State#state{inbound=In-1, trunks_in_use=dict:store(CallID, inbound, Dict)} }. -spec try_prepay/2 :: (CallID, State) -> {{boolean(), proplist()}, #state{}} when CallID :: binary(), State :: #state{}. try_prepay(_CallID, #state{prepay=Pre}=State) when Pre =< 0.0 -> ?LOG_SYS(_CallID, "Failed to authz a per_min trunk", []), {{false, [{<<"Error">>, <<"Insufficient Funds">>}]}, State}; try_prepay(CallID, #state{acct_id=AcctId, my_q=Q, prepay=_Pre, trunks_in_use=Dict}=State) -> case jonny5_listener:is_blacklisted(AcctId) of {true, Reason} -> ?LOG_SYS(CallID, "Authz false for per_min: ~s", [Reason]), {{false, [{<<"Error">>, Reason}]}, State}; false -> ?LOG_SYS(CallID, "Authz a per_min trunk with $~p prepay", [_Pre]), monitor_call(Q, CallID), {{true, [{<<"Trunk-Type">>, <<"per_min">>}]} ,State#state{trunks_in_use=dict:store(CallID, per_min, Dict)} } end. -spec monitor_call/2 :: (Q, CallID) -> ok when Q :: binary(), CallID :: binary(). monitor_call(Q, CallID) -> _ = amqp_util:bind_q_to_callevt(Q, CallID), _ = amqp_util:bind_q_to_callevt(Q, CallID, cdr), ?LOG(CallID, "Monitoring with ~s", [Q]), amqp_util:basic_consume(Q, [{exclusive, false}]). -spec unmonitor_call/2 :: (Q, CallID) -> ok when Q :: binary(), CallID :: binary(). unmonitor_call(Q, CallID) -> amqp_util:unbind_q_from_callevt(Q, CallID), amqp_util:unbind_q_from_callevt(Q, CallID, cdr), ?LOG(CallID, "Un-monitoring", []). -spec process_call_event/3 :: (CallID, JObj, Dict) -> ignore | {release, twoway | inbound, dict()} when CallID :: binary(), JObj :: json_object(), Dict :: dict(). process_call_event(CallID, JObj, Dict) -> case { wh_json:get_value(<<"Application-Name">>, JObj) ,wh_json:get_value(<<"Event-Name">>, JObj) ,wh_json:get_value(<<"Event-Category">>, JObj) } of { <<"bridge">>, <<"CHANNEL_EXECUTE_COMPLETE">>, <<"call_event">> } -> ?LOG(CallID, "Bridge event received", []), case wh_json:get_value(<<"Application-Response">>, JObj) of <<"SUCCESS">> -> ?LOG(CallID, "Bridge event successful", []), ignore; Cause -> ?LOG("Failed to bridge: ~s", [Cause]), release_trunk(CallID, Dict) end; { _, <<"CHANNEL_HANGUP">>, <<"call_event">> } -> ?LOG(CallID, "Channel hungup", []), release_trunk(CallID, Dict); { _, _, <<"error">> } -> ?LOG(CallID, "Execution failed", []), release_trunk(CallID, Dict); {_, <<"CHANNEL_HANGUP_COMPLETE">>, <<"call_event">>} -> ?LOG(CallID, "Channel hungup complete", []), release_trunk(CallID, Dict); { _, <<"cdr">>, <<"call_detail">> } -> ?LOG(CallID, "CDR received", []), release_trunk(CallID, Dict); _E -> ?LOG("Unhandled call event: ~p", [_E]), ignore end. -spec release_trunk/2 :: (CallID, Dict) -> ignore | {release, twoway | inbound, dict()} when CallID :: binary(), Dict :: dict(). release_trunk(CallID, Dict) -> case dict:find(CallID, Dict) of error -> ?LOG_SYS(CallID, "Call is unknown to us", []), ignore; {ok, TrunkType} -> {release, TrunkType, dict:erase(CallID, Dict)} end. Match +1XXXYYYZZZZ as US-48 ; all others are not is_us48(<<"+1", Rest/binary>>) when erlang:byte_size(Rest) =:= 10 -> true; is_us48(Bin) when erlang:byte_size(Bin) < 7 -> true; is_us48(_) -> false.
68f8eef2e67408905c83d9e55422059351a2f14c1cca21e556fabca557274914
skrah/minicaml
Unify.mli
* Copyright ( c ) 2015 . All rights reserved . * * This file is distributed under the terms of the Q Public License * version 1.0 . * Copyright (c) 2015 Stefan Krah. All rights reserved. * * This file is distributed under the terms of the Q Public License * version 1.0. *) exception ValidationError exception CyclicType module Make : functor (ModuleState : ModuleState.S) -> sig module Tvar_env : sig type key = ModuleState.Tyvar.t type 'a t = 'a Map.Make(ModuleState.Tyvar).t val empty : 'a t val is_empty : 'a t -> bool val mem : key -> 'a t -> bool val add : key -> 'a -> 'a t -> 'a t val singleton : key -> 'a -> 'a t val remove : key -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val for_all : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val cardinal : 'a t -> int val bindings : 'a t -> (key * 'a) list val min_binding : 'a t -> key * 'a val max_binding : 'a t -> key * 'a val choose : 'a t -> key * 'a val split : key -> 'a t -> 'a t * 'a option * 'a t val find : key -> 'a t -> 'a val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t end val add : 'a Tvar_env.t -> Tvar_env.key -> 'a -> 'a Tvar_env.t val find_env : 'a Tvar_env.t -> Tvar_env.key -> 'a option val tmeta_of_var : int -> ModuleState.Tyvar.t -> Types.t val validate : bool -> Types.t -> unit val subst : Types.t Tvar_env.t -> Types.t -> Types.t val subst_with_mapping : Tvar_env.key list -> Types.t list -> Types.t -> Types.t val rename_params : Tvar_env.key list -> Types.t -> Symbol.Tyvar.t list * Types.t val subst_with_meta : int -> Tvar_env.key list -> Types.t -> Types.t val expand : Types.t -> Types.t val expand_links : Types.t -> Types.t val occurs : Types.tmeta ref -> Symbol.Tymeta.t -> int -> Types.t -> unit val unify : Types.t -> Types.t -> unit val generalize : int -> Types.t -> Types.t val instantiate : int -> Types.t -> Types.t val requantify : Types.t -> Symbol.Tyvar.t list * Types.t val compress : Types.t -> Types.t val repr : ?closure:bool -> ?fullname:bool -> Types.t -> string val short_repr : ?closure:bool -> ?fullname:bool -> Types.t -> string val tfun_repr : ?closure:bool -> ?fullname:bool -> Types.tfun -> string * string end
null
https://raw.githubusercontent.com/skrah/minicaml/e5f5cad7fdbcfc11561f717042fae73fa743823f/Unify.mli
ocaml
* Copyright ( c ) 2015 . All rights reserved . * * This file is distributed under the terms of the Q Public License * version 1.0 . * Copyright (c) 2015 Stefan Krah. All rights reserved. * * This file is distributed under the terms of the Q Public License * version 1.0. *) exception ValidationError exception CyclicType module Make : functor (ModuleState : ModuleState.S) -> sig module Tvar_env : sig type key = ModuleState.Tyvar.t type 'a t = 'a Map.Make(ModuleState.Tyvar).t val empty : 'a t val is_empty : 'a t -> bool val mem : key -> 'a t -> bool val add : key -> 'a -> 'a t -> 'a t val singleton : key -> 'a -> 'a t val remove : key -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val for_all : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val cardinal : 'a t -> int val bindings : 'a t -> (key * 'a) list val min_binding : 'a t -> key * 'a val max_binding : 'a t -> key * 'a val choose : 'a t -> key * 'a val split : key -> 'a t -> 'a t * 'a option * 'a t val find : key -> 'a t -> 'a val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t end val add : 'a Tvar_env.t -> Tvar_env.key -> 'a -> 'a Tvar_env.t val find_env : 'a Tvar_env.t -> Tvar_env.key -> 'a option val tmeta_of_var : int -> ModuleState.Tyvar.t -> Types.t val validate : bool -> Types.t -> unit val subst : Types.t Tvar_env.t -> Types.t -> Types.t val subst_with_mapping : Tvar_env.key list -> Types.t list -> Types.t -> Types.t val rename_params : Tvar_env.key list -> Types.t -> Symbol.Tyvar.t list * Types.t val subst_with_meta : int -> Tvar_env.key list -> Types.t -> Types.t val expand : Types.t -> Types.t val expand_links : Types.t -> Types.t val occurs : Types.tmeta ref -> Symbol.Tymeta.t -> int -> Types.t -> unit val unify : Types.t -> Types.t -> unit val generalize : int -> Types.t -> Types.t val instantiate : int -> Types.t -> Types.t val requantify : Types.t -> Symbol.Tyvar.t list * Types.t val compress : Types.t -> Types.t val repr : ?closure:bool -> ?fullname:bool -> Types.t -> string val short_repr : ?closure:bool -> ?fullname:bool -> Types.t -> string val tfun_repr : ?closure:bool -> ?fullname:bool -> Types.tfun -> string * string end
17b142a1cb225978ca13d2159457dcb110204ed4d39a7ff9ac37711899c47bf7
gildor478/ocaml-fileutils
FileUtilREADLINK.ml
(******************************************************************************) (* ocaml-fileutils: files and filenames common operations *) (* *) Copyright ( C ) 2003 - 2014 , (* *) (* This library is free software; you can redistribute it and/or modify it *) (* under the terms of the GNU Lesser General Public License as published by *) the Free Software Foundation ; either version 2.1 of the License , or ( at (* your option) any later version, with the OCaml static compilation *) (* exception. *) (* *) (* This library is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file *) (* COPYING for more details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) open FileUtilTypes open FilePath open FileUtilMisc open FileUtilPWD open FileUtilTEST let readlink fln = let all_upper_dir fln = let rec all_upper_dir_aux lst fln = let dir = dirname fln in match lst with | prev_dir :: _ when prev_dir = dir -> lst | _ -> all_upper_dir_aux (dir :: lst) dir in all_upper_dir_aux [fln] fln in let ctst = let st_opt, stL_opt = None, None in compile_filter ?st_opt ?stL_opt Is_link in let rec readlink_aux already_read fln = let newly_read = prevent_recursion already_read fln in let dirs = all_upper_dir fln in try let src_link = List.find ctst (List.rev dirs) in let dst_link = Unix.readlink src_link in let real_link = if is_relative dst_link then reduce (concat (dirname src_link) dst_link) else reduce dst_link in readlink_aux newly_read (reparent src_link real_link fln) with Not_found -> fln in readlink_aux SetFilename.empty (make_absolute (pwd ()) fln)
null
https://raw.githubusercontent.com/gildor478/ocaml-fileutils/9ad8d2ee342c551391f2a9873de01982d24b36d5/src/lib/fileutils/FileUtilREADLINK.ml
ocaml
**************************************************************************** ocaml-fileutils: files and filenames common operations This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by your option) any later version, with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more details. ****************************************************************************
Copyright ( C ) 2003 - 2014 , the Free Software Foundation ; either version 2.1 of the License , or ( at You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA open FileUtilTypes open FilePath open FileUtilMisc open FileUtilPWD open FileUtilTEST let readlink fln = let all_upper_dir fln = let rec all_upper_dir_aux lst fln = let dir = dirname fln in match lst with | prev_dir :: _ when prev_dir = dir -> lst | _ -> all_upper_dir_aux (dir :: lst) dir in all_upper_dir_aux [fln] fln in let ctst = let st_opt, stL_opt = None, None in compile_filter ?st_opt ?stL_opt Is_link in let rec readlink_aux already_read fln = let newly_read = prevent_recursion already_read fln in let dirs = all_upper_dir fln in try let src_link = List.find ctst (List.rev dirs) in let dst_link = Unix.readlink src_link in let real_link = if is_relative dst_link then reduce (concat (dirname src_link) dst_link) else reduce dst_link in readlink_aux newly_read (reparent src_link real_link fln) with Not_found -> fln in readlink_aux SetFilename.empty (make_absolute (pwd ()) fln)
9df2c35e9ba67c9a3294d3cceb1d89f5ac053140d4b3d7e4492734706610eec4
dradtke/Lisp-Text-Editor
generics.lisp
(in-package :gtk-cffi) ;; (defgeneric destroy (gtk-object)) ;; (defgeneric flags (gtk-object)) ;; (defgeneric text (widget &rest flags)) ( defgeneric ( setf text ) ( text widget & rest rest ) ) ( defgeneric ( setf mnemonic - widget ) ( widget label ) ) ;; (defgeneric mnemonic-widget (label)) ;; (defgeneric activate (widget)) ;; (defgeneric realize (widget)) ;; (defgeneric size-request (widget)) ( defgeneric ( setf size - request ) ( size widget ) ) ;; (defgeneric style-field (widget field &optional state type)) ( defgeneric ( setf style - field ) ( value widget field & optional state type ) ) ;; (defgeneric color (widget &rest rest)) ( defgeneric ( setf color ) ( color widget & rest rest ) ) ;; (defgeneric font (widget &rest rest)) ( defgeneric ( setf font ) ( font widget & rest rest ) ) ;; (defgeneric bg-pixmap (widget &rest state)) ( defgeneric ( setf bg - pixmap ) ( pixmap widget & rest rest ) ) ;; (defgeneric allocation (widget)) ( defgeneric ( setf allocation ) ( value widget ) ) ;; (defgeneric show (widget &rest flags)) ;; (defgeneric hide (widget)) ( - window ( widget ) ) ( defgeneric ( setf justify ) ( justify label ) ) ;; (defgeneric justify (label)) ( defgeneric child ( ) ) ( defgeneric ( setf default - size ) ( coords window ) ) ;; (defgeneric default-size (window)) ( defgeneric ( setf screen ) ( screen window ) ) ;; (defgeneric screen (window)) ;; (defgeneric transient-for (window)) ( defgeneric ( setf transient - for ) ( window parent ) ) ( defgeneric ( setf win - position ) ( pos window ) ) ;; (defgeneric add (container widget)) ;; (defgeneric border-width (container)) ( defgeneric ( setf border - width ) ( value container ) ) ( ( widget new - parent ) ) ;; (defgeneric propagate-expose (container child event)) ;; (defgeneric run (dialog &key keep-alive)) ( defgeneric ( setf has - separator ) ( has dialog ) ) ;; (defgeneric has-separator (dialog)) ;; (defgeneric add-button (dialog string response)) ;; ;(defgeneric get-iter (text-buffer text-iter pos)) ;; (defgeneric buffer (text-view)) ( defgeneric ( setf buffer ) ( buffer text - view ) ) ;; (defgeneric add-attribute (cell-layout cell-renderer attr column)) ( defgeneric ( setf cell - data - func ) ( c - handler ;; cell-layout cell-renderer ;; &optional data destroy-notify)) ;; (defgeneric clear-attributes (cell-layout cell-renderer)) ;; (defgeneric clear (cell-layout)) ( defgeneric ( setf sort - column - id ) ( i d tree - view - column ) ) ( defgeneric ( setf reorderable ) ( reorderable tree - view - column ) ) ;; (defgeneric reorderable (tree-view-column)) ( defgeneric ( setf widget ) ( widget tree - view - column ) ) ;; (defgeneric widget (tree-view-column)) ;; (defgeneric pack (tree-view-column cell-renderer &rest flags)) ;; (defgeneric cell-get-position (tree-view-column cell-renderer)) ;; (defgeneric cell-renderers (tree-view-column)) ;; (defgeneric get-cell-at (tree-view-column x)) ( defgeneric ( setf title ) ( title tree - view - column ) ) ( ( tree - view - column ) ) ;; (defgeneric get-indices (tree-path)) ;; (defgeneric get-index (tree-path &optional pos)) ;; (defgeneric copy (struct-object)) ;; (defgeneric foreach (tree-model func &optional data)) ( ( tree - model tree - iter ) ) ( ( tree - model tree - iter ) ) ;; (defgeneric model-values (tree-model &key iter columns col)) ;; (defgeneric path->iter (tree-model tree-path &optional tree-iter)) ;; (defgeneric n-columns (tree-model)) ;; (defgeneric column-type (tree-model col)) ;; (defgeneric path-from-child (tree-model-filter tree-path)) ;; (defgeneric iter-to-child (tree-model-filter tree-iter)) ( defgeneric ( setf model - values ) ( values tree - model - filter ;; &key iter columns col)) ( defgeneric ( setf visible - column ) ( column tree - model - filter ) ) ( defgeneric ( setf shadow - type ) ( shadow - type frame ) ) ;; (defgeneric shadow-type (frame)) ( defgeneric ( setf policy ) ( policy scrolled - window ) ) ;; (defgeneric get-selection (tree-view)) ;; (defgeneric path-at-pos (tree-view x y)) ;; (defgeneric get-cursor (tree-view)) ;; (defgeneric column (tree-view n)) ;; (defgeneric append-column (tree-view tree-view-column)) ( defgeneric ( setf search - column ) ( n tree - view ) ) ;; (defgeneric search-column (tree-view)) ;; (defgeneric model (tree-view)) ( defgeneric ( setf model ) ( model tree - view ) ) ;; (defgeneric get-selected (tree-selection)) ( - selection - foreach ( tree - selection func & optional data ) ) ;; (defgeneric append-iter (list-store &optional tree-iter)) ;; (defgeneric append-values (list-store values)) ;; (defgeneric append-text (combo-box text)) ;; (defgeneric prepend-text (combo-box text)) ;; (defgeneric insert-text (combo-box text)) ;; (defgeneric remove-text (combo-box pos)) ;; (defgeneric active-text (combo-box)) ;; (defgeneric fraction (progress-bar)) ( defgeneric ( setf fraction ) ( fraction progress - bar ) ) ( defgeneric ( setf kid ) ( kid container ) ) ( defgeneric ( setf kids ) ( kids container ) ) ;; (defgeneric resize (table &key rows columns)) ( ( table widget & key left right top bottom ;; xoptions yoptions xpadding ypadding))
null
https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/gtk-cffi-20120208-cvs/gtk/generics.lisp
lisp
(defgeneric destroy (gtk-object)) (defgeneric flags (gtk-object)) (defgeneric text (widget &rest flags)) (defgeneric mnemonic-widget (label)) (defgeneric activate (widget)) (defgeneric realize (widget)) (defgeneric size-request (widget)) (defgeneric style-field (widget field &optional state type)) (defgeneric color (widget &rest rest)) (defgeneric font (widget &rest rest)) (defgeneric bg-pixmap (widget &rest state)) (defgeneric allocation (widget)) (defgeneric show (widget &rest flags)) (defgeneric hide (widget)) (defgeneric justify (label)) (defgeneric default-size (window)) (defgeneric screen (window)) (defgeneric transient-for (window)) (defgeneric add (container widget)) (defgeneric border-width (container)) (defgeneric propagate-expose (container child event)) (defgeneric run (dialog &key keep-alive)) (defgeneric has-separator (dialog)) (defgeneric add-button (dialog string response)) ;(defgeneric get-iter (text-buffer text-iter pos)) (defgeneric buffer (text-view)) (defgeneric add-attribute (cell-layout cell-renderer attr column)) cell-layout cell-renderer &optional data destroy-notify)) (defgeneric clear-attributes (cell-layout cell-renderer)) (defgeneric clear (cell-layout)) (defgeneric reorderable (tree-view-column)) (defgeneric widget (tree-view-column)) (defgeneric pack (tree-view-column cell-renderer &rest flags)) (defgeneric cell-get-position (tree-view-column cell-renderer)) (defgeneric cell-renderers (tree-view-column)) (defgeneric get-cell-at (tree-view-column x)) (defgeneric get-indices (tree-path)) (defgeneric get-index (tree-path &optional pos)) (defgeneric copy (struct-object)) (defgeneric foreach (tree-model func &optional data)) (defgeneric model-values (tree-model &key iter columns col)) (defgeneric path->iter (tree-model tree-path &optional tree-iter)) (defgeneric n-columns (tree-model)) (defgeneric column-type (tree-model col)) (defgeneric path-from-child (tree-model-filter tree-path)) (defgeneric iter-to-child (tree-model-filter tree-iter)) &key iter columns col)) (defgeneric shadow-type (frame)) (defgeneric get-selection (tree-view)) (defgeneric path-at-pos (tree-view x y)) (defgeneric get-cursor (tree-view)) (defgeneric column (tree-view n)) (defgeneric append-column (tree-view tree-view-column)) (defgeneric search-column (tree-view)) (defgeneric model (tree-view)) (defgeneric get-selected (tree-selection)) (defgeneric append-iter (list-store &optional tree-iter)) (defgeneric append-values (list-store values)) (defgeneric append-text (combo-box text)) (defgeneric prepend-text (combo-box text)) (defgeneric insert-text (combo-box text)) (defgeneric remove-text (combo-box pos)) (defgeneric active-text (combo-box)) (defgeneric fraction (progress-bar)) (defgeneric resize (table &key rows columns)) xoptions yoptions xpadding ypadding))
(in-package :gtk-cffi) ( defgeneric ( setf text ) ( text widget & rest rest ) ) ( defgeneric ( setf mnemonic - widget ) ( widget label ) ) ( defgeneric ( setf size - request ) ( size widget ) ) ( defgeneric ( setf style - field ) ( value widget field & optional state type ) ) ( defgeneric ( setf color ) ( color widget & rest rest ) ) ( defgeneric ( setf font ) ( font widget & rest rest ) ) ( defgeneric ( setf bg - pixmap ) ( pixmap widget & rest rest ) ) ( defgeneric ( setf allocation ) ( value widget ) ) ( - window ( widget ) ) ( defgeneric ( setf justify ) ( justify label ) ) ( defgeneric child ( ) ) ( defgeneric ( setf default - size ) ( coords window ) ) ( defgeneric ( setf screen ) ( screen window ) ) ( defgeneric ( setf transient - for ) ( window parent ) ) ( defgeneric ( setf win - position ) ( pos window ) ) ( defgeneric ( setf border - width ) ( value container ) ) ( ( widget new - parent ) ) ( defgeneric ( setf has - separator ) ( has dialog ) ) ( defgeneric ( setf buffer ) ( buffer text - view ) ) ( defgeneric ( setf cell - data - func ) ( c - handler ( defgeneric ( setf sort - column - id ) ( i d tree - view - column ) ) ( defgeneric ( setf reorderable ) ( reorderable tree - view - column ) ) ( defgeneric ( setf widget ) ( widget tree - view - column ) ) ( defgeneric ( setf title ) ( title tree - view - column ) ) ( ( tree - view - column ) ) ( ( tree - model tree - iter ) ) ( ( tree - model tree - iter ) ) ( defgeneric ( setf model - values ) ( values tree - model - filter ( defgeneric ( setf visible - column ) ( column tree - model - filter ) ) ( defgeneric ( setf shadow - type ) ( shadow - type frame ) ) ( defgeneric ( setf policy ) ( policy scrolled - window ) ) ( defgeneric ( setf search - column ) ( n tree - view ) ) ( defgeneric ( setf model ) ( model tree - view ) ) ( - selection - foreach ( tree - selection func & optional data ) ) ( defgeneric ( setf fraction ) ( fraction progress - bar ) ) ( defgeneric ( setf kid ) ( kid container ) ) ( defgeneric ( setf kids ) ( kids container ) ) ( ( table widget & key left right top bottom
dd6f65f952b6a8cadf7eef625199fb393c0085fb80203635d438aea2ceb5c35a
mstksg/advent-of-code-2019
Day24.hs
-- | -- Module : AOC.Challenge.Day24 -- License : BSD3 -- -- Stability : experimental -- Portability : non-portable -- Day 24 . See " AOC.Solver " for the types used in this module ! module AOC.Challenge.Day24 ( day24a , day24b ) where import AOC.Common (Point, cardinalNeighbsSet, parseAsciiMap, firstRepeated, (!!!), Dir(..)) import AOC.Solver ((:~>)(..), dyno_) import Control.DeepSeq (NFData) import Data.Finite (Finite, finites) import Data.Semigroup (Min(..), Max(..), Sum(..)) import Data.Set (Set) import GHC.Generics (Generic) import Linear.V2 (V2(..)) import qualified Data.Map as M import qualified Data.Set as S allPoints :: Set Point allPoints = S.fromList $ V2 <$> [0..4] <*> [0..4] stepWith :: Ord a => (Set a -> Set a) -- ^ get the set of all points to check, from current alive -> (a -> Set a) -- ^ neighbors -> Set a -- ^ initial -> [Set a] -- ^ yipee stepWith universe neighbs = iterate go where go s0 = flip S.filter (universe s0) $ \p -> let n = S.size $ neighbs p `S.intersection` s0 in if p `S.member` s0 then n == 1 else n == 1 || n == 2 day24a :: Set Point :~> Set Point day24a = MkSol { sParse = Just . parseMap , sShow = show . getSum . foldMap (Sum . biodiversity) , sSolve = firstRepeated . stepWith (const allPoints) cardinalNeighbsSet } where biodiversity :: Point -> Int biodiversity (V2 x y) = 2 ^ (y * 5 + x) | Position in layer . Can not be ( 2,2 ) . Use ' mkP5 ' if you 're not sure . type P5 = V2 (Finite 5) | Safely construct a ' P5 ' that is not ( 2,2 ) mkP5 :: Finite 5 -> Finite 5 -> Maybe P5 mkP5 2 2 = Nothing mkP5 x y = Just (V2 x y) data Loc = L { lLevel :: !Int -- ^ positive: zoom in, negative: zoom out , lPoint :: !P5 -- ^ position in layer. } deriving (Eq, Ord, Show, Generic) instance NFData Loc stepLoc :: Loc -> Dir -> [Loc] stepLoc (L n p@(V2 x y)) = \case North -> case p of V2 2 3 -> L (n + 1) . (`V2` 4) <$> finites V2 _ 0 -> [L (n - 1) (V2 2 1)] _ -> [L n (V2 x (y - 1))] East -> case p of V2 1 2 -> L (n + 1) . V2 0 <$> finites V2 4 _ -> [L (n - 1) (V2 3 2)] _ -> [L n (V2 (x + 1) y)] South -> case p of V2 2 1 -> L (n + 1) . (`V2` 0) <$> finites V2 _ 4 -> [L (n - 1) (V2 2 3)] _ -> [L n (V2 x (y + 1))] West -> case p of V2 3 2 -> L (n + 1) . V2 4 <$> finites V2 0 _ -> [L (n - 1) (V2 1 2)] _ -> [L n (V2 (x - 1) y)] day24b :: Set Loc :~> Set Loc day24b = MkSol { sParse = Just . S.map (L 0 . fmap fromIntegral) . parseMap , sShow = show . S.size , sSolve = Just . (!!! dyno_ "steps" 200) . stepWith getUniverse getNeighbs } where getNeighbs p = S.fromList $ foldMap (stepLoc p) [North ..] getUniverse s = oldLocs <> zoomOut where oldLocs = S.fromList [ L n p | n <- [mn .. mx + 1] , Just p <- mkP5 <$> finites <*> finites ] a little optimization : only check the center 9 points in the zoomed -- out layer zoomOut = S.fromList [ L (mn - 1) p | Just p <- mkP5 <$> [1..3] <*> [1..3] ] (Min mn, Max mx) = foldMap (\(lLevel->l) -> (Min l, Max l)) . S.toList $ s parseMap :: String -> Set Point parseMap = M.keysSet . M.filter (== '#') . parseAsciiMap Just
null
https://raw.githubusercontent.com/mstksg/advent-of-code-2019/df2b1c76ad26ad20306f705e923a09b14d538374/src/AOC/Challenge/Day24.hs
haskell
| Module : AOC.Challenge.Day24 License : BSD3 Stability : experimental Portability : non-portable ^ get the set of all points to check, from current alive ^ neighbors ^ initial ^ yipee ^ positive: zoom in, negative: zoom out ^ position in layer. out layer
Day 24 . See " AOC.Solver " for the types used in this module ! module AOC.Challenge.Day24 ( day24a , day24b ) where import AOC.Common (Point, cardinalNeighbsSet, parseAsciiMap, firstRepeated, (!!!), Dir(..)) import AOC.Solver ((:~>)(..), dyno_) import Control.DeepSeq (NFData) import Data.Finite (Finite, finites) import Data.Semigroup (Min(..), Max(..), Sum(..)) import Data.Set (Set) import GHC.Generics (Generic) import Linear.V2 (V2(..)) import qualified Data.Map as M import qualified Data.Set as S allPoints :: Set Point allPoints = S.fromList $ V2 <$> [0..4] <*> [0..4] stepWith :: Ord a stepWith universe neighbs = iterate go where go s0 = flip S.filter (universe s0) $ \p -> let n = S.size $ neighbs p `S.intersection` s0 in if p `S.member` s0 then n == 1 else n == 1 || n == 2 day24a :: Set Point :~> Set Point day24a = MkSol { sParse = Just . parseMap , sShow = show . getSum . foldMap (Sum . biodiversity) , sSolve = firstRepeated . stepWith (const allPoints) cardinalNeighbsSet } where biodiversity :: Point -> Int biodiversity (V2 x y) = 2 ^ (y * 5 + x) | Position in layer . Can not be ( 2,2 ) . Use ' mkP5 ' if you 're not sure . type P5 = V2 (Finite 5) | Safely construct a ' P5 ' that is not ( 2,2 ) mkP5 :: Finite 5 -> Finite 5 -> Maybe P5 mkP5 2 2 = Nothing mkP5 x y = Just (V2 x y) data Loc = L } deriving (Eq, Ord, Show, Generic) instance NFData Loc stepLoc :: Loc -> Dir -> [Loc] stepLoc (L n p@(V2 x y)) = \case North -> case p of V2 2 3 -> L (n + 1) . (`V2` 4) <$> finites V2 _ 0 -> [L (n - 1) (V2 2 1)] _ -> [L n (V2 x (y - 1))] East -> case p of V2 1 2 -> L (n + 1) . V2 0 <$> finites V2 4 _ -> [L (n - 1) (V2 3 2)] _ -> [L n (V2 (x + 1) y)] South -> case p of V2 2 1 -> L (n + 1) . (`V2` 0) <$> finites V2 _ 4 -> [L (n - 1) (V2 2 3)] _ -> [L n (V2 x (y + 1))] West -> case p of V2 3 2 -> L (n + 1) . V2 4 <$> finites V2 0 _ -> [L (n - 1) (V2 1 2)] _ -> [L n (V2 (x - 1) y)] day24b :: Set Loc :~> Set Loc day24b = MkSol { sParse = Just . S.map (L 0 . fmap fromIntegral) . parseMap , sShow = show . S.size , sSolve = Just . (!!! dyno_ "steps" 200) . stepWith getUniverse getNeighbs } where getNeighbs p = S.fromList $ foldMap (stepLoc p) [North ..] getUniverse s = oldLocs <> zoomOut where oldLocs = S.fromList [ L n p | n <- [mn .. mx + 1] , Just p <- mkP5 <$> finites <*> finites ] a little optimization : only check the center 9 points in the zoomed zoomOut = S.fromList [ L (mn - 1) p | Just p <- mkP5 <$> [1..3] <*> [1..3] ] (Min mn, Max mx) = foldMap (\(lLevel->l) -> (Min l, Max l)) . S.toList $ s parseMap :: String -> Set Point parseMap = M.keysSet . M.filter (== '#') . parseAsciiMap Just
d56320a976644005e34f864d8b54e2f87cc96a570600ba187cfd83cdd3ed0b3d
leptonyu/boots
Web.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # module Boots.Factory.Web( buildWeb , HasWeb(..) -- ** Configuration , HasWebConfig(..) , WebConfig(..) , EndpointConfig(..) -- ** Environment , WebEnv(..) , newWebEnv , askEnv -- ** Modified Middleware , EnvMiddleware , registerMiddleware -- ** Api serve , tryServe , trySwagger , tryServeWithSwagger -- ** Utilities , HasSwagger(..) , HasServer(..) , HasContextEntry(..) , SetContextEntry(..) , Context(..) , logException , whenException , ToSchema , Vault ) where import Boots import Boots.Endpoint.Swagger import Boots.Metrics import Control.Exception ( SomeException , fromException ) import qualified Data.HashMap.Strict as HM import Data.Maybe import Data.Swagger (Swagger) import Data.Swagger.Schema (ToSchema) import Data.Text (Text) import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Encoding import Data.Word import Network.Wai import Network.Wai.Handler.Warp import Salak import Servant import Servant.Server.Internal.ServerError (responseServerError) import Servant.Swagger -- | Application Configuration. data WebConfig = WebConfig ^ hostname , used in swagger . , port :: !Word16 -- ^ Application http port. } deriving (Eq, Show) instance Default WebConfig where # INLINE def # def = WebConfig "localhost" 8888 instance FromProp m WebConfig where # INLINE fromProp # fromProp = WebConfig <$> "host" .?: hostname <*> "port" .?: port | Environment values with ` WebConfig ` . class HasWebConfig env where askWebConfig :: Lens' env WebConfig instance HasWebConfig WebConfig where askWebConfig = id -- | Endpoint configuration. data EndpointConfig = EndpointConfig { enabled :: Bool , endpoints :: HM.HashMap Text Bool } instance FromProp m EndpointConfig where fromProp = EndpointConfig <$> "enabled" .?= True <*> "enabled" .?= HM.empty -- | Web environment, which defined all components to build a web application. data WebEnv env context = WebEnv { serveW :: forall api. HasServer api context => Proxy api -> Context context -> Server api -> Application -- ^ A wrapper of `serveWithContext`. , serveA :: forall api. HasSwagger api => Proxy api -> Swagger -- ^ A wrapper of `toSwagger`. , middleware :: EnvMiddleware env -- ^ Modified middleware. , envs :: AppEnv env -- ^ Application environment. , context :: AppEnv env -> Context context -- ^ Function used to generate @context@ from @env. , config :: WebConfig -- ^ Web configuration. , endpoint :: EndpointConfig -- ^ Endpoint configuration. , store :: Store -- ^ Metrics store. } | Environment values with ` WebEnv ` . instance HasWebConfig (WebEnv env context) where askWebConfig = lens config (\x y -> x { config = y}) instance HasMetrics (WebEnv env context) where # INLINE askMetrics # askMetrics = lens store (\x y -> x { store = y}) instance HasApp (WebEnv env context) env where # INLINE askApp # askApp = lens envs (\x y -> x { envs = y}) instance HasSalak (WebEnv env context) where # INLINE askSalak # askSalak = askApp @(WebEnv env context) @env . askSalak instance HasLogger (WebEnv env context) where # INLINE askLogger # askLogger = askApp @(WebEnv env context) @env . askLogger instance HasRandom (WebEnv env context) where # INLINE askRandom # askRandom = askApp @(WebEnv env context) @env . askRandom instance HasHealth (WebEnv env context) where # INLINE askHealth # askHealth = askApp @(WebEnv env context) @env . askHealth class ( HasContextEntry context (AppEnv env) , SetContextEntry context (AppEnv env)) => HasWeb context env | context -> env where askWeb :: Lens' (Context context) (AppEnv env) askWeb = lens getContextEntry (flip setContextEntry) instance HasWeb (AppEnv env : as) env -- | Class type used to modify @context@ entries. class HasContextEntry context env => SetContextEntry context env where setContextEntry :: env -> Context context -> Context context instance {-# OVERLAPPABLE #-} SetContextEntry as env => SetContextEntry (a : as) env where # INLINE setContextEntry # setContextEntry env (a :. as) = a :. setContextEntry env as instance SetContextEntry (env : as) env where # INLINE setContextEntry # setContextEntry env (_ :. as) = env :. as instance HasWeb context env => HasApp (Context context) env where askApp = askWeb @context @env instance HasWeb context env => HasSalak (Context context) where askSalak = askWeb @context @env . askSalak instance HasWeb context env => HasLogger (Context context) where askLogger = askWeb @context @env . askLogger instance HasWeb context env => HasRandom (Context context) where askRandom = askWeb @context @env . askRandom -- | Create a web environment. # INLINE newWebEnv # newWebEnv :: HasContextEntry context (AppEnv env) => AppEnv env -- ^ Application environment. -> (AppEnv env -> Context context) -- ^ Function used to generate @context@ from @env@. -> WebConfig -- ^ Web configuration. -> EndpointConfig -- ^ Endpoint configuration. -> Store -- ^ Metrics store. -> WebEnv env context newWebEnv = WebEnv serveWithContext toSwagger id -- | Get application environment @env@. # INLINE askEnv # askEnv :: MonadMask n => Factory n (WebEnv env context) (AppEnv env) askEnv = envs <$> getEnv | Modified ` , which support modify @env@. type EnvMiddleware env = (AppEnv env -> Application) -> AppEnv env -> Application -- | Register a modified middleware. # INLINE registerMiddleware # registerMiddleware :: MonadMask n => EnvMiddleware env -> Factory n (WebEnv env context) () registerMiddleware md = modifyEnv $ \web -> web { middleware = md . middleware web } | Build a web application from ` WebEnv ` . buildWeb :: forall context env n . ( MonadIO n , MonadMask n , HasWeb context env ) => Proxy context -- ^ @context@ proxy. -> Proxy env -- ^ @env@ proxy. ^ Factory which create an application from ` WebEnv ` . buildWeb _ _ = do (WebEnv{..} :: WebEnv env context) <- getEnv within envs $ do let AppEnv{..} = envs serveWarp WebConfig{..} = runSettings $ defaultSettings & setPort (fromIntegral port) & setOnExceptionResponse whenException & setOnException (\_ -> runAppT envs . logException) let ok = enabled endpoint && HM.lookup "swagger" (endpoints endpoint) /= Just False when ok $ logInfo $ "Swagger enabled: http://" <> toLogStr (hostname config) <> ":" <> toLogStr (port config) <> "/endpoints/swagger" logInfo $ "Service started on port(s): " <> toLogStr (port config) delay $ logInfo "Service ended" return $ serveWarp config $ flip middleware envs $ \env1 -> if ok then serveW (Proxy @EndpointSwagger) (context env1) (return $ baseInfo (hostname config) name version (port config) $ serveA $ Proxy @EmptyAPI) else serveW (Proxy @EmptyAPI) (context env1) emptyServer -- | Log exception. # INLINE logException # logException :: HasLogger env => SomeException -> App env () logException = logError . toLogStr . formatException -- | Convert an exception into `Network.Wai.Response`. # INLINE whenException # whenException :: SomeException -> Network.Wai.Response whenException e = responseServerError $ fromMaybe err400 { errBody = fromString $ show e} (fromException e :: Maybe ServerError) -- | Format exception. # INLINE formatException # formatException :: SomeException -> Text formatException e = case fromException e of Just ServerError{..} -> fromString errReasonPhrase <> " " <> toStrict (decodeUtf8 errBody) _ -> fromString $ show e -- | Serve web server with swagger. tryServeWithSwagger :: forall env context api n . ( HasContextEntry context (AppEnv env) , HasServer api context , HasSwagger api , MonadMask n) => Bool -- ^ If do this action. -> Proxy context -- ^ Context proxy. -> Proxy api -- ^ Api proxy. -> ServerT api (App (AppEnv env)) -- ^ Api server. -> Factory n (WebEnv env context) () tryServeWithSwagger b pc proxy server = do trySwagger b proxy tryServe b pc proxy server -- | Try serve a swagger definition. trySwagger :: (MonadMask n, HasSwagger api) => Bool -- ^ If do this action. -> Proxy api -- ^ Api proxy. -> Factory n (WebEnv env context) () trySwagger b api = when b $ modifyEnv $ \web -> web { serveA = serveA web . gop api } -- | Try serve a web server. tryServe :: forall env context api n . ( HasContextEntry context (AppEnv env) , HasServer api context , MonadMask n) => Bool -- ^ If do this action. -> Proxy context -- ^ Context proxy. -> Proxy api -- ^ Api proxy. -> ServerT api (App (AppEnv env)) -- ^ Api server. -> Factory n (WebEnv env context) () tryServe b pc proxy server = when b $ modifyEnv $ \web -> web { serveW = \p c s -> serveW web (gop p proxy) c $ s :<|> hoistServerWithContext proxy pc (go . runAppT (getContextEntry c :: AppEnv env)) server } where # INLINE go # go :: IO a -> Servant.Handler a go = liftIO # INLINE gop # gop :: forall a b. Proxy a -> Proxy b -> Proxy (a :<|> b) gop _ _ = Proxy
null
https://raw.githubusercontent.com/leptonyu/boots/335d58baafb1e0700b1a7dbe595a7264bd4d83ba/boots-web/src/Boots/Factory/Web.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # ** Configuration ** Environment ** Modified Middleware ** Api serve ** Utilities | Application Configuration. ^ Application http port. | Endpoint configuration. | Web environment, which defined all components to build a web application. ^ A wrapper of `serveWithContext`. ^ A wrapper of `toSwagger`. ^ Modified middleware. ^ Application environment. ^ Function used to generate @context@ from @env. ^ Web configuration. ^ Endpoint configuration. ^ Metrics store. | Class type used to modify @context@ entries. # OVERLAPPABLE # | Create a web environment. ^ Application environment. ^ Function used to generate @context@ from @env@. ^ Web configuration. ^ Endpoint configuration. ^ Metrics store. | Get application environment @env@. | Register a modified middleware. ^ @context@ proxy. ^ @env@ proxy. | Log exception. | Convert an exception into `Network.Wai.Response`. | Format exception. | Serve web server with swagger. ^ If do this action. ^ Context proxy. ^ Api proxy. ^ Api server. | Try serve a swagger definition. ^ If do this action. ^ Api proxy. | Try serve a web server. ^ If do this action. ^ Context proxy. ^ Api proxy. ^ Api server.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # module Boots.Factory.Web( buildWeb , HasWeb(..) , HasWebConfig(..) , WebConfig(..) , EndpointConfig(..) , WebEnv(..) , newWebEnv , askEnv , EnvMiddleware , registerMiddleware , tryServe , trySwagger , tryServeWithSwagger , HasSwagger(..) , HasServer(..) , HasContextEntry(..) , SetContextEntry(..) , Context(..) , logException , whenException , ToSchema , Vault ) where import Boots import Boots.Endpoint.Swagger import Boots.Metrics import Control.Exception ( SomeException , fromException ) import qualified Data.HashMap.Strict as HM import Data.Maybe import Data.Swagger (Swagger) import Data.Swagger.Schema (ToSchema) import Data.Text (Text) import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Encoding import Data.Word import Network.Wai import Network.Wai.Handler.Warp import Salak import Servant import Servant.Server.Internal.ServerError (responseServerError) import Servant.Swagger data WebConfig = WebConfig ^ hostname , used in swagger . } deriving (Eq, Show) instance Default WebConfig where # INLINE def # def = WebConfig "localhost" 8888 instance FromProp m WebConfig where # INLINE fromProp # fromProp = WebConfig <$> "host" .?: hostname <*> "port" .?: port | Environment values with ` WebConfig ` . class HasWebConfig env where askWebConfig :: Lens' env WebConfig instance HasWebConfig WebConfig where askWebConfig = id data EndpointConfig = EndpointConfig { enabled :: Bool , endpoints :: HM.HashMap Text Bool } instance FromProp m EndpointConfig where fromProp = EndpointConfig <$> "enabled" .?= True <*> "enabled" .?= HM.empty data WebEnv env context = WebEnv { serveW :: forall api. HasServer api context => Proxy api -> Context context -> Server api -> Application , serveA :: forall api. HasSwagger api => Proxy api -> Swagger } | Environment values with ` WebEnv ` . instance HasWebConfig (WebEnv env context) where askWebConfig = lens config (\x y -> x { config = y}) instance HasMetrics (WebEnv env context) where # INLINE askMetrics # askMetrics = lens store (\x y -> x { store = y}) instance HasApp (WebEnv env context) env where # INLINE askApp # askApp = lens envs (\x y -> x { envs = y}) instance HasSalak (WebEnv env context) where # INLINE askSalak # askSalak = askApp @(WebEnv env context) @env . askSalak instance HasLogger (WebEnv env context) where # INLINE askLogger # askLogger = askApp @(WebEnv env context) @env . askLogger instance HasRandom (WebEnv env context) where # INLINE askRandom # askRandom = askApp @(WebEnv env context) @env . askRandom instance HasHealth (WebEnv env context) where # INLINE askHealth # askHealth = askApp @(WebEnv env context) @env . askHealth class ( HasContextEntry context (AppEnv env) , SetContextEntry context (AppEnv env)) => HasWeb context env | context -> env where askWeb :: Lens' (Context context) (AppEnv env) askWeb = lens getContextEntry (flip setContextEntry) instance HasWeb (AppEnv env : as) env class HasContextEntry context env => SetContextEntry context env where setContextEntry :: env -> Context context -> Context context # INLINE setContextEntry # setContextEntry env (a :. as) = a :. setContextEntry env as instance SetContextEntry (env : as) env where # INLINE setContextEntry # setContextEntry env (_ :. as) = env :. as instance HasWeb context env => HasApp (Context context) env where askApp = askWeb @context @env instance HasWeb context env => HasSalak (Context context) where askSalak = askWeb @context @env . askSalak instance HasWeb context env => HasLogger (Context context) where askLogger = askWeb @context @env . askLogger instance HasWeb context env => HasRandom (Context context) where askRandom = askWeb @context @env . askRandom # INLINE newWebEnv # newWebEnv :: HasContextEntry context (AppEnv env) -> WebEnv env context newWebEnv = WebEnv serveWithContext toSwagger id # INLINE askEnv # askEnv :: MonadMask n => Factory n (WebEnv env context) (AppEnv env) askEnv = envs <$> getEnv | Modified ` , which support modify @env@. type EnvMiddleware env = (AppEnv env -> Application) -> AppEnv env -> Application # INLINE registerMiddleware # registerMiddleware :: MonadMask n => EnvMiddleware env -> Factory n (WebEnv env context) () registerMiddleware md = modifyEnv $ \web -> web { middleware = md . middleware web } | Build a web application from ` WebEnv ` . buildWeb :: forall context env n . ( MonadIO n , MonadMask n , HasWeb context env ) ^ Factory which create an application from ` WebEnv ` . buildWeb _ _ = do (WebEnv{..} :: WebEnv env context) <- getEnv within envs $ do let AppEnv{..} = envs serveWarp WebConfig{..} = runSettings $ defaultSettings & setPort (fromIntegral port) & setOnExceptionResponse whenException & setOnException (\_ -> runAppT envs . logException) let ok = enabled endpoint && HM.lookup "swagger" (endpoints endpoint) /= Just False when ok $ logInfo $ "Swagger enabled: http://" <> toLogStr (hostname config) <> ":" <> toLogStr (port config) <> "/endpoints/swagger" logInfo $ "Service started on port(s): " <> toLogStr (port config) delay $ logInfo "Service ended" return $ serveWarp config $ flip middleware envs $ \env1 -> if ok then serveW (Proxy @EndpointSwagger) (context env1) (return $ baseInfo (hostname config) name version (port config) $ serveA $ Proxy @EmptyAPI) else serveW (Proxy @EmptyAPI) (context env1) emptyServer # INLINE logException # logException :: HasLogger env => SomeException -> App env () logException = logError . toLogStr . formatException # INLINE whenException # whenException :: SomeException -> Network.Wai.Response whenException e = responseServerError $ fromMaybe err400 { errBody = fromString $ show e} (fromException e :: Maybe ServerError) # INLINE formatException # formatException :: SomeException -> Text formatException e = case fromException e of Just ServerError{..} -> fromString errReasonPhrase <> " " <> toStrict (decodeUtf8 errBody) _ -> fromString $ show e tryServeWithSwagger :: forall env context api n . ( HasContextEntry context (AppEnv env) , HasServer api context , HasSwagger api , MonadMask n) -> Factory n (WebEnv env context) () tryServeWithSwagger b pc proxy server = do trySwagger b proxy tryServe b pc proxy server trySwagger :: (MonadMask n, HasSwagger api) -> Factory n (WebEnv env context) () trySwagger b api = when b $ modifyEnv $ \web -> web { serveA = serveA web . gop api } tryServe :: forall env context api n . ( HasContextEntry context (AppEnv env) , HasServer api context , MonadMask n) -> Factory n (WebEnv env context) () tryServe b pc proxy server = when b $ modifyEnv $ \web -> web { serveW = \p c s -> serveW web (gop p proxy) c $ s :<|> hoistServerWithContext proxy pc (go . runAppT (getContextEntry c :: AppEnv env)) server } where # INLINE go # go :: IO a -> Servant.Handler a go = liftIO # INLINE gop # gop :: forall a b. Proxy a -> Proxy b -> Proxy (a :<|> b) gop _ _ = Proxy
0b2859507fe06db5d8df47cc48c8715e78588ac88bc04ae02d9e6bae2a625a83
jeapostrophe/exp
dpr.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse) racket/stxparam) (define-syntax-parameter queue-defer #f) (define-syntax (defere stx) (define qdv (syntax-parameter-value #'queue-defer)) (unless qdv (raise-syntax-error 'defer "Illegal use outside of define/dpr" stx)) (syntax-parse stx [(_ (f a ...)) (with-syntax ([(v ...) (generate-temporaries #'(a ...))]) (quasisyntax/loc stx (#,qdv (let ([v a] ...) (λ () (f v ...))))))])) (define-syntax-parameter return (λ (stx) (raise-syntax-error 'return "Illegal use outside of define/dpr" stx))) (struct exn:fail:panic exn:fail (v [recovered? #:mutable])) (define (panic v) (raise (exn:fail:panic (format "panic ~e" v) (current-continuation-marks) v #f))) (define current-panic (make-parameter #f)) (define (recover) (define p (current-panic)) (and p (set-exn:fail:panic-recovered?! p #t) (exn:fail:panic-v p))) (define-syntax (define/dpr-v1 stx) (syntax-parse stx [(_ (fun . fmls) . body) (syntax/loc stx (define (fun . fmls) (define ds null) (define (this-queue-defer f) (set! ds (cons f ds))) (define (run-defers) (for ([d (in-list ds)]) (d))) (begin0 (with-handlers ([exn:fail:panic? (λ (p) (parameterize ([current-panic p]) (run-defers)) (unless (exn:fail:panic-recovered? p) (raise p)))]) (let/ec this-return (syntax-parameterize ([queue-defer #'this-queue-defer] [return (make-rename-transformer #'this-return)]) . body)) (run-defers)))))])) (define-syntax (define/dpr stx) (syntax-parse stx [(_ (fun . fmls) . body) (syntax/loc stx (define (fun . fmls) (define ds null) (define (this-queue-defer f) (set! ds (cons (box f) ds))) (define (run-defers) (for ([db (in-list ds)]) (define d (unbox db)) (set-box! db #f) (when d (d)))) (begin0 (with-handlers ([exn:fail:panic? (λ (p) (parameterize ([current-panic p]) (run-defers)) (unless (exn:fail:panic-recovered? p) (raise p)))]) (let/ec this-return (syntax-parameterize ([queue-defer #'this-queue-defer] [return (make-rename-transformer #'this-return)]) . body)) (run-defers)))))])) (define-syntax-rule (defer . e) (defere ((λ () . e)))) (module+ test (require rackunit) (define-syntax-rule (test c e o) (begin (define os (open-output-string)) (check-equal? (parameterize ([current-output-port os]) (with-handlers ([exn:fail:panic? (λ (p) (exn:fail:panic-v p))]) c)) e) (check-equal? (get-output-string os) o))) (define/dpr (a) (define i 0) (defere (printf "~a\n" i)) (set! i (add1 i)) (return (void))) (test (a) (void) "0\n") (define/dpr (b) (for ([i (in-range 4)]) (defer (printf "~a" i)))) (test (b) (void) "3210") ;; xxx Named function returns would be a lot more complicated, so we ;; don't have example c (define/dpr (main recover?) (f recover?) (printf "Returned normally from f.\n")) (define/dpr (f recover?) (when recover? (defer (define r (recover)) (when r (printf "Recovered in f ~a\n" r)))) (printf "Calling g.\n") (g 0) (printf "Returned normally from g.\n")) (define/dpr (g i) (when (> i 3) (printf "Panicking!\n") (panic (format "~a" i))) (defer (printf "Defer in g ~a\n" i)) (printf "Printing in g ~a\n" i) (g (add1 i))) (test (main #t) (void) "Calling g.\nPrinting in g 0\nPrinting in g 1\nPrinting in g 2\nPrinting in g 3\nPanicking!\nDefer in g 3\nDefer in g 2\nDefer in g 1\nDefer in g 0\nRecovered in f 4\nReturned normally from f.\n") (test (main #f) "4" "Calling g.\nPrinting in g 0\nPrinting in g 1\nPrinting in g 2\nPrinting in g 3\nPanicking!\nDefer in g 3\nDefer in g 2\nDefer in g 1\nDefer in g 0\n") (define/dpr (panic-in-defer) (defer (displayln 0)) (defer (displayln 1)) (defer (displayln 2) (panic '!)) (defer (displayln 3))) (test (panic-in-defer) '! "3\n2\n1\n0\n"))
null
https://raw.githubusercontent.com/jeapostrophe/exp/43615110fd0439d2ef940c42629fcdc054c370f9/dpr.rkt
racket
xxx Named function returns would be a lot more complicated, so we don't have example c
#lang racket/base (require (for-syntax racket/base syntax/parse) racket/stxparam) (define-syntax-parameter queue-defer #f) (define-syntax (defere stx) (define qdv (syntax-parameter-value #'queue-defer)) (unless qdv (raise-syntax-error 'defer "Illegal use outside of define/dpr" stx)) (syntax-parse stx [(_ (f a ...)) (with-syntax ([(v ...) (generate-temporaries #'(a ...))]) (quasisyntax/loc stx (#,qdv (let ([v a] ...) (λ () (f v ...))))))])) (define-syntax-parameter return (λ (stx) (raise-syntax-error 'return "Illegal use outside of define/dpr" stx))) (struct exn:fail:panic exn:fail (v [recovered? #:mutable])) (define (panic v) (raise (exn:fail:panic (format "panic ~e" v) (current-continuation-marks) v #f))) (define current-panic (make-parameter #f)) (define (recover) (define p (current-panic)) (and p (set-exn:fail:panic-recovered?! p #t) (exn:fail:panic-v p))) (define-syntax (define/dpr-v1 stx) (syntax-parse stx [(_ (fun . fmls) . body) (syntax/loc stx (define (fun . fmls) (define ds null) (define (this-queue-defer f) (set! ds (cons f ds))) (define (run-defers) (for ([d (in-list ds)]) (d))) (begin0 (with-handlers ([exn:fail:panic? (λ (p) (parameterize ([current-panic p]) (run-defers)) (unless (exn:fail:panic-recovered? p) (raise p)))]) (let/ec this-return (syntax-parameterize ([queue-defer #'this-queue-defer] [return (make-rename-transformer #'this-return)]) . body)) (run-defers)))))])) (define-syntax (define/dpr stx) (syntax-parse stx [(_ (fun . fmls) . body) (syntax/loc stx (define (fun . fmls) (define ds null) (define (this-queue-defer f) (set! ds (cons (box f) ds))) (define (run-defers) (for ([db (in-list ds)]) (define d (unbox db)) (set-box! db #f) (when d (d)))) (begin0 (with-handlers ([exn:fail:panic? (λ (p) (parameterize ([current-panic p]) (run-defers)) (unless (exn:fail:panic-recovered? p) (raise p)))]) (let/ec this-return (syntax-parameterize ([queue-defer #'this-queue-defer] [return (make-rename-transformer #'this-return)]) . body)) (run-defers)))))])) (define-syntax-rule (defer . e) (defere ((λ () . e)))) (module+ test (require rackunit) (define-syntax-rule (test c e o) (begin (define os (open-output-string)) (check-equal? (parameterize ([current-output-port os]) (with-handlers ([exn:fail:panic? (λ (p) (exn:fail:panic-v p))]) c)) e) (check-equal? (get-output-string os) o))) (define/dpr (a) (define i 0) (defere (printf "~a\n" i)) (set! i (add1 i)) (return (void))) (test (a) (void) "0\n") (define/dpr (b) (for ([i (in-range 4)]) (defer (printf "~a" i)))) (test (b) (void) "3210") (define/dpr (main recover?) (f recover?) (printf "Returned normally from f.\n")) (define/dpr (f recover?) (when recover? (defer (define r (recover)) (when r (printf "Recovered in f ~a\n" r)))) (printf "Calling g.\n") (g 0) (printf "Returned normally from g.\n")) (define/dpr (g i) (when (> i 3) (printf "Panicking!\n") (panic (format "~a" i))) (defer (printf "Defer in g ~a\n" i)) (printf "Printing in g ~a\n" i) (g (add1 i))) (test (main #t) (void) "Calling g.\nPrinting in g 0\nPrinting in g 1\nPrinting in g 2\nPrinting in g 3\nPanicking!\nDefer in g 3\nDefer in g 2\nDefer in g 1\nDefer in g 0\nRecovered in f 4\nReturned normally from f.\n") (test (main #f) "4" "Calling g.\nPrinting in g 0\nPrinting in g 1\nPrinting in g 2\nPrinting in g 3\nPanicking!\nDefer in g 3\nDefer in g 2\nDefer in g 1\nDefer in g 0\n") (define/dpr (panic-in-defer) (defer (displayln 0)) (defer (displayln 1)) (defer (displayln 2) (panic '!)) (defer (displayln 3))) (test (panic-in-defer) '! "3\n2\n1\n0\n"))
c1940f2cfc67c61fbaf169fe6230e7bc04047a2af1bf0d62d6e84544cb9052de
mirage/ocaml-vhd
f.ml
* Copyright ( C ) 2011 - 2013 Citrix Inc * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2011-2013 Citrix Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) VHD manipulation let sector_size = 512 let sector_shift = 9 exception Cstruct_differ let cstruct_equal a b = let check_contents a b = try for i = 0 to Cstruct.len a - 1 do let a' = Cstruct.get_char a i in let b' = Cstruct.get_char b i in if a' <> b' then raise Cstruct_differ done; true with _ -> false in (Cstruct.len a = (Cstruct.len b)) && (check_contents a b) exception Invalid_sector of int64 * int64 module Memory = struct let alloc bytes = if bytes = 0 then Cstruct.create 0 else let n = (bytes + 4095) / 4096 in let pages = Io_page.(to_cstruct (get n)) in Cstruct.sub pages 0 bytes end let constant size v = let buf = Memory.alloc size in for i = 0 to size - 1 do Cstruct.set_uint8 buf i v done; buf let sectors_in_2mib = 2 * 1024 * 2 let empty_2mib = constant (sectors_in_2mib * 512) 0 let sector_all_zeroes = constant 512 0 let sector_all_ones = constant 512 0xff module Int64 = struct include Int64 let ( ++ ) = add let ( -- ) = sub let ( // ) = div let ( ** ) = mul let ( lsl ) = shift_left let ( lsr ) = shift_right_logical let roundup_sector x = ((x ++ (1L lsl sector_shift -- 1L)) lsr sector_shift) lsl sector_shift end let roundup_sector x = ((x + (1 lsl sector_shift - 1)) lsr sector_shift) lsl sector_shift let kib = 1024L let mib = Int64.(1024L ** kib) let gib = Int64.(1024L ** mib) let max_disk_size = Int64.(2040L ** gib) let _kib_shift = 10 let _mib_shift = 20 let _gib_shift = 30 let blank_uuid = match Uuidm.of_bytes (String.make 16 '\000') with | Some x -> x | None -> assert false (* never happens *) module Feature = struct type t = | Temporary let of_int32 x = if Int32.logand x 1l <> 0l then [ Temporary ] else [] let to_int32 ts = let one = function | Temporary -> 1 in let reserved = 2 in (* always set *) Int32.of_int (List.fold_left (lor) reserved (List.map one ts)) let to_string = function | Temporary -> "Temporary" end module Disk_type = struct type t = | Fixed_hard_disk | Dynamic_hard_disk | Differencing_hard_disk exception Unknown of int32 let of_int32 = let open Rresult in function | 2l -> R.ok Fixed_hard_disk | 3l -> R.ok Dynamic_hard_disk | 4l -> R.ok Differencing_hard_disk | x -> R.error (Unknown x) let to_int32 = function | Fixed_hard_disk -> 2l | Dynamic_hard_disk -> 3l | Differencing_hard_disk -> 4l let to_string = function | Fixed_hard_disk -> "Fixed_hard_disk" | Dynamic_hard_disk -> "Dynamic_hard_disk" | Differencing_hard_disk -> "Differencing_hard_disk" end module Host_OS = struct type t = | Windows | Macintosh | Other of int32 let of_int32 = function | 0x5769326bl -> Windows | 0x4d616320l -> Macintosh | x -> Other x let to_int32 = function | Windows -> 0x5769326bl | Macintosh -> 0x4d616320l | Other x -> x let to_string = function | Windows -> "Windows" | Macintosh -> "Macintosh" | Other x -> Printf.sprintf "Other %lx" x end module Geometry = struct type t = { cylinders : int; heads : int; sectors : int; } from the Appendix ' CHS calculation ' let of_sectors sectors = let open Int64 in let max_secs = 65535L ** 255L ** 16L in let secs = min max_secs sectors in let secs_per_track = ref 0L in let heads = ref 0L in let cyls_times_heads = ref 0L in if secs > 65535L ** 63L ** 16L then begin secs_per_track := 255L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end else begin secs_per_track := 17L; cyls_times_heads := secs // !secs_per_track; heads := max ((!cyls_times_heads ++ 1023L) // 1024L) 4L; if (!cyls_times_heads >= (!heads ** 1024L) || !heads > 16L) then begin secs_per_track := 31L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end; if (!cyls_times_heads >= (!heads ** 1024L)) then begin secs_per_track := 63L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end end; { cylinders = to_int (!cyls_times_heads // !heads); heads = to_int !heads; sectors = to_int !secs_per_track } let to_string t = Printf.sprintf "{ cylinders = %d; heads = %d; sectors = %d }" t.cylinders t.heads t.sectors end module Checksum = struct type t = int32 (* TODO: use the optimised mirage version *) let of_cstruct m = let rec inner n cur = if n=Cstruct.len m then cur else inner (n+1) (Int32.add cur (Int32.of_int (Cstruct.get_uint8 m n))) in Int32.lognot (inner 0 0l) let sub_int32 t x = (* Adjust the checksum [t] by removing the contribution of [x] *) let open Int32 in let t' = lognot t in let a = logand (shift_right_logical x 0) (of_int 0xff) in let b = logand (shift_right_logical x 8) (of_int 0xff) in let c = logand (shift_right_logical x 16) (of_int 0xff) in let d = logand (shift_right_logical x 24) (of_int 0xff) in Int32.lognot (sub (sub (sub (sub t' a) b) c) d) end module UTF16 = struct type t = int array let to_utf8_exn s = let utf8_chars_of_int i = if i < 0x80 then [char_of_int i] else if i < 0x800 then begin let z = i land 0x3f and y = (i lsr 6) land 0x1f in [char_of_int (0xc0 + y); char_of_int (0x80+z)] end else if i < 0x10000 then begin let z = i land 0x3f and y = (i lsr 6) land 0x3f and x = (i lsr 12) land 0x0f in [char_of_int (0xe0 + x); char_of_int (0x80+y); char_of_int (0x80+z)] end else if i < 0x110000 then begin let z = i land 0x3f and y = (i lsr 6) land 0x3f and x = (i lsr 12) land 0x3f and w = (i lsr 18) land 0x07 in [char_of_int (0xf0 + w); char_of_int (0x80+x); char_of_int (0x80+y); char_of_int (0x80+z)] end else failwith "Bad unicode character!" in String.concat "" (List.map (fun c -> Printf.sprintf "%c" c) (List.flatten (List.map utf8_chars_of_int (Array.to_list s)))) let to_utf8 x = try Rresult.R.ok (to_utf8_exn x) with e -> Rresult.R.error e let to_string x = Printf.sprintf "[| %s |]" (String.concat "; " (List.map string_of_int (Array.to_list x))) let of_ascii string = Array.init (String.length string) (fun c -> int_of_char string.[c]) FIXME ( obviously ) let marshal (buf: Cstruct.t) t = let rec inner ofs n = if n = Array.length t then Cstruct.sub buf 0 ofs else begin let char = t.(n) in if char < 0x10000 then begin Cstruct.BE.set_uint16 buf ofs char; inner (ofs + 2) (n + 1) end else begin let char = char - 0x10000 in let c1 = (char lsr 10) land 0x3ff in (* high bits *) let c2 = char land 0x3ff in (* low bits *) Cstruct.BE.set_uint16 buf (ofs + 0) (0xd800 + c1); Cstruct.BE.set_uint16 buf (ofs + 2) (0xdc00 + c2); inner (ofs + 4) (n + 1) end end in inner 0 0 let unmarshal (buf: Cstruct.t) len = (* Check if there's a byte order marker *) let _bigendian, pos, max = match Cstruct.BE.get_uint16 buf 0 with | 0xfeff -> true, 2, (len / 2 - 1) | 0xfffe -> false, 2, (len / 2 - 1) | _ -> true, 0, (len / 2) in (* UTF-16 strings end with a \000\000 *) let rec strlen acc i = if i >= max then acc else if Cstruct.BE.get_uint16 buf i = 0 then acc else strlen (acc + 1) (i + 2) in let max = strlen 0 0 in let string = Array.make max 0 in let rec inner ofs n = if n >= max then string else begin let c = Cstruct.BE.get_uint16 buf ofs in let code, ofs', n' = if c >= 0xd800 && c <= 0xdbff then begin let c2 = Cstruct.BE.get_uint16 buf (ofs + 2) in if c2 < 0xdc00 || c2 > 0xdfff then (failwith (Printf.sprintf "Bad unicode char: %04x %04x" c c2)); let top10bits = c-0xd800 in let bottom10bits = c2-0xdc00 in let char = 0x10000 + (bottom10bits lor (top10bits lsl 10)) in char, ofs + 4, n + 1 end else c, ofs + 2, n + 1 in string.(n) <- code; inner ofs' n' end in try Rresult.R.ok (inner pos 0) with e -> Rresult.R.error e end module Footer = struct type t = { (* "conectix" *) features : Feature.t list; data_offset : int64; time_stamp : int32; creator_application : string; creator_version : int32; creator_host_os : Host_OS.t; original_size : int64; current_size : int64; geometry : Geometry.t; disk_type : Disk_type.t; checksum : int32; uid : Uuidm.t; saved_state : bool } let default_creator_application = "caml" let default_creator_version = 0x00000001l let create ?(features=[]) ~data_offset ?(time_stamp=0l) ?(creator_application = default_creator_application) ?(creator_version = default_creator_version) ?(creator_host_os = Host_OS.Other 0l) ~current_size ?original_size ~disk_type ?(uid = Uuidm.v `V4) ?(saved_state = false) () = let original_size = match original_size with | None -> current_size | Some x -> x in let geometry = Geometry.of_sectors Int64.(current_size lsr sector_shift) in let checksum = 0l in { features; data_offset; time_stamp; creator_application; creator_version; creator_host_os; original_size; current_size; geometry; disk_type; checksum; uid; saved_state } let to_string t = Printf.sprintf "{ features = [ %s ]; data_offset = %Lx; time_stamp = %lx; creator_application = %s; creator_version = %lx; creator_host_os = %s; original_size = %Ld; current_size = %Ld; geometry = %s; disk_type = %s; checksum = %ld; uid = %s; saved_state = %b }" (String.concat "; " (List.map Feature.to_string t.features)) t.data_offset t.time_stamp t.creator_application t.creator_version (Host_OS.to_string t.creator_host_os) t.original_size t.current_size (Geometry.to_string t.geometry) (Disk_type.to_string t.disk_type) t.checksum (Uuidm.to_string t.uid) t.saved_state let magic = "conectix" let expected_version = 0x00010000l let dump t = Printf.printf "VHD FOOTER\n"; Printf.printf "-=-=-=-=-=\n\n"; Printf.printf "cookie : %s\n" magic; Printf.printf "features : %s\n" (String.concat "," (List.map Feature.to_string t.features)); Printf.printf "format_version : 0x%lx\n" expected_version; Printf.printf "data_offset : 0x%Lx\n" t.data_offset; Printf.printf "time_stamp : %lu\n" t.time_stamp; Printf.printf "creator_application : %s\n" t.creator_application; Printf.printf "creator_version : 0x%lx\n" t.creator_version; Printf.printf "creator_host_os : %s\n" (Host_OS.to_string t.creator_host_os); Printf.printf "original_size : 0x%Lx\n" t.original_size; Printf.printf "current_size : 0x%Lx\n" t.current_size; Printf.printf "geometry : %s\n" (Geometry.to_string t.geometry); Printf.printf "disk_type : %s\n" (Disk_type.to_string t.disk_type); Printf.printf "checksum : %lu\n" t.checksum; Printf.printf "uid : %s\n" (Uuidm.to_string t.uid); Printf.printf "saved_state : %b\n\n" t.saved_state [%%cstruct type footer = { magic: uint8_t [@len 8]; features: uint32_t; version: uint32_t; data_offset: uint64_t; time_stamp: uint32_t; creator_application: uint8_t [@len 4]; creator_version: uint32_t; creator_host_os: uint32_t; original_size: uint64_t; current_size: uint64_t; cylinders: uint16_t; heads: uint8_t; sectors: uint8_t; disk_type: uint32_t; checksum: uint32_t; uid: uint8_t [@len 16]; saved_state: uint8_t; 427 zeroed } [@@big_endian]] let sizeof = 512 let marshal (buf: Cstruct.t) t = set_footer_magic magic 0 buf; set_footer_features buf (Feature.to_int32 t.features); set_footer_version buf expected_version; set_footer_data_offset buf t.data_offset; set_footer_time_stamp buf t.time_stamp; set_footer_creator_application t.creator_application 0 buf; set_footer_creator_version buf t.creator_version; set_footer_creator_host_os buf (Host_OS.to_int32 t.creator_host_os); set_footer_original_size buf t.original_size; set_footer_current_size buf t.current_size; set_footer_cylinders buf t.geometry.Geometry.cylinders; set_footer_heads buf t.geometry.Geometry.heads; set_footer_sectors buf t.geometry.Geometry.sectors; set_footer_disk_type buf (Disk_type.to_int32 t.disk_type); set_footer_checksum buf 0l; set_footer_uid (Uuidm.to_bytes t.uid) 0 buf; set_footer_saved_state buf (if t.saved_state then 1 else 0); let remaining = Cstruct.shift buf sizeof_footer in for i = 0 to 426 do Cstruct.set_uint8 remaining i 0 done; let checksum = Checksum.of_cstruct (Cstruct.sub buf 0 sizeof) in set_footer_checksum buf checksum; { t with checksum } let unmarshal (buf: Cstruct.t) = let open Rresult in let magic' = copy_footer_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Unsupported footer cookie: expected %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let features = Feature.of_int32 (get_footer_features buf) in let format_version = get_footer_version buf in ( if format_version <> expected_version then R.error (Failure (Printf.sprintf "Unsupported footer version: expected %lx, got %lx" expected_version format_version)) else R.ok () ) >>= fun () -> let data_offset = get_footer_data_offset buf in let time_stamp = get_footer_time_stamp buf in let creator_application = copy_footer_creator_application buf in let creator_version = get_footer_creator_version buf in let creator_host_os = Host_OS.of_int32 (get_footer_creator_host_os buf) in let original_size = get_footer_original_size buf in let current_size = get_footer_current_size buf in let cylinders = get_footer_cylinders buf in let heads = get_footer_heads buf in let sectors = get_footer_sectors buf in let geometry = { Geometry.cylinders; heads; sectors } in Disk_type.of_int32 (get_footer_disk_type buf) >>= fun disk_type -> let checksum = get_footer_checksum buf in let bytes = copy_footer_uid buf in ( match Uuidm.of_bytes bytes with | None -> R.error (Failure (Printf.sprintf "Failed to decode UUID: %s" (String.escaped bytes))) | Some uid -> R.ok uid ) >>= fun uid -> let saved_state = get_footer_saved_state buf = 1 in let expected_checksum = Checksum.(sub_int32 (of_cstruct (Cstruct.sub buf 0 sizeof)) checksum) in ( if checksum <> expected_checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" expected_checksum checksum)) else R.ok () ) >>= fun () -> R.ok { features; data_offset; time_stamp; creator_version; creator_application; creator_host_os; original_size; current_size; geometry; disk_type; checksum; uid; saved_state } let compute_checksum t = (* No alignment necessary *) let buf = Cstruct.of_bigarray (Bigarray.(Array1.create char c_layout sizeof)) in let t = marshal buf t in t.checksum end module Platform_code = struct type t = | None | Wi2r | Wi2k | W2ru | W2ku | Mac | MacX let wi2r = 0x57693272l let wi2k = 0x5769326Bl let w2ru = 0x57327275l let w2ku = 0x57326b75l let mac = 0x4d616320l let macx = 0x4d616358l let of_int32 = let open Rresult in function | 0l -> R.ok None | x when x = wi2r -> R.ok Wi2r | x when x = wi2k -> R.ok Wi2k | x when x = w2ru -> R.ok W2ru | x when x = w2ku -> R.ok W2ku | x when x = mac -> R.ok Mac | x when x = macx -> R.ok MacX | x -> R.error (Failure (Printf.sprintf "unknown platform_code: %lx" x)) let to_int32 = function | None -> 0l | Wi2r -> wi2r | Wi2k -> wi2k | W2ru -> w2ru | W2ku -> w2ku | Mac -> mac | MacX -> macx let to_string = function | None -> "None" | Wi2r -> "Wi2r [deprecated]" | Wi2k -> "Wi2k [deprecated]" | W2ru -> "W2ru" | W2ku -> "W2ku" | Mac -> "Mac " | MacX -> "MacX" end module Parent_locator = struct type t = { platform_code : Platform_code.t; WARNING WARNING - the following field is measured in * bytes * because Viridian VHDs do this . This is a deviation from the spec . When reading in this field , we multiply by 512 if the value is less than 511 do this. This is a deviation from the spec. When reading in this field, we multiply by 512 if the value is less than 511 *) platform_data_space : int32; Original unaltered value platform_data_length : int32; platform_data_offset : int64; platform_data : Cstruct.t; } let equal a b = true && (a.platform_code = b.platform_code) && (a.platform_data_space = b.platform_data_space) && (a.platform_data_space_original = b.platform_data_space_original) && (a.platform_data_length = b.platform_data_length) && (a.platform_data_offset = b.platform_data_offset) && (cstruct_equal a.platform_data b.platform_data) let null = { platform_code=Platform_code.None; platform_data_space=0l; platform_data_space_original=0l; platform_data_length=0l; platform_data_offset=0L; platform_data=Cstruct.create 0; } let to_string t = Printf.sprintf "(%s %lx %lx, %ld, 0x%Lx, %s)" (Platform_code.to_string t.platform_code) t.platform_data_space t.platform_data_space_original t.platform_data_length t.platform_data_offset (Cstruct.to_string t.platform_data) let to_filename t = match t.platform_code with | Platform_code.MacX -> (* Interpret as a NULL-terminated string *) let rec find_string from = if Cstruct.len t.platform_data <= from then t.platform_data else if Cstruct.get_uint8 t.platform_data from = 0 then Cstruct.sub t.platform_data 0 from else find_string (from + 1) in let path = Cstruct.to_string (find_string 0) in let expected_prefix = "file://" in let expected_prefix' = String.length expected_prefix in let startswith prefix x = let prefix' = String.length prefix and x' = String.length x in prefix' <= x' && (String.sub x 0 prefix' = prefix) in if startswith expected_prefix path then Some (String.sub path expected_prefix' (String.length path - expected_prefix')) else None | _ -> None [%%cstruct type header = { platform_code: uint32_t; platform_data_space: uint32_t; platform_data_length: uint32_t; reserved: uint32_t; platform_data_offset: uint64_t; } [@@big_endian]] let sizeof = sizeof_header let marshal (buf: Cstruct.t) t = set_header_platform_code buf (Platform_code.to_int32 t.platform_code); set_header_platform_data_space buf (Int32.shift_right_logical t.platform_data_space sector_shift); set_header_platform_data_length buf t.platform_data_length; set_header_reserved buf 0l; set_header_platform_data_offset buf t.platform_data_offset let unmarshal (buf: Cstruct.t) = let open Rresult.R.Infix in Platform_code.of_int32 (get_header_platform_code buf) >>= fun platform_code -> let platform_data_space_original = get_header_platform_data_space buf in The spec says this field should be stored in sectors . However some viridian vhds store the value in bytes . We assume that any value we read < 512l is actually in sectors ( 511l sectors is adequate space for a filename ) and any value > = 511l is in bytes . We store the unaltered on - disk value in [ platform_data_space_original ] and the decoded value in * bytes * in [ platform_data_space ] . store the value in bytes. We assume that any value we read < 512l is actually in sectors (511l sectors is adequate space for a filename) and any value >= 511l is in bytes. We store the unaltered on-disk value in [platform_data_space_original] and the decoded value in *bytes* in [platform_data_space]. *) let platform_data_space = if platform_data_space_original < 512l then Int32.shift_left platform_data_space_original sector_shift else platform_data_space_original in let platform_data_length = get_header_platform_data_length buf in let platform_data_offset = get_header_platform_data_offset buf in Rresult.R.return { platform_code; platform_data_space_original; platform_data_space; platform_data_length; platform_data_offset; platform_data = Cstruct.create 0 } let from_filename filename = Convenience function when creating simple vhds which have only one parent locator in the standard place ( offset 1536 bytes ) one parent locator in the standard place (offset 1536 bytes) *) let uri = "file://" ^ filename in let platform_data = Cstruct.create (String.length uri) in Cstruct.blit_from_string uri 0 platform_data 0 (String.length uri); let locator0 = { platform_code = Platform_code.MacX; platform_data_space = 512l; (* bytes *) platform_data_space_original=1l; (* sector *) platform_data_length = Int32.of_int (String.length uri); platform_data_offset = 1536L; platform_data; } in [| locator0; null; null; null; null; null; null; null; |] end module Header = struct type t = { (* cxsparse *) 0xFFFFFFFF table_offset : int64; 0x00010000l max_table_entries : int; block_size_sectors_shift : int; checksum : int32; parent_unique_id : Uuidm.t; parent_time_stamp : int32; parent_unicode_name : int array; parent_locators : Parent_locator.t array; } 1 lsl 12 = 4096 sectors = 2 MiB let create ~table_offset ~current_size ?(block_size_sectors_shift = default_block_size_sectors_shift) ?(checksum = 0l) ?(parent_unique_id = blank_uuid) ?(parent_time_stamp = 0l) ?(parent_unicode_name = [| |]) ?(parent_locators = Array.make 8 Parent_locator.null) () = let open Int64 in (* Round up the size to the next block *) let shift = block_size_sectors_shift + sector_shift in let current_size = ((current_size ++ (1L lsl shift -- 1L)) lsr shift) lsl shift in let max_table_entries = to_int (current_size lsr shift) in { table_offset; max_table_entries; block_size_sectors_shift; checksum; parent_unique_id; parent_time_stamp; parent_unicode_name; parent_locators } let to_string t = Printf.sprintf "{ table_offset = %Ld; max_table_entries = %d; block_size_sectors_shift = %d; checksum = %ld; parent_unique_id = %s; parent_time_stamp = %ld parent_unicode_name = %s; parent_locators = [| %s |]" t.table_offset t.max_table_entries t.block_size_sectors_shift t.checksum (Uuidm.to_string t.parent_unique_id) t.parent_time_stamp (UTF16.to_string t.parent_unicode_name) (String.concat "; " (List.map Parent_locator.to_string (Array.to_list t.parent_locators))) let equal a b = true && (a.table_offset = b.table_offset) && (a.max_table_entries = b.max_table_entries) && (a.block_size_sectors_shift = b.block_size_sectors_shift) && (a.checksum = b.checksum) && (a.parent_unique_id = b.parent_unique_id) && (a.parent_time_stamp = b.parent_time_stamp) && (a.parent_unicode_name = b.parent_unicode_name) && (Array.length a.parent_locators = (Array.length b.parent_locators)) && (try for i = 0 to Array.length a.parent_locators - 1 do if not(Parent_locator.equal a.parent_locators.(i) b.parent_locators.(i)) then raise Not_found (* arbitrary exn *) done; true with _ -> false) let set_parent t filename = let parent_locators = Parent_locator.from_filename filename in let parent_unicode_name = UTF16.of_utf8 filename in (* Safety check: this code assumes the single parent locator points to data in the same place. *) let not_implemented x = failwith (Printf.sprintf "unexpected vhd parent locators: %s" x) in for i = 1 to Array.length parent_locators - 1 do if not(Parent_locator.equal t.parent_locators.(i) parent_locators.(i)) then not_implemented (string_of_int i) done; if parent_locators.(0).Parent_locator.platform_data_space <> t.parent_locators.(0).Parent_locator.platform_data_space then not_implemented "platform_data_space"; if parent_locators.(0).Parent_locator.platform_data_offset <> t.parent_locators.(0).Parent_locator.platform_data_offset then not_implemented "platform_data_offset"; { t with parent_locators; parent_unicode_name } 1 bit per each 512 byte sector within the block let sizeof_bitmap t = 1 lsl (t.block_size_sectors_shift - 3) let magic = "cxsparse" XXX : the spec says 8 bytes containing 0xFFFFFFFF let expected_version = 0x00010000l let default_block_size = 1 lsl (default_block_size_sectors_shift + sector_shift) let dump t = Printf.printf "VHD HEADER\n"; Printf.printf "-=-=-=-=-=\n"; Printf.printf "cookie : %s\n" magic; Printf.printf "data_offset : %Lx\n" expected_data_offset; Printf.printf "table_offset : %Lu\n" t.table_offset; Printf.printf "header_version : 0x%lx\n" expected_version; Printf.printf "max_table_entries : 0x%x\n" t.max_table_entries; Printf.printf "block_size : 0x%x\n" ((1 lsl t.block_size_sectors_shift) * sector_size); Printf.printf "checksum : %lu\n" t.checksum; Printf.printf "parent_unique_id : %s\n" (Uuidm.to_string t.parent_unique_id); Printf.printf "parent_time_stamp : %lu\n" t.parent_time_stamp; let s = match UTF16.to_utf8 t.parent_unicode_name with | Ok s -> s | Error _e -> Printf.sprintf "<Unable to decode UTF-16: %s>" (String.concat " " (List.map (fun x -> Printf.sprintf "%02x" x) (Array.to_list t.parent_unicode_name))) in Printf.printf "parent_unicode_name : '%s' (%d bytes)\n" s (Array.length t.parent_unicode_name); Printf.printf "parent_locators : %s\n" (String.concat "\n " (List.map Parent_locator.to_string (Array.to_list t.parent_locators))) [%%cstruct type header = { magic: uint8_t [@len 8]; data_offset: uint64_t; table_offset: uint64_t; header_version: uint32_t; max_table_entries: uint32_t; block_size: uint32_t; checksum: uint32_t; parent_unique_id: uint8_t [@len 16]; parent_time_stamp: uint32_t; reserved: uint32_t; parent_unicode_name: uint8_t [@len 512]; 8 parent locators 256 reserved } [@@big_endian]] let sizeof = sizeof_header + (8 * Parent_locator.sizeof) + 256 let unicode_offset = 8 + 8 + 8 + 4 + 4 + 4 + 4 + 16 + 4 + 4 let marshal (buf: Cstruct.t) t = set_header_magic magic 0 buf; set_header_data_offset buf expected_data_offset; set_header_table_offset buf t.table_offset; set_header_header_version buf expected_version; set_header_max_table_entries buf (Int32.of_int t.max_table_entries); set_header_block_size buf (Int32.of_int (1 lsl (t.block_size_sectors_shift + sector_shift))); set_header_checksum buf 0l; set_header_parent_unique_id (Uuidm.to_bytes t.parent_unique_id) 0 buf; set_header_parent_time_stamp buf t.parent_time_stamp; set_header_reserved buf 0l; for i = 0 to 511 do Cstruct.set_uint8 buf (unicode_offset + i) 0 done; let (_: Cstruct.t) = UTF16.marshal (Cstruct.shift buf unicode_offset) t.parent_unicode_name in let parent_locators = Cstruct.shift buf (unicode_offset + 512) in for i = 0 to 7 do let buf = Cstruct.shift parent_locators (Parent_locator.sizeof * i) in let pl = if Array.length t.parent_locators <= i then Parent_locator.null else t.parent_locators.(i) in Parent_locator.marshal buf pl done; let reserved = Cstruct.shift parent_locators (8 * Parent_locator.sizeof) in for i = 0 to 255 do Cstruct.set_uint8 reserved i 0 done; let checksum = Checksum.of_cstruct (Cstruct.sub buf 0 sizeof) in set_header_checksum buf checksum; { t with checksum } let unmarshal (buf: Cstruct.t) = let open Rresult in let open Rresult.R.Infix in let magic' = copy_header_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Expected cookie %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let data_offset = get_header_data_offset buf in ( if data_offset <> expected_data_offset then R.error (Failure (Printf.sprintf "Expected header data_offset %Lx, got %Lx" expected_data_offset data_offset)) else R.ok () ) >>= fun () -> let table_offset = get_header_table_offset buf in let header_version = get_header_header_version buf in ( if header_version <> expected_version then R.error (Failure (Printf.sprintf "Expected header_version %lx, got %lx" expected_version header_version)) else R.ok () ) >>= fun () -> let max_table_entries = get_header_max_table_entries buf in ( if Int64.of_int32 max_table_entries > Int64.of_int Sys.max_array_length then R.error (Failure (Printf.sprintf "expected max_table_entries < %d, got %ld" Sys.max_array_length max_table_entries)) else R.ok (Int32.to_int max_table_entries) ) >>= fun max_table_entries -> let block_size = get_header_block_size buf in let rec to_shift acc = function | 0 -> R.error (Failure "block size is zero") | 1 -> R.ok acc | n when n mod 2 = 1 -> R.error (Failure (Printf.sprintf "block_size is not a power of 2: %lx" block_size)) | n -> to_shift (acc + 1) (n / 2) in to_shift 0 (Int32.to_int block_size) >>= fun block_size_shift -> let block_size_sectors_shift = block_size_shift - sector_shift in let checksum = get_header_checksum buf in let bytes = copy_header_parent_unique_id buf in ( match (Uuidm.of_bytes bytes) with | None -> R.error (Failure (Printf.sprintf "Failed to decode UUID: %s" (String.escaped bytes))) | Some x -> R.ok x ) >>= fun parent_unique_id -> let parent_time_stamp = get_header_parent_time_stamp buf in UTF16.unmarshal (Cstruct.sub buf unicode_offset 512) 512 >>= fun parent_unicode_name -> let parent_locators_buf = Cstruct.shift buf (unicode_offset + 512) in let parent_locators = Array.make 8 Parent_locator.null in let rec loop = function | 8 -> R.ok () | i -> let buf = Cstruct.shift parent_locators_buf (Parent_locator.sizeof * i) in Parent_locator.unmarshal buf >>= fun p -> parent_locators.(i) <- p; loop (i + 1) in loop 0 >>= fun () -> let expected_checksum = Checksum.(sub_int32 (of_cstruct (Cstruct.sub buf 0 sizeof)) checksum) in ( if checksum <> expected_checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" expected_checksum checksum)) else R.ok () ) >>= fun () -> R.ok { table_offset; max_table_entries; block_size_sectors_shift; checksum; parent_unique_id; parent_time_stamp; parent_unicode_name; parent_locators } let compute_checksum t = (* No alignment necessary *) let buf = Cstruct.of_bigarray (Bigarray.(Array1.create char c_layout sizeof)) in let t = marshal buf t in t.checksum end module BAT = struct type t = { max_table_entries: int; data: Cstruct.t; mutable highest_value: int32; } let unused = 0xffffffffl let unused' = 0xffffffffL let get t i = Cstruct.BE.get_uint32 t.data (i * 4) let set t i j = Cstruct.BE.set_uint32 t.data (i * 4) j; (* TODO: we need a proper free 'list' if we are going to allow blocks to be deallocated eg through TRIM *) if j <> unused && j > t.highest_value then t.highest_value <- j let length t = t.max_table_entries let int64_from_uint32 u32 = let (&&&) = Int64.logand in Int64.(of_int32 u32 &&& 0x0000_0000_ffff_ffffL) let fold f t initial = let rec loop acc i = if i = t.max_table_entries then acc else let v = get t i |> int64_from_uint32 in if v = unused' then loop acc (i + 1) else loop (f i v acc) (i + 1) in loop initial 0 let equal t1 t2 = true && t1.highest_value = t2.highest_value && t1.max_table_entries = t2.max_table_entries && (try for i = 0 to length t1 - 1 do if get t1 i <> get t2 i then raise Not_found done; true with Not_found -> false) We always round up the size of the BAT to the next sector let sizeof_bytes (header: Header.t) = let size_needed = header.Header.max_table_entries * 4 in The BAT is always extended to a sector boundary roundup_sector size_needed let of_buffer (header: Header.t) (data: Cstruct.t) = for i = 0 to (Cstruct.len data) / 4 - 1 do Cstruct.BE.set_uint32 data (i * 4) unused done; { max_table_entries = header.Header.max_table_entries; data; highest_value = -1l; } let to_string (t: t) = let used = ref [] in for i = 0 to length t - 1 do if get t i <> unused then used := (i, get t i) :: !used done; Printf.sprintf "(%d rounded to %d)[ %s ] with highest_value = %ld" (length t) (Cstruct.len t.data / 4) (String.concat "; " (List.map (fun (i, x) -> Printf.sprintf "(%d, %lx)" i x) (List.rev !used))) t.highest_value let unmarshal (buf: Cstruct.t) (header: Header.t) = let t = { data = buf; max_table_entries = header.Header.max_table_entries; highest_value = -1l; } in for i = 0 to length t - 1 do if get t i > t.highest_value then t.highest_value <- get t i done; t let marshal (buf: Cstruct.t) (t: t) = Cstruct.blit t.data 0 buf 0 (Cstruct.len t.data) let dump t = Printf.printf "BAT\n"; Printf.printf "-=-\n"; for i = 0 to t.max_table_entries - 1 do Printf.printf "%d\t:0x%lx\n" i (get t i) done end module Batmap_header = struct [%%cstruct type header = { magic: uint8_t [@len 8]; offset: uint64_t; size_in_sectors: uint32_t; major_version: uint16_t; minor_version: uint16_t; checksum: uint32_t; marker: uint8_t; } [@@big_endian]] let magic = "tdbatmap" let current_major_version = 1 let current_minor_version = 2 let sizeof = roundup_sector sizeof_header type t = { offset: int64; size_in_sectors: int; major_version: int; minor_version: int; checksum: int32; marker: int } let unmarshal (buf: Cstruct.t) = let open Rresult in let open Rresult.R.Infix in let magic' = copy_header_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Expected cookie %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let offset = get_header_offset buf in let size_in_sectors = Int32.to_int (get_header_size_in_sectors buf) in let major_version = get_header_major_version buf in let minor_version = get_header_minor_version buf in ( if major_version <> current_major_version || minor_version <> current_minor_version then R.error (Failure (Printf.sprintf "Unexpected BATmap version: %d.%d" major_version minor_version)) else R.ok () ) >>= fun () -> let checksum = get_header_checksum buf in let marker = get_header_marker buf in R.ok { offset; size_in_sectors; major_version; minor_version; checksum; marker } let marshal (buf: Cstruct.t) (t: t) = for i = 0 to Cstruct.len buf - 1 do Cstruct.set_uint8 buf i 0 done; set_header_offset buf t.offset; set_header_size_in_sectors buf (Int32.of_int t.size_in_sectors); set_header_major_version buf t.major_version; set_header_minor_version buf t.minor_version; set_header_checksum buf t.checksum; set_header_marker buf t.marker let offset (x: Header.t) = Int64.(x.Header.table_offset ++ (of_int (BAT.sizeof_bytes x))) end module Batmap = struct type t = Cstruct.t let sizeof_bytes (x: Header.t) = (x.Header.max_table_entries + 7) lsr 3 let sizeof (x: Header.t) = roundup_sector (sizeof_bytes x) let set t n = let byte = Cstruct.get_uint8 t (n / 8) in let bit = n mod 8 in let mask = 0x80 lsr bit in Cstruct.set_uint8 t (n / 8) (byte lor mask) let get t n = let byte = Cstruct.get_uint8 t (n / 8) in let bit = n mod 8 in let mask = 0x80 lsr bit in byte land mask <> mask let unmarshal (buf: Cstruct.t) (h: Header.t) (bh: Batmap_header.t) = let open Rresult in let open Rresult.R.Infix in let needed = Cstruct.sub buf 0 (sizeof_bytes h) in let checksum = Checksum.of_cstruct buf in ( if checksum <> bh.Batmap_header.checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" bh.Batmap_header.checksum checksum)) else R.ok () ) >>= fun () -> R.ok needed end module Bitmap = struct type t = | Full | Partial of Cstruct.t let get t sector_in_block = match t with | Full -> true | Partial buf -> let sector_in_block = Int64.to_int sector_in_block in let bitmap_byte = Cstruct.get_uint8 buf (sector_in_block / 8) in let bitmap_bit = sector_in_block mod 8 in let mask = 0x80 lsr bitmap_bit in (bitmap_byte land mask) = mask let set t sector_in_block = match t with | Full -> None (* already set, no on-disk update required *) | Partial buf -> let sector_in_block = Int64.to_int sector_in_block in let bitmap_byte = Cstruct.get_uint8 buf (sector_in_block / 8) in let bitmap_bit = sector_in_block mod 8 in let mask = 0x80 lsr bitmap_bit in if (bitmap_byte land mask) = mask then None (* already set, no on-disk update required *) else begin (* not set, we must update the sector on disk *) let byte_offset = sector_in_block / 8 in Cstruct.set_uint8 buf byte_offset (bitmap_byte lor mask); let sector_start = (byte_offset lsr sector_shift) lsl sector_shift in Some (Int64.of_int sector_start, Cstruct.sub buf sector_start sector_size) end let setv t sector_in_block remaining = let rec loop updates sector remaining = match updates, remaining with | None, 0L -> None | Some (offset, bufs), 0L -> Some (offset, List.rev bufs) | _, _n -> let sector' = Int64.succ sector in let remaining' = Int64.pred remaining in begin match updates, set t sector with | _, None -> loop updates sector' remaining' | Some (offset, _), Some (offset', _) when offset = offset' -> loop updates sector' remaining' | Some (offset, bufs), Some (offset', buf) when offset' = Int64.succ offset -> loop (Some(offset, buf :: bufs)) sector' remaining' | None, Some (offset', buf) -> loop (Some (offset', [ buf ])) sector' remaining' | _, _ -> assert false (* bitmap sector offsets must be contiguous by construction *) end in loop None sector_in_block remaining end module Bitmap_cache = struct type t = { cache: (int * Bitmap.t) option ref; (* effective only for streaming *) all_zeroes: Cstruct.t; all_ones: Cstruct.t; } let all_ones size = if size = Cstruct.len sector_all_ones then sector_all_ones else constant size 0xff let all_zeroes size = if size = Cstruct.len sector_all_zeroes then sector_all_zeroes else constant size 0x0 let make t = let sizeof_bitmap = Header.sizeof_bitmap t in let cache = ref None in let all_ones = all_ones sizeof_bitmap in let all_zeroes = all_zeroes sizeof_bitmap in { cache; all_ones; all_zeroes } end module Sector = struct type t = Cstruct.t let dump t = if Cstruct.len t = 0 then Printf.printf "Empty sector\n" else for i=0 to Cstruct.len t - 1 do if (i mod 16 = 15) then Printf.printf "%02x\n" (Cstruct.get_uint8 t i) else Printf.printf "%02x " (Cstruct.get_uint8 t i) done end module Vhd = struct type 'a t = { filename: string; rw: bool; handle: 'a; header: Header.t; footer: Footer.t; parent: 'a t option; bat: BAT.t; batmap: (Batmap_header.t * Batmap.t) option; bitmap_cache: Bitmap_cache.t; } let resize t new_size = if new_size > t.footer.Footer.original_size then invalid_arg "Vhd.resize"; { t with footer = { t.footer with Footer.current_size = new_size } } let rec dump t = Printf.printf "VHD file: %s\n" t.filename; Header.dump t.header; Footer.dump t.footer; match t.parent with | None -> () | Some parent -> dump parent let used_max_table_entries t = Some tools will create a larger - than - necessary BAT for small .vhds to allow the virtual size to be changed later . allow the virtual size to be changed later. *) let max_table_entries = t.header.Header.max_table_entries in let block_size_bytes_shift = t.header.Header.block_size_sectors_shift + sector_shift in let current_size_blocks = Int64.(to_int (shift_right (add t.footer.Footer.current_size (sub (1L lsl block_size_bytes_shift) 1L)) block_size_bytes_shift)) in if current_size_blocks > max_table_entries then failwith (Printf.sprintf "max_table_entries (%d) < current size (%d) expressed in blocks (1 << %d)" max_table_entries current_size_blocks block_size_bytes_shift); current_size_blocks type block_marker = | Start of (string * int64) | End of (string * int64) (* Nb this only copes with dynamic or differencing disks *) let check_overlapping_blocks t = let tomarkers name start length = [Start (name,start); End (name,Int64.sub (Int64.add start length) 1L)] in let blocks = tomarkers "footer_at_top" 0L 512L in let blocks = (tomarkers "header" t.footer.Footer.data_offset 1024L) @ blocks in let blocks = if t.footer.Footer.disk_type = Disk_type.Differencing_hard_disk then begin let locators = Array.mapi (fun i l -> (i,l)) t.header.Header.parent_locators in let locators = Array.to_list locators in let open Parent_locator in let locators = List.filter (fun (_,l) -> l.platform_code <> Platform_code.None) locators in let locations = List.map (fun (i,l) -> let name = Printf.sprintf "locator block %d" i in let start = l.platform_data_offset in let length = Int64.of_int32 l.platform_data_space in tomarkers name start length) locators in (List.flatten locations) @ blocks end else blocks in let bat_start = t.header.Header.table_offset in let bat_size = Int64.of_int t.header.Header.max_table_entries in let bat = tomarkers "BAT" bat_start bat_size in let blocks = bat @ blocks in let bat_blocks = ref [] in for i = 0 to BAT.length t.bat - 1 do let e = BAT.get t.bat i in if e <> BAT.unused then begin let name = Printf.sprintf "block %d" i in let start = Int64.mul 512L (Int64.of_int32 (BAT.get t.bat i)) in let size = Int64.shift_left 1L (t.header.Header.block_size_sectors_shift + sector_shift) in bat_blocks := (tomarkers name start size) @ !bat_blocks end done; let blocks = blocks @ !bat_blocks in let get_pos = function | Start (_,a) -> a | End (_,a) -> a in let to_string = function | Start (name,pos) -> Printf.sprintf "%Lx START of section '%s'" pos name | End (name,pos) -> Printf.sprintf "%Lx END of section '%s'" pos name in let l = List.sort (fun a b -> compare (get_pos a) (get_pos b)) blocks in List.iter (fun marker -> Printf.printf "%s\n" (to_string marker)) l exception EmptyVHD let get_top_unused_offset header bat = let open Int64 in try let last_block_start = let max_entry = bat.BAT.highest_value in if max_entry = -1l then raise EmptyVHD; 512L ** (of_int32 max_entry) in last_block_start ++ (of_int (Header.sizeof_bitmap header)) ++ (1L lsl (header.Header.block_size_sectors_shift + sector_shift)) with | EmptyVHD -> let pos = add header.Header.table_offset (mul 4L (of_int header.Header.max_table_entries)) in pos (* TODO: need a quicker block allocator *) let get_free_sector header bat = let open Int64 in let next_free_byte = get_top_unused_offset header bat in to_int32 ((next_free_byte ++ 511L) lsr sector_shift) module Field = struct (** Dynamically-typed field-level access *) type 'a f = { name: string; get: 'a t -> string; } let _features = "features" let _data_offset = "data-offset" let _timestamp = "time-stamp" let _creator_application = "creator-application" let _creator_version = "creator_version" let _creator_host_os = "creator-host-os" let _original_size = "original-size" let _current_size = "current-size" let _geometry = "geometry" let _disk_type = "disk-type" let _footer_checksum = "footer-checksum" let _uuid = "uuid" let _saved_state = "saved-state" let _table_offset = "table-offset" let _max_table_entries = "max-table-entries" let _block_size_sectors_shift = "block-size-sectors-shift" let _header_checksum = "header-checksum" let _parent_uuid = "parent_unique_id" let _parent_time_stamp = "parent-time-stamp" let _parent_unicode_name = "parent-unicode-name" let _parent_locator_prefix = "parent-locator-" let _parent_locator_prefix_len = String.length _parent_locator_prefix let _batmap_version = "batmap-version" let _batmap_offset = "batmap-offset" let _batmap_size_in_sectors = "batmap-size-in-sectors" let _batmap_checksum = "batmap-checksum" let list = [ _features; _data_offset; _timestamp; _creator_application; _creator_version; _creator_host_os; _original_size; _current_size; _geometry; _disk_type; _footer_checksum; _uuid; _saved_state; _table_offset; _max_table_entries; _block_size_sectors_shift; _header_checksum; _parent_uuid; _parent_time_stamp; _parent_unicode_name ] @ (List.map (fun x -> _parent_locator_prefix ^ (string_of_int x)) [0; 1; 2; 3; 4; 5; 6;7] ) @ [ _batmap_version; _batmap_offset; _batmap_size_in_sectors; _batmap_checksum ] let startswith prefix x = let prefix' = String.length prefix and x' = String.length x in prefix' <= x' && (String.sub x 0 prefix' = prefix) let get t key = let opt f = function | None -> None | Some x -> Some (f x) in if key = _features then Some (String.concat ", " (List.map Feature.to_string t.footer.Footer.features)) else if key = _data_offset then Some (Int64.to_string t.footer.Footer.data_offset) else if key = _timestamp then Some (Int32.to_string t.footer.Footer.time_stamp) else if key = _creator_application then Some t.footer.Footer.creator_application else if key = _creator_version then Some (Int32.to_string t.footer.Footer.creator_version) else if key = _creator_host_os then Some (Host_OS.to_string t.footer.Footer.creator_host_os) else if key = _original_size then Some (Int64.to_string t.footer.Footer.original_size) else if key = _current_size then Some (Int64.to_string t.footer.Footer.current_size) else if key = _geometry then Some (Geometry.to_string t.footer.Footer.geometry) else if key = _disk_type then Some (Disk_type.to_string t.footer.Footer.disk_type) else if key = _footer_checksum then Some (Int32.to_string t.footer.Footer.checksum) else if key = _uuid then Some (Uuidm.to_string t.footer.Footer.uid) else if key = _saved_state then Some (string_of_bool t.footer.Footer.saved_state) else if key = _table_offset then Some (Int64.to_string t.header.Header.table_offset) else if key = _max_table_entries then Some (string_of_int t.header.Header.max_table_entries) else if key = _block_size_sectors_shift then Some (string_of_int t.header.Header.block_size_sectors_shift) else if key = _header_checksum then Some (Int32.to_string t.header.Header.checksum) else if key = _parent_uuid then Some (Uuidm.to_string t.header.Header.parent_unique_id) else if key = _parent_time_stamp then Some (Int32.to_string t.header.Header.parent_time_stamp) else if key = _parent_unicode_name then Some (UTF16.to_utf8_exn t.header.Header.parent_unicode_name) else if startswith _parent_locator_prefix key then begin try let i = int_of_string (String.sub key _parent_locator_prefix_len (String.length key - _parent_locator_prefix_len)) in Some (Parent_locator.to_string t.header.Header.parent_locators.(i)) with _ -> None end else if key = _batmap_version then opt (fun (t, _) -> Printf.sprintf "%d.%d" t.Batmap_header.major_version t.Batmap_header.minor_version) t.batmap else if key = _batmap_offset then opt (fun (t, _) -> Int64.to_string t.Batmap_header.offset) t.batmap else if key = _batmap_size_in_sectors then opt (fun (t, _) -> string_of_int t.Batmap_header.size_in_sectors) t.batmap else if key = _batmap_checksum then opt (fun (t, _) -> Int32.to_string t.Batmap_header.checksum) t.batmap else None type 'a t = 'a f end end module Raw = struct type 'a t = { filename: string; handle: 'a; } end type size = { total: int64; TODO : rename to ' data ' empty: int64; copy: int64; } let empty = { total = 0L; metadata = 0L; empty = 0L; copy = 0L } module Stream = functor(A: S.ASYNC) -> struct open A type 'a ll = | Cons of 'a * (unit -> 'a ll t) | End let rec iter f = function | Cons(x, rest) -> f x >>= fun () -> rest () >>= fun x -> iter f x | End -> return () let rec fold_left f initial xs = match xs with | End -> return initial | Cons (x, rest) -> f initial x >>= fun initial' -> rest () >>= fun xs -> fold_left f initial' xs type 'a stream = { elements: 'a Element.t ll; size: size; } end module Fragment = struct type t = | Header of Header.t | Footer of Footer.t | BAT of BAT.t | Batmap of Batmap.t | Block of int64 * Cstruct.t end module From_input = functor (I: S.INPUT) -> struct open I type 'a ll = | Cons of 'a * (unit -> 'a ll t) | End (* Convert Error values into failed threads *) let (>>|=) m f = match m with | Error e -> fail e | Ok x -> f x (* Operator to avoid bracket overload *) let (>+>) m f = return (Cons(m, f)) open Memory let openstream size_opt fd = let buffer = alloc Footer.sizeof in read fd buffer >>= fun () -> Footer.unmarshal buffer >>|= fun footer -> Fragment.Footer footer >+> fun () -> (* header is at the Footer data_offset *) skip_to fd footer.Footer.data_offset >>= fun () -> let buffer = alloc Header.sizeof in read fd buffer >>= fun () -> Header.unmarshal buffer >>|= fun header -> Fragment.Header header >+> fun () -> BAT is at the table offset skip_to fd header.Header.table_offset >>= fun () -> let buffer = alloc (BAT.sizeof_bytes header) in read fd buffer >>= fun () -> let bat = BAT.unmarshal buffer header in Fragment.BAT bat >+> fun () -> (* Create a mapping of physical sector -> virtual sector *) let module M = Map.Make(Int64) in let phys_to_virt = BAT.fold (fun idx sector acc -> M.add sector idx acc) bat M.empty in let bitmap = alloc (Header.sizeof_bitmap header) in let data = alloc (1 lsl (header.Header.block_size_sectors_shift + sector_shift)) in let rec block blocks andthen = if M.is_empty blocks then andthen () else let s, idx = M.min_binding blocks in let physical_block_offset = Int64.(shift_left (of_int idx) header.Header.block_size_sectors_shift) in skip_to fd Int64.(shift_left s sector_shift) >>= fun () -> read fd bitmap >>= fun () -> let bitmap = Bitmap.Partial bitmap in let num_sectors = 1 lsl header.Header.block_size_sectors_shift in (* Compute the length of a 'span' of sectors in the bitmap, so we can coalesce our reads into large chunks *) let length_of_span from = let this = Bitmap.get bitmap (Int64.of_int from) in let rec loop length i = if i < num_sectors && Bitmap.get bitmap (Int64.of_int i) = this then loop (length+1) (i+1) else length in loop 0 from in let rec sector i andthen = if i = num_sectors then andthen () else let len = length_of_span i in let frag = Cstruct.sub data 0 (len lsl sector_shift) in read fd frag >>= fun () -> let physical_offset = Int64.(add physical_block_offset (of_int i)) in if Bitmap.get bitmap (Int64.of_int i) then Fragment.Block(physical_offset, frag) >+> fun () -> sector (i + len) andthen else sector (i + len) andthen in sector 0 (fun () -> block (M.remove s blocks) andthen) in block phys_to_virt (fun () -> let buffer = alloc Footer.sizeof in ( match size_opt with | None -> return () | Some s -> let (&&&) = Int64.logand in let footer_offset = Int64.(sub s 1L &&& lognot 0b1_1111_1111L) in offset is last 512 - byte - aligned block in the file skip_to fd footer_offset) >>= fun () -> read fd buffer >>= fun () -> Footer.unmarshal buffer >>|= fun footer -> Fragment.Footer footer >+> fun () -> return End) end module From_file = functor(F: S.FILE) -> struct open F (* Convert Error values into failed threads *) let (>>|=) m f = match m with | Error e -> fail e | Ok x -> f x (* Search a path for a filename *) let search filename path = let rec loop = function | [] -> return None | x :: xs -> let possibility = Filename.concat x filename in ( F.exists possibility >>= function | true -> return (Some possibility) | false -> loop xs ) in if Filename.is_relative filename then loop path else loop [ "" ] let rec unaligned_really_write fd offset buffer = let open Int64 in let sector_start = (offset lsr sector_shift) lsl sector_shift in let current = Memory.alloc sector_size in really_read fd sector_start current >>= fun () -> let adjusted_len = offset ++ (of_int (Cstruct.len buffer)) -- sector_start in let write_this_time = max adjusted_len 512L in let remaining_to_write = adjusted_len -- write_this_time in let useful_bytes_to_write = Stdlib.min (Cstruct.len buffer) (to_int (write_this_time -- offset ++ sector_start)) in Cstruct.blit buffer 0 current (to_int (offset -- sector_start)) useful_bytes_to_write; really_write fd sector_start current >>= fun () -> if remaining_to_write <= 0L then return () else unaligned_really_write fd (offset ++ (of_int useful_bytes_to_write)) (Cstruct.shift buffer useful_bytes_to_write) module Footer_IO = struct let read fd pos = let buf = Memory.alloc Footer.sizeof in really_read fd pos buf >>= fun () -> Footer.unmarshal buf >>|= fun x -> return x let write sector fd pos t = let t = Footer.marshal sector t in really_write fd pos sector >>= fun () -> return t end module Parent_locator_IO = struct open Parent_locator let read fd t = let l = Int32.to_int t.platform_data_length in let l_rounded = roundup_sector l in ( if l_rounded = 0 then return (Cstruct.create 0) else let platform_data = Memory.alloc l_rounded in really_read fd t.platform_data_offset platform_data >>= fun () -> return platform_data ) >>= fun platform_data -> let platform_data = Cstruct.sub platform_data 0 l in return { t with platform_data } let write fd t = (* Only write those that actually have a platform_code *) if t.platform_code <> Platform_code.None then unaligned_really_write fd t.platform_data_offset t.platform_data else return () end module Header_IO = struct open Header let get_parent_filename t search_path = let rec test checked_so_far n = if n >= Array.length t.parent_locators then fail (Failure (Printf.sprintf "Failed to find parent (tried [ %s ] with search_path %s)" (String.concat "; " checked_so_far) (String.concat "; " search_path) )) else let l = t.parent_locators.(n) in let open Parent_locator in match to_filename l with | Some path -> ( search path search_path >>= function | None -> test (path :: checked_so_far) (n + 1) | Some path -> return path ) | None -> test checked_so_far (n + 1) in test [] 0 let read fd pos = let buf = Memory.alloc sizeof in really_read fd pos buf >>= fun () -> unmarshal buf >>|= fun t -> (* Read the parent_locator data *) let rec read_parent_locator = function | 8 -> return () | n -> let p = t.parent_locators.(n) in Parent_locator_IO.read fd p >>= fun p -> t.parent_locators.(n) <- p; read_parent_locator (n + 1) in read_parent_locator 0 >>= fun () -> return t let write buf fd pos t = let t' = marshal buf t in (* Write the parent_locator data *) let rec write_parent_locator = function | 8 -> return () | n -> let p = t.parent_locators.(n) in Parent_locator_IO.write fd p >>= fun () -> write_parent_locator (n + 1) in really_write fd pos buf >>= fun () -> write_parent_locator 0 >>= fun () -> return t' end module BAT_IO = struct open BAT let read fd (header: Header.t) = let buf = Memory.alloc (sizeof_bytes header) in really_read fd header.Header.table_offset buf >>= fun () -> return (unmarshal buf header) let write buf fd (header: Header.t) t = marshal buf t; really_write fd header.Header.table_offset buf end module Batmap_IO = struct let read fd (header: Header.t) = let buf = Memory.alloc Batmap_header.sizeof in really_read fd (Batmap_header.offset header) buf >>= fun () -> match Batmap_header.unmarshal buf with | Error _ -> return None | Ok h -> let batmap = Memory.alloc (h.Batmap_header.size_in_sectors * sector_size) in ( really_read fd h.Batmap_header.offset batmap >>= fun () -> match Batmap.unmarshal batmap header h with | Error _ -> return None | Ok batmap -> return (Some (h, batmap))) end module Bitmap_IO = struct open Bitmap let read fd (header: Header.t) (bat: BAT.t) (block: int) = let open Int64 in let pos = (of_int32 (BAT.get bat block)) lsl sector_shift in let bitmap = Memory.alloc (Header.sizeof_bitmap header) in really_read fd pos bitmap >>= fun () -> return (Partial bitmap) end module Vhd_IO = struct open Vhd let write_trailing_footer buf handle t = let sector = Vhd.get_free_sector t.Vhd.header t.Vhd.bat in let offset = Int64.(shift_left (of_int32 sector) sector_shift) in Footer_IO.write buf handle offset t.Vhd.footer >>= fun _ -> return () let write_metadata t = let footer_buf = Memory.alloc Footer.sizeof in Footer_IO.write footer_buf t.Vhd.handle 0L t.Vhd.footer >>= fun footer -> (* This causes the file size to be increased so we can successfully read empty blocks in places like the parent locators *) write_trailing_footer footer_buf t.Vhd.handle t >>= fun () -> let t ={ t with Vhd.footer } in let buf = Memory.alloc Header.sizeof in Header_IO.write buf t.Vhd.handle t.Vhd.footer.Footer.data_offset t.Vhd.header >>= fun header -> let t = { t with Vhd.header } in let buf = Memory.alloc (BAT.sizeof_bytes header) in BAT_IO.write buf t.Vhd.handle t.Vhd.header t.Vhd.bat >>= fun () -> (* Assume the data is there, or will be written later *) return t let create_dynamic ~filename ~size ?(uuid = Uuidm.v `V4) ?(saved_state=false) ?(features=[]) () = The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT *) let data_offset = 512L in let table_offset = 2048L in let open Int64 in let header = Header.create ~table_offset ~current_size:size () in let size = (of_int header.Header.max_table_entries) lsl (header.Header.block_size_sectors_shift + sector_shift) in let footer = Footer.create ~features ~data_offset ~current_size:size ~disk_type:Disk_type.Dynamic_hard_disk ~uid:uuid ~saved_state () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let batmap = None in let bitmap_cache = Bitmap_cache.make header in F.create filename >>= fun handle -> let t = { filename; rw = true; handle; header; footer; parent = None; bat; batmap; bitmap_cache } in write_metadata t >>= fun t -> return t let make_relative_path base target = assert (not (Filename.is_relative base)); assert (not (Filename.is_relative target)); let to_list path = let rec loop acc path = if Filename.dirname path = "/" then Filename.basename path :: acc else loop (Filename.basename path :: acc) (Filename.dirname path) in loop [] path in let base = to_list (Filename.dirname base) in let target = to_list target in (* remove common preceeding path elements *) let rec remove_common = function | [], y -> [], y | x, [] -> x, [] | x :: xs, y :: ys when x = y -> remove_common (xs, ys) | xs, ys -> xs, ys in let base, target = remove_common (base, target) in let base = List.map (fun _ -> "..") base in String.concat "/" (base @ target) let create_difference ~filename ~parent ?(relative_path = true) ?(uuid=Uuidm.v `V4) ?(saved_state=false) ?(features=[]) () = (* We use the same basic file layout as in create_dynamic *) let data_offset = 512L in let table_offset = 2048L in let footer = Footer.create ~features ~data_offset ~time_stamp:(F.now ()) ~current_size:parent.Vhd.footer.Footer.current_size ~disk_type:Disk_type.Differencing_hard_disk ~uid:uuid ~saved_state () in let parent_filename = if relative_path then make_relative_path filename parent.Vhd.filename else parent.Vhd.filename in let parent_locators = Parent_locator.from_filename parent_filename in F.get_modification_time parent.Vhd.filename >>= fun parent_time_stamp -> let header = Header.create ~table_offset ~current_size:parent.Vhd.footer.Footer.current_size ~block_size_sectors_shift:parent.Vhd.header.Header.block_size_sectors_shift ~parent_unique_id:parent.Vhd.footer.Footer.uid ~parent_time_stamp ~parent_unicode_name:(UTF16.of_utf8 parent.Vhd.filename) ~parent_locators () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in F.create filename >>= fun handle -> (* Re-open the parent file to avoid sharing the underlying file descriptor and having to perform reference counting *) F.openfile parent.Vhd.filename false >>= fun parent_handle -> let parent = { parent with handle = parent_handle } in let batmap = None in let bitmap_cache = Bitmap_cache.make header in let t = { filename; rw = true; handle; header; footer; parent = Some parent; bat; batmap; bitmap_cache } in write_metadata t >>= fun t -> return t let rec openchain ?(path = ["."]) filename rw = search filename path >>= function | None -> fail (Failure (Printf.sprintf "Failed to find %s (search path = %s)" filename (String.concat ":" path))) | Some filename -> F.openfile filename rw >>= fun handle -> Footer_IO.read handle 0L >>= fun footer -> Header_IO.read handle (Int64.of_int Footer.sizeof) >>= fun header -> BAT_IO.read handle header >>= fun bat -> (match footer.Footer.disk_type with | Disk_type.Differencing_hard_disk -> (* Add the directory of the current file to the search path *) let path = Filename.dirname filename :: path in Header_IO.get_parent_filename header path >>= fun parent_filename -> openchain ~path parent_filename false >>= fun p -> return (Some p) | _ -> return None) >>= fun parent -> Batmap_IO.read handle header >>= fun batmap -> let bitmap_cache = Bitmap_cache.make header in return { filename; rw; handle; header; footer; bat; bitmap_cache; batmap; parent } let openfile filename rw = F.openfile filename rw >>= fun handle -> Footer_IO.read handle 0L >>= fun footer -> Header_IO.read handle (Int64.of_int Footer.sizeof) >>= fun header -> BAT_IO.read handle header >>= fun bat -> Batmap_IO.read handle header >>= fun batmap -> let bitmap_cache = Bitmap_cache.make header in return { filename; rw; handle; header; footer; bat; bitmap_cache; batmap; parent = None } let close t = (* We avoided rewriting the footer for speed, this is where it is repaired. *) ( if t.Vhd.rw then (write_metadata t >>= fun _ -> return ()) else return () ) >>= fun () -> let rec close t = F.close t.Vhd.handle >>= fun () -> match t.Vhd.parent with | None -> return () | Some p -> close p in close t (* Fetch a block bitmap via the cache *) let get_bitmap t block_num = match !(t.Vhd.bitmap_cache.Bitmap_cache.cache) with | Some (block_num', bitmap) when block_num' = block_num -> return bitmap | _ -> Bitmap_IO.read t.Vhd.handle t.Vhd.header t.Vhd.bat block_num >>= fun bitmap -> t.Vhd.bitmap_cache.Bitmap_cache.cache := Some(block_num, bitmap); return bitmap (* Converts a virtual sector offset into a physical sector offset *) let rec get_sector_location t sector = let open Int64 in if sector lsl sector_shift > t.Vhd.footer.Footer.current_size perhaps elements in the vhd chain have different sizes else let maybe_get_from_parent () = match t.Vhd.footer.Footer.disk_type,t.Vhd.parent with | Disk_type.Differencing_hard_disk,Some vhd2 -> get_sector_location vhd2 sector | Disk_type.Differencing_hard_disk,None -> fail (Failure "Sector in parent but no parent found!") | Disk_type.Dynamic_hard_disk,_ -> return None | Disk_type.Fixed_hard_disk,_ -> fail (Failure "Fixed disks are not supported") in let block_num = to_int (sector lsr t.Vhd.header.Header.block_size_sectors_shift) in let sector_in_block = rem sector (1L lsl t.Vhd.header.Header.block_size_sectors_shift) in if BAT.get t.Vhd.bat block_num = BAT.unused then maybe_get_from_parent () else begin get_bitmap t block_num >>= fun bitmap -> let in_this_bitmap = Bitmap.get bitmap sector_in_block in match t.Vhd.footer.Footer.disk_type, in_this_bitmap with | _, true -> let data_sector = (of_int32 (BAT.get t.Vhd.bat block_num)) ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) ++ sector_in_block in return (Some(t, data_sector)) | Disk_type.Dynamic_hard_disk, false -> return None | Disk_type.Differencing_hard_disk, false -> maybe_get_from_parent () | Disk_type.Fixed_hard_disk, _ -> fail (Failure "Fixed disks are not supported") end let read_sector t sector data = let open Int64 in if sector < 0L || (sector lsl sector_shift >= t.Vhd.footer.Footer.current_size) then fail (Invalid_sector(sector, t.Vhd.footer.Footer.current_size lsr sector_shift)) else get_sector_location t sector >>= function | None -> return false | Some (t, offset) -> really_read t.Vhd.handle (offset lsl sector_shift) data >>= fun () -> return true let parallel f xs = let ts = List.map f xs in let rec join = function | [] -> return () | t :: ts -> t >>= fun () -> join ts in join ts let rec write_physical t (offset, bufs) = match bufs with | [] -> return () | b :: bs -> really_write t offset b >>= fun () -> write_physical t (Int64.(add offset (of_int (Cstruct.len b))), bs) let count_sectors bufs = let rec loop acc = function | [] -> acc | b :: bs -> loop (Cstruct.len b / sector_size + acc) bs in loop 0 bufs (* quantise the (offset, buffer) into within-block chunks *) let quantise block_size_in_sectors offset bufs = let open Int64 in (* our starting position in (block, sector) co-ordinates *) let block = to_int (div offset (of_int block_size_in_sectors)) in let sector = to_int (rem offset (of_int block_size_in_sectors)) in let rec loop acc (offset, bufs) (block, sector) = function | [] -> let acc = if bufs = [] then acc else (offset, bufs) :: acc in List.rev acc | b :: bs -> let remaining_this_block = block_size_in_sectors - sector in let available = Cstruct.len b / sector_size in if available = 0 then loop acc (offset, bufs) (block, sector) bs else if available < remaining_this_block then loop acc (offset, b :: bufs) (block, sector + available) bs else if available = remaining_this_block then loop ((offset, List.rev (b :: bufs)) :: acc) (add offset (of_int available), []) (block + 1, 0) bs else let b' = Cstruct.sub b 0 (remaining_this_block * sector_size) in let b'' = Cstruct.shift b (remaining_this_block * sector_size) in loop ((offset, List.rev (b' :: bufs)) :: acc) (add offset (of_int remaining_this_block), []) (block + 1, 0) (b'' :: bs) in List.rev (loop [] (offset, []) (block, sector) bufs) let write t offset bufs = let block_size_in_sectors = 1 lsl t.Vhd.header.Header.block_size_sectors_shift in let _bitmap_size = Header.sizeof_bitmap t.Vhd.header in (* quantise the (offset, buffer) into within-block chunks *) We permute data and bitmap sector writes , but only flush the BAT at the end . In the event of a crash during this operation , arbitrary data sectors will have been written but we will never expose garbage ( as would happen if we flushed the BAT before writing the data blocks . In the event of a crash during this operation, arbitrary data sectors will have been written but we will never expose garbage (as would happen if we flushed the BAT before writing the data blocks. *) let open Int64 in let rec loop (write_bat, acc) = function | [] -> return (write_bat, acc) | (offset, bufs) :: rest -> let block_num = to_int (offset lsr t.Vhd.header.Header.block_size_sectors_shift) in assert (block_num < (BAT.length t.Vhd.bat)); let nsectors = of_int (count_sectors bufs) in ( let size_sectors = t.Vhd.footer.Footer.current_size lsr sector_shift in if offset < 0L then fail (Invalid_sector(offset, size_sectors)) else if (add offset nsectors) > size_sectors then fail (Invalid_sector(add offset nsectors, size_sectors)) else return () ) >>= fun () -> let sector_in_block = rem offset (of_int block_size_in_sectors) in if BAT.get t.Vhd.bat block_num <> BAT.unused then begin let bitmap_sector = of_int32 (BAT.get t.Vhd.bat block_num) in let data_sector = bitmap_sector ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) ++ sector_in_block in let data_writes = [ (data_sector lsl sector_shift), bufs ] in ( get_bitmap t block_num >>= fun bitmap -> match Bitmap.setv bitmap sector_in_block nsectors with | None -> return [] | Some (offset, bufs) -> return [ (bitmap_sector lsl sector_shift) ++ offset, bufs] ) >>= fun bitmap_writes -> loop (write_bat, acc @ bitmap_writes @ data_writes) rest end else begin BAT.set t.Vhd.bat block_num (Vhd.get_free_sector t.Vhd.header t.Vhd.bat); let bitmap_sector = of_int32 (BAT.get t.Vhd.bat block_num) in let block_start = bitmap_sector ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) in let data_sector = block_start ++ sector_in_block in let data_writes = [ (data_sector lsl sector_shift), bufs ] in We will have to write the bitmap anyway , but if we have no parent then we write all 1s since we 're expected to physically zero the block . write all 1s since we're expected to physically zero the block. *) let bitmap_writes = if t.Vhd.parent = None then [ (bitmap_sector lsl sector_shift), [ t.Vhd.bitmap_cache.Bitmap_cache.all_ones ] ] else let bitmap_size = Header.sizeof_bitmap t.Vhd.header in let bitmap = Memory.alloc bitmap_size in Cstruct.blit t.Vhd.bitmap_cache.Bitmap_cache.all_zeroes 0 bitmap 0 bitmap_size; ignore (Bitmap.setv (Bitmap.Partial bitmap) sector_in_block nsectors); [ (bitmap_sector lsl sector_shift), [ bitmap ] ] in let zeroes offset length = let rec zero acc remaining = if remaining = 0L then acc else let this = min remaining (Int64.of_int sectors_in_2mib) in let buf = Cstruct.sub empty_2mib 0 (Int64.to_int this * sector_size) in zero (buf :: acc) (Int64.sub remaining this) in [ offset lsl sector_shift, zero [] length ] in let before = zeroes block_start sector_in_block in let trailing_sectors = sub (of_int block_size_in_sectors) (add sector_in_block nsectors) in let after = zeroes (add (add block_start sector_in_block) nsectors) trailing_sectors in loop (true, (acc @ bitmap_writes @ before @ data_writes @ after)) rest end in loop (false, []) (quantise block_size_in_sectors offset bufs) >>= fun (write_bat, data_writes) -> parallel (write_physical t.Vhd.handle) data_writes >>= fun () -> if write_bat then begin let bat_buffer = Memory.alloc (BAT.sizeof_bytes t.Vhd.header) in BAT_IO.write bat_buffer t.Vhd.handle t.Vhd.header t.Vhd.bat end else return () (* XXX; only write the bits of the bat which changed *) end module Raw_IO = struct open Raw let openfile filename rw = F.openfile filename rw >>= fun handle -> return { filename; handle } let close t = F.close t.handle let create ~filename ~size () = F.create filename >>= fun handle -> F.really_write handle size (Cstruct.create 0) >>= fun () -> return { filename; handle } end include Stream(F) Test whether a block is in any BAT in the path to the root . If so then we will look up all sectors . look up all sectors. *) let rec in_any_bat vhd i = i < vhd.Vhd.header.Header.max_table_entries && match BAT.get vhd.Vhd.bat i <> BAT.unused, vhd.Vhd.parent with | true, _ -> true | false, Some parent -> in_any_bat parent i | false, None -> false let rec coalesce_request acc s = let open Int64 in s >>= fun next -> match next, acc with | End, None -> return End | End, Some x -> return (Cons(x, fun () -> return End)) | Cons(`Sectors s, next), None -> return(Cons(`Sectors s, fun () -> coalesce_request None (next ()))) | Cons(`Sectors _, _next), Some x -> return(Cons(x, fun () -> coalesce_request None s)) | Cons(`Empty n, next), None -> coalesce_request (Some(`Empty n)) (next ()) | Cons(`Empty n, next), Some(`Empty m) -> coalesce_request (Some(`Empty (n ++ m))) (next ()) | Cons(`Empty _n, _next), Some x -> return (Cons(x, fun () -> coalesce_request None s)) | Cons(`Copy(h, ofs, len), next), None -> coalesce_request (Some (`Copy(h, ofs, len))) (next ()) | Cons(`Copy(h, ofs, len), next), Some(`Copy(h', ofs', len')) -> if ofs ++ len = ofs' && h == h' then coalesce_request (Some(`Copy(h, ofs, len ++ len'))) (next ()) else if ofs' ++ len' = ofs && h == h' then coalesce_request (Some(`Copy(h, ofs', len ++ len'))) (next ()) else return (Cons(`Copy(h', ofs', len'), fun () -> coalesce_request None s)) | Cons(`Copy(_h, _ofs, _len), _next), Some x -> return(Cons(x, fun () -> coalesce_request None s)) let twomib_bytes = 2 * 1024 * 1024 let twomib_sectors = twomib_bytes / 512 let rec expand_empty_elements twomib_empty s = let open Int64 in s >>= function | End -> return End | Cons(`Empty n, next) -> let rec copy n = let this = to_int (min n (of_int twomib_sectors)) in let block = Cstruct.sub twomib_empty 0 (this * 512) in let n = n -- (of_int this) in let next () = if n > 0L then copy n else expand_empty_elements twomib_empty (next ()) in return (Cons(`Sectors block, next)) in copy n | Cons(x, next) -> return (Cons(x, fun () -> expand_empty_elements twomib_empty (next ()))) let expand_empty s = let open Int64 in let size = { s.size with empty = 0L; metadata = s.size.metadata ++ s.size.empty } in let twomib_empty = let b = Cstruct.create twomib_bytes in for i = 0 to twomib_bytes - 1 do Cstruct.set_uint8 b i 0 done; b in expand_empty_elements twomib_empty (return s.elements) >>= fun elements -> return { elements; size } let rec expand_copy_elements buffer s = let open Int64 in s >>= function | End -> return End | Cons(`Copy(h, sector_start, sector_len), next) -> let rec copy sector_start sector_len = let this = to_int (min sector_len (of_int twomib_sectors)) in let data = Cstruct.sub buffer 0 (this * 512) in really_read h (sector_start ** 512L) data >>= fun () -> let sector_start = sector_start ++ (of_int this) in let sector_len = sector_len -- (of_int this) in let next () = if sector_len > 0L then copy sector_start sector_len else expand_copy_elements buffer (next ()) in return (Cons(`Sectors data, next)) in copy sector_start sector_len | Cons(x, next) -> return (Cons(x, fun () -> expand_copy_elements buffer (next ()))) let expand_copy s = let open Int64 in let size = { s.size with copy = 0L; metadata = s.size.metadata ++ s.size.copy } in let buffer = Memory.alloc twomib_bytes in expand_copy_elements buffer (return s.elements) >>= fun elements -> return { elements; size } module Vhd_input = struct If we 're streaming a fully consolidated disk ( where from = None ) then we include blocks if they 're in any BAT on the path to the tree root . If from = Some from then we must take the two paths to the tree root : t , from : vhd list and include blocks where x | x \in ( from - t ) " we must revert changes specific to the ' from ' branch " and x | x \in ( t - from ) " we must include changes specific to the ' t ' branch " blocks if they're in any BAT on the path to the tree root. If from = Some from then we must take the two paths to the tree root: t, from : vhd list and include blocks where x | x \in (from - t) "we must revert changes specific to the 'from' branch" and x | x \in (t - from) "we must include changes specific to the 't' branch" *) let include_block from t = match from with | None -> in_any_bat t | Some from -> let module E = struct We ca n't simply compare filenames as strings ( consider " ./././foo " and " foo " ) . We use the combination of the vhd 's builtin uuid ( which should be enough by itself ) and the basename , just in case there exist duplicate uuids in the wild ( because no - one else seems to really care to check ) We use the combination of the vhd's builtin uuid (which should be enough by itself) and the basename, just in case there exist duplicate uuids in the wild (because no-one else seems to really care to check) *) type key = Uuidm.t * string type t = (key * BAT.t) let _to_string ((uuid, filename), _) = Printf.sprintf "%s:%s" (Uuidm.to_string uuid) filename let compare x y = compare (fst x) (fst y) end in let module BATS = Set.Make(E) in let rec make t = let rest = match t.Vhd.parent with | None -> BATS.empty | Some x -> make x in BATS.add ((t.Vhd.footer.Footer.uid, Filename.basename t.Vhd.filename), t.Vhd.bat) rest in let t_branch = make t in let from_branch = make from in let to_include = BATS.(union (diff t_branch from_branch) (diff from_branch t_branch)) in fun i -> BATS.fold (fun (_, bat) acc -> acc || (i < BAT.length bat && BAT.get bat i <> BAT.unused)) to_include false let raw_common ?from ?(raw: 'a) (vhd: fd Vhd.t) = let block_size_sectors_shift = vhd.Vhd.header.Header.block_size_sectors_shift in let max_table_entries = Vhd.used_max_table_entries vhd in let empty_block = `Empty (Int64.shift_left 1L block_size_sectors_shift) in let empty_sector = `Empty 1L in let include_block = include_block from vhd in let rec block i = let next_block () = block (i + 1) in if i = max_table_entries then return End else begin if not(include_block i) then return (Cons(empty_block, next_block)) else begin let absolute_block_start = Int64.(shift_left (of_int i) block_size_sectors_shift) in let rec sector j = let next_sector () = sector (j + 1) in let absolute_sector = Int64.(add absolute_block_start (of_int j)) in if j = 1 lsl block_size_sectors_shift then next_block () else match raw with | None -> begin Vhd_IO.get_sector_location vhd absolute_sector >>= function | None -> return (Cons(empty_sector, next_sector)) | Some (vhd', offset) -> return (Cons(`Copy(vhd'.Vhd.handle, offset, 1L), next_sector)) end | Some raw -> return (Cons(`Copy(raw, absolute_sector, 1L), next_sector)) in sector 0 end end in (* Note we avoid inspecting the sector bitmaps to avoid unnecessary seeking *) let rec count totals i = if i = max_table_entries then totals else begin if not(include_block i) then count { totals with empty = Int64.(add totals.empty (shift_left 1L (block_size_sectors_shift + sector_shift))) } (i + 1) else count { totals with copy = Int64.(add totals.copy (shift_left 1L (block_size_sectors_shift + sector_shift))) } (i + 1) end in coalesce_request None (block 0) >>= fun elements -> let size = count { empty with total = vhd.Vhd.footer.Footer.current_size } 0 in return { elements; size } let raw ?from (vhd: fd Vhd.t) = raw_common ?from vhd let vhd_common ?from ?raw ?(emit_batmap=false)(t: fd Vhd.t) = let block_size_sectors_shift = t.Vhd.header.Header.block_size_sectors_shift in let max_table_entries = Vhd.used_max_table_entries t in The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT Batmap_header | iff batmap Batmap | byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT Batmap_header | iff batmap Batmap | *) let data_offset = 512L in let table_offset = 2048L in let size = t.Vhd.footer.Footer.current_size in let disk_type = match from with | None -> Disk_type.Dynamic_hard_disk | Some _ -> Disk_type.Differencing_hard_disk in let footer = Footer.create ~data_offset ~current_size:size ~disk_type () in ( match from with | None -> return (Header.create ~table_offset ~current_size:size ~block_size_sectors_shift ()) | Some from -> let parent_locators = Parent_locator.from_filename from.Vhd.filename in F.get_modification_time from.Vhd.filename >>= fun parent_time_stamp -> let h = Header.create ~table_offset ~current_size:size ~block_size_sectors_shift ~parent_unique_id:from.Vhd.footer.Footer.uid ~parent_time_stamp ~parent_unicode_name:(UTF16.of_utf8 from.Vhd.filename) ~parent_locators () in return h ) >>= fun header -> let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let sizeof_bat = BAT.sizeof_bytes header in let sizeof_bitmap = Header.sizeof_bitmap header in (* We'll always set all bitmap bits *) let bitmap = Memory.alloc sizeof_bitmap in for i = 0 to sizeof_bitmap - 1 do Cstruct.set_uint8 bitmap i 0xff done; let sizeof_data_sectors = 1 lsl block_size_sectors_shift in let sizeof_data = 1 lsl (block_size_sectors_shift + sector_shift) in let include_block = include_block from t in Calculate where the first data block can go . Note the is already rounded up to the next sector boundary . rounded up to the next sector boundary. *) let next_free_sector_in_bytes = Int64.(table_offset ++ (of_int sizeof_bat)) in let batmap_header = Memory.alloc Batmap_header.sizeof in let batmap = Memory.alloc (Batmap.sizeof header) in for i = 0 to Batmap.sizeof header - 1 do Cstruct.set_uint8 batmap i 0 done; let first_block = if emit_batmap then Int64.(next_free_sector_in_bytes ++ (of_int Batmap_header.sizeof) ++ (of_int (Batmap.sizeof header))) else next_free_sector_in_bytes in let next_byte = ref first_block in for i = 0 to max_table_entries - 1 do if include_block i then begin BAT.set bat i (Int64.(to_int32(!next_byte lsr sector_shift))); Batmap.set batmap i; next_byte := Int64.(!next_byte ++ (of_int sizeof_bitmap) ++ (of_int sizeof_data)) end done; Batmap_header.marshal batmap_header { Batmap_header.offset = Int64.(next_free_sector_in_bytes ++ 512L); size_in_sectors = Batmap.sizeof header lsr sector_shift; major_version = Batmap_header.current_major_version; minor_version = Batmap_header.current_minor_version; checksum = Checksum.of_cstruct batmap; marker = 0; }; let write_sectors buf andthen = return(Cons(`Sectors buf, andthen)) in let rec block i andthen = let rec sector j = let next () = if j = sizeof_data_sectors - 1 then block (i + 1) andthen else sector (j + 1) in let absolute_sector = Int64.(add (shift_left (of_int i) block_size_sectors_shift) (of_int j)) in match raw with | None -> begin Vhd_IO.get_sector_location t absolute_sector >>= function | None -> return (Cons(`Empty 1L, next)) | Some (vhd', offset) -> return (Cons(`Copy(vhd'.Vhd.handle, offset, 1L), next)) end | Some raw -> return (Cons(`Copy(raw, absolute_sector, 1L), next)) in if i >= max_table_entries then andthen () else if include_block i then return(Cons(`Sectors bitmap, fun () -> sector 0)) else block (i + 1) andthen in let batmap andthen = if emit_batmap then write_sectors batmap_header (fun () -> write_sectors batmap andthen) else andthen () in assert(Footer.sizeof = 512); assert(Header.sizeof = 1024); let buf = Memory.alloc (max Footer.sizeof (max Header.sizeof sizeof_bat)) in let (_: Footer.t) = Footer.marshal buf footer in coalesce_request None (return (Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> let (_: Header.t) = Header.marshal buf header in write_sectors (Cstruct.sub buf 0 Header.sizeof) (fun () -> return(Cons(`Empty 1L, fun () -> BAT.marshal buf bat; write_sectors (Cstruct.sub buf 0 sizeof_bat) (fun () -> let (_: Footer.t) = Footer.marshal buf footer in batmap (fun () -> block 0 (fun () -> return(Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> return End)) ) ) ) )) ) ))) >>= fun elements -> (* Note we avoid inspecting the sector bitmaps to avoid unnecessary seeking *) let rec count totals i = if i = max_table_entries then totals else begin if not(include_block i) then count totals (i + 1) else count { totals with copy = Int64.(add totals.copy (shift_left 1L (block_size_sectors_shift + sector_shift))); metadata = Int64.(add totals.metadata (of_int sizeof_bitmap)) } (i + 1) end in let size = { empty with metadata = Int64.of_int ((2 * Footer.sizeof + Header.sizeof + sizeof_bat) / 512); empty = 512L; total = t.Vhd.footer.Footer.current_size } in let size = count size 0 in return { elements; size } let vhd ?from ?emit_batmap (t: fd Vhd.t) = vhd_common ?from ?emit_batmap t end module Hybrid_input = struct let raw ?from (raw: 'a) (vhd: fd Vhd.t) = Vhd_input.raw_common ?from ~raw vhd let vhd ?from (raw: 'a) (vhd: fd Vhd.t) = Vhd_input.vhd_common ?from ~raw vhd end module Raw_input = struct open Raw let vhd t = The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT *) let data_offset = 512L in let table_offset = 2048L in F.get_file_size t.filename >>= fun current_size -> let header = Header.create ~table_offset ~current_size () in let current_size = Int64.(shift_left (of_int header.Header.max_table_entries) (header.Header.block_size_sectors_shift + sector_shift)) in let footer = Footer.create ~data_offset ~current_size ~disk_type:Disk_type.Dynamic_hard_disk () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let sizeof_bat = BAT.sizeof_bytes header in let sizeof_bitmap = Header.sizeof_bitmap header in (* We'll always set all bitmap bits *) let bitmap = Memory.alloc sizeof_bitmap in for i = 0 to sizeof_bitmap - 1 do Cstruct.set_uint8 bitmap i 0xff done; let sizeof_data = 1 lsl (header.Header.block_size_sectors_shift + sector_shift) in let include_block i = let length = Int64.(shift_left 1L (sector_shift + header.Header.block_size_sectors_shift)) in let offset = Int64.(shift_left (of_int i) (sector_shift + header.Header.block_size_sectors_shift)) in (* is the next data byte in the next block? *) F.lseek_data t.Raw.handle offset >>= fun data -> return (Int64.add offset length > data) in Calculate where the first data block will go . Note the is already rounded up to the next sector boundary . rounded up to the next sector boundary. *) let first_block = Int64.(table_offset ++ (of_int sizeof_bat)) in let next_byte = ref first_block in let blocks = header.Header.max_table_entries in let rec loop i = if i = blocks then return () else include_block i >>= function | true -> BAT.set bat i (Int64.(to_int32(!next_byte lsr sector_shift))); next_byte := Int64.(!next_byte ++ (of_int sizeof_bitmap) ++ (of_int sizeof_data)); loop (i+1) | false -> loop (i+1) in loop 0 >>= fun () -> let write_sectors buf _from andthen = return(Cons(`Sectors buf, andthen)) in let rec block i andthen = if i >= blocks then andthen () else include_block i >>= function | true -> let length = Int64.(shift_left 1L header.Header.block_size_sectors_shift) in let sector = Int64.(shift_left (of_int i) header.Header.block_size_sectors_shift) in return (Cons(`Sectors bitmap, fun () -> return (Cons(`Copy(t.Raw.handle, sector, length), fun () -> block (i+1) andthen)))) | false -> block (i + 1) andthen in assert(Footer.sizeof = 512); assert(Header.sizeof = 1024); let buf = Memory.alloc (max Footer.sizeof (max Header.sizeof sizeof_bat)) in let (_: Footer.t) = Footer.marshal buf footer in coalesce_request None (return (Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> let (_: Header.t) = Header.marshal buf header in write_sectors (Cstruct.sub buf 0 Header.sizeof) 0 (fun () -> return(Cons(`Empty 1L, fun () -> BAT.marshal buf bat; write_sectors (Cstruct.sub buf 0 sizeof_bat) 0 (fun () -> let (_: Footer.t) = Footer.marshal buf footer in block 0 (fun () -> return(Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> return End)) ) ) )) ) ))) >>= fun elements -> let metadata = Int64.of_int ((2 * Footer.sizeof + Header.sizeof + sizeof_bat + sizeof_bitmap * blocks)) in let size = { empty with metadata; total = current_size; copy = current_size } in return { elements; size } let raw t = F.get_file_size t.filename >>= fun bytes -> (* round up to the next full sector *) let open Int64 in let bytes = roundup_sector bytes in let size = { total = bytes; metadata = 0L; empty = 0L; copy = bytes; } in let rec copy sector_start sector_len = if sector_len = 0L then return End else let bytes_start = Int64.shift_left sector_start sector_shift in F.lseek_data t.handle bytes_start >>= fun bytes_next_data_start -> let sector_next_data_start = Int64.shift_right bytes_next_data_start sector_shift in let empty_sectors = Int64.sub sector_next_data_start sector_start in if empty_sectors > 0L then return (Cons(`Empty empty_sectors, fun () -> copy sector_next_data_start (Int64.sub sector_len empty_sectors))) else We want to copy at least one sector , so we 're not interested in holes " closer " than that . than that. *) F.lseek_hole t.handle Int64.(shift_left (succ sector_next_data_start) sector_shift) >>= fun bytes_next_hole_start -> let sector_next_hole_start = Int64.shift_right bytes_next_hole_start sector_shift in let sector_data_length = Int64.sub sector_next_hole_start sector_next_data_start in return (Cons(`Copy(t.handle, sector_next_data_start, sector_data_length), fun () -> copy sector_next_hole_start (Int64.sub sector_len sector_data_length))) in copy 0L (bytes lsr sector_shift) >>= fun elements -> return { size; elements } end end
null
https://raw.githubusercontent.com/mirage/ocaml-vhd/8efec5c3930d81e471d04e134fb8b3c640afef3a/vhd_format/f.ml
ocaml
never happens always set TODO: use the optimised mirage version Adjust the checksum [t] by removing the contribution of [x] high bits low bits Check if there's a byte order marker UTF-16 strings end with a \000\000 "conectix" No alignment necessary Interpret as a NULL-terminated string bytes sector cxsparse Round up the size to the next block arbitrary exn Safety check: this code assumes the single parent locator points to data in the same place. No alignment necessary TODO: we need a proper free 'list' if we are going to allow blocks to be deallocated eg through TRIM already set, no on-disk update required already set, no on-disk update required not set, we must update the sector on disk bitmap sector offsets must be contiguous by construction effective only for streaming Nb this only copes with dynamic or differencing disks TODO: need a quicker block allocator * Dynamically-typed field-level access Convert Error values into failed threads Operator to avoid bracket overload header is at the Footer data_offset Create a mapping of physical sector -> virtual sector Compute the length of a 'span' of sectors in the bitmap, so we can coalesce our reads into large chunks Convert Error values into failed threads Search a path for a filename Only write those that actually have a platform_code Read the parent_locator data Write the parent_locator data This causes the file size to be increased so we can successfully read empty blocks in places like the parent locators Assume the data is there, or will be written later remove common preceeding path elements We use the same basic file layout as in create_dynamic Re-open the parent file to avoid sharing the underlying file descriptor and having to perform reference counting Add the directory of the current file to the search path We avoided rewriting the footer for speed, this is where it is repaired. Fetch a block bitmap via the cache Converts a virtual sector offset into a physical sector offset quantise the (offset, buffer) into within-block chunks our starting position in (block, sector) co-ordinates quantise the (offset, buffer) into within-block chunks XXX; only write the bits of the bat which changed Note we avoid inspecting the sector bitmaps to avoid unnecessary seeking We'll always set all bitmap bits Note we avoid inspecting the sector bitmaps to avoid unnecessary seeking We'll always set all bitmap bits is the next data byte in the next block? round up to the next full sector
* Copyright ( C ) 2011 - 2013 Citrix Inc * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2011-2013 Citrix Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) VHD manipulation let sector_size = 512 let sector_shift = 9 exception Cstruct_differ let cstruct_equal a b = let check_contents a b = try for i = 0 to Cstruct.len a - 1 do let a' = Cstruct.get_char a i in let b' = Cstruct.get_char b i in if a' <> b' then raise Cstruct_differ done; true with _ -> false in (Cstruct.len a = (Cstruct.len b)) && (check_contents a b) exception Invalid_sector of int64 * int64 module Memory = struct let alloc bytes = if bytes = 0 then Cstruct.create 0 else let n = (bytes + 4095) / 4096 in let pages = Io_page.(to_cstruct (get n)) in Cstruct.sub pages 0 bytes end let constant size v = let buf = Memory.alloc size in for i = 0 to size - 1 do Cstruct.set_uint8 buf i v done; buf let sectors_in_2mib = 2 * 1024 * 2 let empty_2mib = constant (sectors_in_2mib * 512) 0 let sector_all_zeroes = constant 512 0 let sector_all_ones = constant 512 0xff module Int64 = struct include Int64 let ( ++ ) = add let ( -- ) = sub let ( // ) = div let ( ** ) = mul let ( lsl ) = shift_left let ( lsr ) = shift_right_logical let roundup_sector x = ((x ++ (1L lsl sector_shift -- 1L)) lsr sector_shift) lsl sector_shift end let roundup_sector x = ((x + (1 lsl sector_shift - 1)) lsr sector_shift) lsl sector_shift let kib = 1024L let mib = Int64.(1024L ** kib) let gib = Int64.(1024L ** mib) let max_disk_size = Int64.(2040L ** gib) let _kib_shift = 10 let _mib_shift = 20 let _gib_shift = 30 let blank_uuid = match Uuidm.of_bytes (String.make 16 '\000') with | Some x -> x module Feature = struct type t = | Temporary let of_int32 x = if Int32.logand x 1l <> 0l then [ Temporary ] else [] let to_int32 ts = let one = function | Temporary -> 1 in Int32.of_int (List.fold_left (lor) reserved (List.map one ts)) let to_string = function | Temporary -> "Temporary" end module Disk_type = struct type t = | Fixed_hard_disk | Dynamic_hard_disk | Differencing_hard_disk exception Unknown of int32 let of_int32 = let open Rresult in function | 2l -> R.ok Fixed_hard_disk | 3l -> R.ok Dynamic_hard_disk | 4l -> R.ok Differencing_hard_disk | x -> R.error (Unknown x) let to_int32 = function | Fixed_hard_disk -> 2l | Dynamic_hard_disk -> 3l | Differencing_hard_disk -> 4l let to_string = function | Fixed_hard_disk -> "Fixed_hard_disk" | Dynamic_hard_disk -> "Dynamic_hard_disk" | Differencing_hard_disk -> "Differencing_hard_disk" end module Host_OS = struct type t = | Windows | Macintosh | Other of int32 let of_int32 = function | 0x5769326bl -> Windows | 0x4d616320l -> Macintosh | x -> Other x let to_int32 = function | Windows -> 0x5769326bl | Macintosh -> 0x4d616320l | Other x -> x let to_string = function | Windows -> "Windows" | Macintosh -> "Macintosh" | Other x -> Printf.sprintf "Other %lx" x end module Geometry = struct type t = { cylinders : int; heads : int; sectors : int; } from the Appendix ' CHS calculation ' let of_sectors sectors = let open Int64 in let max_secs = 65535L ** 255L ** 16L in let secs = min max_secs sectors in let secs_per_track = ref 0L in let heads = ref 0L in let cyls_times_heads = ref 0L in if secs > 65535L ** 63L ** 16L then begin secs_per_track := 255L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end else begin secs_per_track := 17L; cyls_times_heads := secs // !secs_per_track; heads := max ((!cyls_times_heads ++ 1023L) // 1024L) 4L; if (!cyls_times_heads >= (!heads ** 1024L) || !heads > 16L) then begin secs_per_track := 31L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end; if (!cyls_times_heads >= (!heads ** 1024L)) then begin secs_per_track := 63L; heads := 16L; cyls_times_heads := secs // !secs_per_track; end end; { cylinders = to_int (!cyls_times_heads // !heads); heads = to_int !heads; sectors = to_int !secs_per_track } let to_string t = Printf.sprintf "{ cylinders = %d; heads = %d; sectors = %d }" t.cylinders t.heads t.sectors end module Checksum = struct type t = int32 let of_cstruct m = let rec inner n cur = if n=Cstruct.len m then cur else inner (n+1) (Int32.add cur (Int32.of_int (Cstruct.get_uint8 m n))) in Int32.lognot (inner 0 0l) let sub_int32 t x = let open Int32 in let t' = lognot t in let a = logand (shift_right_logical x 0) (of_int 0xff) in let b = logand (shift_right_logical x 8) (of_int 0xff) in let c = logand (shift_right_logical x 16) (of_int 0xff) in let d = logand (shift_right_logical x 24) (of_int 0xff) in Int32.lognot (sub (sub (sub (sub t' a) b) c) d) end module UTF16 = struct type t = int array let to_utf8_exn s = let utf8_chars_of_int i = if i < 0x80 then [char_of_int i] else if i < 0x800 then begin let z = i land 0x3f and y = (i lsr 6) land 0x1f in [char_of_int (0xc0 + y); char_of_int (0x80+z)] end else if i < 0x10000 then begin let z = i land 0x3f and y = (i lsr 6) land 0x3f and x = (i lsr 12) land 0x0f in [char_of_int (0xe0 + x); char_of_int (0x80+y); char_of_int (0x80+z)] end else if i < 0x110000 then begin let z = i land 0x3f and y = (i lsr 6) land 0x3f and x = (i lsr 12) land 0x3f and w = (i lsr 18) land 0x07 in [char_of_int (0xf0 + w); char_of_int (0x80+x); char_of_int (0x80+y); char_of_int (0x80+z)] end else failwith "Bad unicode character!" in String.concat "" (List.map (fun c -> Printf.sprintf "%c" c) (List.flatten (List.map utf8_chars_of_int (Array.to_list s)))) let to_utf8 x = try Rresult.R.ok (to_utf8_exn x) with e -> Rresult.R.error e let to_string x = Printf.sprintf "[| %s |]" (String.concat "; " (List.map string_of_int (Array.to_list x))) let of_ascii string = Array.init (String.length string) (fun c -> int_of_char string.[c]) FIXME ( obviously ) let marshal (buf: Cstruct.t) t = let rec inner ofs n = if n = Array.length t then Cstruct.sub buf 0 ofs else begin let char = t.(n) in if char < 0x10000 then begin Cstruct.BE.set_uint16 buf ofs char; inner (ofs + 2) (n + 1) end else begin let char = char - 0x10000 in Cstruct.BE.set_uint16 buf (ofs + 0) (0xd800 + c1); Cstruct.BE.set_uint16 buf (ofs + 2) (0xdc00 + c2); inner (ofs + 4) (n + 1) end end in inner 0 0 let unmarshal (buf: Cstruct.t) len = let _bigendian, pos, max = match Cstruct.BE.get_uint16 buf 0 with | 0xfeff -> true, 2, (len / 2 - 1) | 0xfffe -> false, 2, (len / 2 - 1) | _ -> true, 0, (len / 2) in let rec strlen acc i = if i >= max then acc else if Cstruct.BE.get_uint16 buf i = 0 then acc else strlen (acc + 1) (i + 2) in let max = strlen 0 0 in let string = Array.make max 0 in let rec inner ofs n = if n >= max then string else begin let c = Cstruct.BE.get_uint16 buf ofs in let code, ofs', n' = if c >= 0xd800 && c <= 0xdbff then begin let c2 = Cstruct.BE.get_uint16 buf (ofs + 2) in if c2 < 0xdc00 || c2 > 0xdfff then (failwith (Printf.sprintf "Bad unicode char: %04x %04x" c c2)); let top10bits = c-0xd800 in let bottom10bits = c2-0xdc00 in let char = 0x10000 + (bottom10bits lor (top10bits lsl 10)) in char, ofs + 4, n + 1 end else c, ofs + 2, n + 1 in string.(n) <- code; inner ofs' n' end in try Rresult.R.ok (inner pos 0) with e -> Rresult.R.error e end module Footer = struct type t = { features : Feature.t list; data_offset : int64; time_stamp : int32; creator_application : string; creator_version : int32; creator_host_os : Host_OS.t; original_size : int64; current_size : int64; geometry : Geometry.t; disk_type : Disk_type.t; checksum : int32; uid : Uuidm.t; saved_state : bool } let default_creator_application = "caml" let default_creator_version = 0x00000001l let create ?(features=[]) ~data_offset ?(time_stamp=0l) ?(creator_application = default_creator_application) ?(creator_version = default_creator_version) ?(creator_host_os = Host_OS.Other 0l) ~current_size ?original_size ~disk_type ?(uid = Uuidm.v `V4) ?(saved_state = false) () = let original_size = match original_size with | None -> current_size | Some x -> x in let geometry = Geometry.of_sectors Int64.(current_size lsr sector_shift) in let checksum = 0l in { features; data_offset; time_stamp; creator_application; creator_version; creator_host_os; original_size; current_size; geometry; disk_type; checksum; uid; saved_state } let to_string t = Printf.sprintf "{ features = [ %s ]; data_offset = %Lx; time_stamp = %lx; creator_application = %s; creator_version = %lx; creator_host_os = %s; original_size = %Ld; current_size = %Ld; geometry = %s; disk_type = %s; checksum = %ld; uid = %s; saved_state = %b }" (String.concat "; " (List.map Feature.to_string t.features)) t.data_offset t.time_stamp t.creator_application t.creator_version (Host_OS.to_string t.creator_host_os) t.original_size t.current_size (Geometry.to_string t.geometry) (Disk_type.to_string t.disk_type) t.checksum (Uuidm.to_string t.uid) t.saved_state let magic = "conectix" let expected_version = 0x00010000l let dump t = Printf.printf "VHD FOOTER\n"; Printf.printf "-=-=-=-=-=\n\n"; Printf.printf "cookie : %s\n" magic; Printf.printf "features : %s\n" (String.concat "," (List.map Feature.to_string t.features)); Printf.printf "format_version : 0x%lx\n" expected_version; Printf.printf "data_offset : 0x%Lx\n" t.data_offset; Printf.printf "time_stamp : %lu\n" t.time_stamp; Printf.printf "creator_application : %s\n" t.creator_application; Printf.printf "creator_version : 0x%lx\n" t.creator_version; Printf.printf "creator_host_os : %s\n" (Host_OS.to_string t.creator_host_os); Printf.printf "original_size : 0x%Lx\n" t.original_size; Printf.printf "current_size : 0x%Lx\n" t.current_size; Printf.printf "geometry : %s\n" (Geometry.to_string t.geometry); Printf.printf "disk_type : %s\n" (Disk_type.to_string t.disk_type); Printf.printf "checksum : %lu\n" t.checksum; Printf.printf "uid : %s\n" (Uuidm.to_string t.uid); Printf.printf "saved_state : %b\n\n" t.saved_state [%%cstruct type footer = { magic: uint8_t [@len 8]; features: uint32_t; version: uint32_t; data_offset: uint64_t; time_stamp: uint32_t; creator_application: uint8_t [@len 4]; creator_version: uint32_t; creator_host_os: uint32_t; original_size: uint64_t; current_size: uint64_t; cylinders: uint16_t; heads: uint8_t; sectors: uint8_t; disk_type: uint32_t; checksum: uint32_t; uid: uint8_t [@len 16]; saved_state: uint8_t; 427 zeroed } [@@big_endian]] let sizeof = 512 let marshal (buf: Cstruct.t) t = set_footer_magic magic 0 buf; set_footer_features buf (Feature.to_int32 t.features); set_footer_version buf expected_version; set_footer_data_offset buf t.data_offset; set_footer_time_stamp buf t.time_stamp; set_footer_creator_application t.creator_application 0 buf; set_footer_creator_version buf t.creator_version; set_footer_creator_host_os buf (Host_OS.to_int32 t.creator_host_os); set_footer_original_size buf t.original_size; set_footer_current_size buf t.current_size; set_footer_cylinders buf t.geometry.Geometry.cylinders; set_footer_heads buf t.geometry.Geometry.heads; set_footer_sectors buf t.geometry.Geometry.sectors; set_footer_disk_type buf (Disk_type.to_int32 t.disk_type); set_footer_checksum buf 0l; set_footer_uid (Uuidm.to_bytes t.uid) 0 buf; set_footer_saved_state buf (if t.saved_state then 1 else 0); let remaining = Cstruct.shift buf sizeof_footer in for i = 0 to 426 do Cstruct.set_uint8 remaining i 0 done; let checksum = Checksum.of_cstruct (Cstruct.sub buf 0 sizeof) in set_footer_checksum buf checksum; { t with checksum } let unmarshal (buf: Cstruct.t) = let open Rresult in let magic' = copy_footer_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Unsupported footer cookie: expected %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let features = Feature.of_int32 (get_footer_features buf) in let format_version = get_footer_version buf in ( if format_version <> expected_version then R.error (Failure (Printf.sprintf "Unsupported footer version: expected %lx, got %lx" expected_version format_version)) else R.ok () ) >>= fun () -> let data_offset = get_footer_data_offset buf in let time_stamp = get_footer_time_stamp buf in let creator_application = copy_footer_creator_application buf in let creator_version = get_footer_creator_version buf in let creator_host_os = Host_OS.of_int32 (get_footer_creator_host_os buf) in let original_size = get_footer_original_size buf in let current_size = get_footer_current_size buf in let cylinders = get_footer_cylinders buf in let heads = get_footer_heads buf in let sectors = get_footer_sectors buf in let geometry = { Geometry.cylinders; heads; sectors } in Disk_type.of_int32 (get_footer_disk_type buf) >>= fun disk_type -> let checksum = get_footer_checksum buf in let bytes = copy_footer_uid buf in ( match Uuidm.of_bytes bytes with | None -> R.error (Failure (Printf.sprintf "Failed to decode UUID: %s" (String.escaped bytes))) | Some uid -> R.ok uid ) >>= fun uid -> let saved_state = get_footer_saved_state buf = 1 in let expected_checksum = Checksum.(sub_int32 (of_cstruct (Cstruct.sub buf 0 sizeof)) checksum) in ( if checksum <> expected_checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" expected_checksum checksum)) else R.ok () ) >>= fun () -> R.ok { features; data_offset; time_stamp; creator_version; creator_application; creator_host_os; original_size; current_size; geometry; disk_type; checksum; uid; saved_state } let compute_checksum t = let buf = Cstruct.of_bigarray (Bigarray.(Array1.create char c_layout sizeof)) in let t = marshal buf t in t.checksum end module Platform_code = struct type t = | None | Wi2r | Wi2k | W2ru | W2ku | Mac | MacX let wi2r = 0x57693272l let wi2k = 0x5769326Bl let w2ru = 0x57327275l let w2ku = 0x57326b75l let mac = 0x4d616320l let macx = 0x4d616358l let of_int32 = let open Rresult in function | 0l -> R.ok None | x when x = wi2r -> R.ok Wi2r | x when x = wi2k -> R.ok Wi2k | x when x = w2ru -> R.ok W2ru | x when x = w2ku -> R.ok W2ku | x when x = mac -> R.ok Mac | x when x = macx -> R.ok MacX | x -> R.error (Failure (Printf.sprintf "unknown platform_code: %lx" x)) let to_int32 = function | None -> 0l | Wi2r -> wi2r | Wi2k -> wi2k | W2ru -> w2ru | W2ku -> w2ku | Mac -> mac | MacX -> macx let to_string = function | None -> "None" | Wi2r -> "Wi2r [deprecated]" | Wi2k -> "Wi2k [deprecated]" | W2ru -> "W2ru" | W2ku -> "W2ku" | Mac -> "Mac " | MacX -> "MacX" end module Parent_locator = struct type t = { platform_code : Platform_code.t; WARNING WARNING - the following field is measured in * bytes * because Viridian VHDs do this . This is a deviation from the spec . When reading in this field , we multiply by 512 if the value is less than 511 do this. This is a deviation from the spec. When reading in this field, we multiply by 512 if the value is less than 511 *) platform_data_space : int32; Original unaltered value platform_data_length : int32; platform_data_offset : int64; platform_data : Cstruct.t; } let equal a b = true && (a.platform_code = b.platform_code) && (a.platform_data_space = b.platform_data_space) && (a.platform_data_space_original = b.platform_data_space_original) && (a.platform_data_length = b.platform_data_length) && (a.platform_data_offset = b.platform_data_offset) && (cstruct_equal a.platform_data b.platform_data) let null = { platform_code=Platform_code.None; platform_data_space=0l; platform_data_space_original=0l; platform_data_length=0l; platform_data_offset=0L; platform_data=Cstruct.create 0; } let to_string t = Printf.sprintf "(%s %lx %lx, %ld, 0x%Lx, %s)" (Platform_code.to_string t.platform_code) t.platform_data_space t.platform_data_space_original t.platform_data_length t.platform_data_offset (Cstruct.to_string t.platform_data) let to_filename t = match t.platform_code with | Platform_code.MacX -> let rec find_string from = if Cstruct.len t.platform_data <= from then t.platform_data else if Cstruct.get_uint8 t.platform_data from = 0 then Cstruct.sub t.platform_data 0 from else find_string (from + 1) in let path = Cstruct.to_string (find_string 0) in let expected_prefix = "file://" in let expected_prefix' = String.length expected_prefix in let startswith prefix x = let prefix' = String.length prefix and x' = String.length x in prefix' <= x' && (String.sub x 0 prefix' = prefix) in if startswith expected_prefix path then Some (String.sub path expected_prefix' (String.length path - expected_prefix')) else None | _ -> None [%%cstruct type header = { platform_code: uint32_t; platform_data_space: uint32_t; platform_data_length: uint32_t; reserved: uint32_t; platform_data_offset: uint64_t; } [@@big_endian]] let sizeof = sizeof_header let marshal (buf: Cstruct.t) t = set_header_platform_code buf (Platform_code.to_int32 t.platform_code); set_header_platform_data_space buf (Int32.shift_right_logical t.platform_data_space sector_shift); set_header_platform_data_length buf t.platform_data_length; set_header_reserved buf 0l; set_header_platform_data_offset buf t.platform_data_offset let unmarshal (buf: Cstruct.t) = let open Rresult.R.Infix in Platform_code.of_int32 (get_header_platform_code buf) >>= fun platform_code -> let platform_data_space_original = get_header_platform_data_space buf in The spec says this field should be stored in sectors . However some viridian vhds store the value in bytes . We assume that any value we read < 512l is actually in sectors ( 511l sectors is adequate space for a filename ) and any value > = 511l is in bytes . We store the unaltered on - disk value in [ platform_data_space_original ] and the decoded value in * bytes * in [ platform_data_space ] . store the value in bytes. We assume that any value we read < 512l is actually in sectors (511l sectors is adequate space for a filename) and any value >= 511l is in bytes. We store the unaltered on-disk value in [platform_data_space_original] and the decoded value in *bytes* in [platform_data_space]. *) let platform_data_space = if platform_data_space_original < 512l then Int32.shift_left platform_data_space_original sector_shift else platform_data_space_original in let platform_data_length = get_header_platform_data_length buf in let platform_data_offset = get_header_platform_data_offset buf in Rresult.R.return { platform_code; platform_data_space_original; platform_data_space; platform_data_length; platform_data_offset; platform_data = Cstruct.create 0 } let from_filename filename = Convenience function when creating simple vhds which have only one parent locator in the standard place ( offset 1536 bytes ) one parent locator in the standard place (offset 1536 bytes) *) let uri = "file://" ^ filename in let platform_data = Cstruct.create (String.length uri) in Cstruct.blit_from_string uri 0 platform_data 0 (String.length uri); let locator0 = { platform_code = Platform_code.MacX; platform_data_length = Int32.of_int (String.length uri); platform_data_offset = 1536L; platform_data; } in [| locator0; null; null; null; null; null; null; null; |] end module Header = struct type t = { 0xFFFFFFFF table_offset : int64; 0x00010000l max_table_entries : int; block_size_sectors_shift : int; checksum : int32; parent_unique_id : Uuidm.t; parent_time_stamp : int32; parent_unicode_name : int array; parent_locators : Parent_locator.t array; } 1 lsl 12 = 4096 sectors = 2 MiB let create ~table_offset ~current_size ?(block_size_sectors_shift = default_block_size_sectors_shift) ?(checksum = 0l) ?(parent_unique_id = blank_uuid) ?(parent_time_stamp = 0l) ?(parent_unicode_name = [| |]) ?(parent_locators = Array.make 8 Parent_locator.null) () = let open Int64 in let shift = block_size_sectors_shift + sector_shift in let current_size = ((current_size ++ (1L lsl shift -- 1L)) lsr shift) lsl shift in let max_table_entries = to_int (current_size lsr shift) in { table_offset; max_table_entries; block_size_sectors_shift; checksum; parent_unique_id; parent_time_stamp; parent_unicode_name; parent_locators } let to_string t = Printf.sprintf "{ table_offset = %Ld; max_table_entries = %d; block_size_sectors_shift = %d; checksum = %ld; parent_unique_id = %s; parent_time_stamp = %ld parent_unicode_name = %s; parent_locators = [| %s |]" t.table_offset t.max_table_entries t.block_size_sectors_shift t.checksum (Uuidm.to_string t.parent_unique_id) t.parent_time_stamp (UTF16.to_string t.parent_unicode_name) (String.concat "; " (List.map Parent_locator.to_string (Array.to_list t.parent_locators))) let equal a b = true && (a.table_offset = b.table_offset) && (a.max_table_entries = b.max_table_entries) && (a.block_size_sectors_shift = b.block_size_sectors_shift) && (a.checksum = b.checksum) && (a.parent_unique_id = b.parent_unique_id) && (a.parent_time_stamp = b.parent_time_stamp) && (a.parent_unicode_name = b.parent_unicode_name) && (Array.length a.parent_locators = (Array.length b.parent_locators)) && (try for i = 0 to Array.length a.parent_locators - 1 do if not(Parent_locator.equal a.parent_locators.(i) b.parent_locators.(i)) done; true with _ -> false) let set_parent t filename = let parent_locators = Parent_locator.from_filename filename in let parent_unicode_name = UTF16.of_utf8 filename in let not_implemented x = failwith (Printf.sprintf "unexpected vhd parent locators: %s" x) in for i = 1 to Array.length parent_locators - 1 do if not(Parent_locator.equal t.parent_locators.(i) parent_locators.(i)) then not_implemented (string_of_int i) done; if parent_locators.(0).Parent_locator.platform_data_space <> t.parent_locators.(0).Parent_locator.platform_data_space then not_implemented "platform_data_space"; if parent_locators.(0).Parent_locator.platform_data_offset <> t.parent_locators.(0).Parent_locator.platform_data_offset then not_implemented "platform_data_offset"; { t with parent_locators; parent_unicode_name } 1 bit per each 512 byte sector within the block let sizeof_bitmap t = 1 lsl (t.block_size_sectors_shift - 3) let magic = "cxsparse" XXX : the spec says 8 bytes containing 0xFFFFFFFF let expected_version = 0x00010000l let default_block_size = 1 lsl (default_block_size_sectors_shift + sector_shift) let dump t = Printf.printf "VHD HEADER\n"; Printf.printf "-=-=-=-=-=\n"; Printf.printf "cookie : %s\n" magic; Printf.printf "data_offset : %Lx\n" expected_data_offset; Printf.printf "table_offset : %Lu\n" t.table_offset; Printf.printf "header_version : 0x%lx\n" expected_version; Printf.printf "max_table_entries : 0x%x\n" t.max_table_entries; Printf.printf "block_size : 0x%x\n" ((1 lsl t.block_size_sectors_shift) * sector_size); Printf.printf "checksum : %lu\n" t.checksum; Printf.printf "parent_unique_id : %s\n" (Uuidm.to_string t.parent_unique_id); Printf.printf "parent_time_stamp : %lu\n" t.parent_time_stamp; let s = match UTF16.to_utf8 t.parent_unicode_name with | Ok s -> s | Error _e -> Printf.sprintf "<Unable to decode UTF-16: %s>" (String.concat " " (List.map (fun x -> Printf.sprintf "%02x" x) (Array.to_list t.parent_unicode_name))) in Printf.printf "parent_unicode_name : '%s' (%d bytes)\n" s (Array.length t.parent_unicode_name); Printf.printf "parent_locators : %s\n" (String.concat "\n " (List.map Parent_locator.to_string (Array.to_list t.parent_locators))) [%%cstruct type header = { magic: uint8_t [@len 8]; data_offset: uint64_t; table_offset: uint64_t; header_version: uint32_t; max_table_entries: uint32_t; block_size: uint32_t; checksum: uint32_t; parent_unique_id: uint8_t [@len 16]; parent_time_stamp: uint32_t; reserved: uint32_t; parent_unicode_name: uint8_t [@len 512]; 8 parent locators 256 reserved } [@@big_endian]] let sizeof = sizeof_header + (8 * Parent_locator.sizeof) + 256 let unicode_offset = 8 + 8 + 8 + 4 + 4 + 4 + 4 + 16 + 4 + 4 let marshal (buf: Cstruct.t) t = set_header_magic magic 0 buf; set_header_data_offset buf expected_data_offset; set_header_table_offset buf t.table_offset; set_header_header_version buf expected_version; set_header_max_table_entries buf (Int32.of_int t.max_table_entries); set_header_block_size buf (Int32.of_int (1 lsl (t.block_size_sectors_shift + sector_shift))); set_header_checksum buf 0l; set_header_parent_unique_id (Uuidm.to_bytes t.parent_unique_id) 0 buf; set_header_parent_time_stamp buf t.parent_time_stamp; set_header_reserved buf 0l; for i = 0 to 511 do Cstruct.set_uint8 buf (unicode_offset + i) 0 done; let (_: Cstruct.t) = UTF16.marshal (Cstruct.shift buf unicode_offset) t.parent_unicode_name in let parent_locators = Cstruct.shift buf (unicode_offset + 512) in for i = 0 to 7 do let buf = Cstruct.shift parent_locators (Parent_locator.sizeof * i) in let pl = if Array.length t.parent_locators <= i then Parent_locator.null else t.parent_locators.(i) in Parent_locator.marshal buf pl done; let reserved = Cstruct.shift parent_locators (8 * Parent_locator.sizeof) in for i = 0 to 255 do Cstruct.set_uint8 reserved i 0 done; let checksum = Checksum.of_cstruct (Cstruct.sub buf 0 sizeof) in set_header_checksum buf checksum; { t with checksum } let unmarshal (buf: Cstruct.t) = let open Rresult in let open Rresult.R.Infix in let magic' = copy_header_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Expected cookie %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let data_offset = get_header_data_offset buf in ( if data_offset <> expected_data_offset then R.error (Failure (Printf.sprintf "Expected header data_offset %Lx, got %Lx" expected_data_offset data_offset)) else R.ok () ) >>= fun () -> let table_offset = get_header_table_offset buf in let header_version = get_header_header_version buf in ( if header_version <> expected_version then R.error (Failure (Printf.sprintf "Expected header_version %lx, got %lx" expected_version header_version)) else R.ok () ) >>= fun () -> let max_table_entries = get_header_max_table_entries buf in ( if Int64.of_int32 max_table_entries > Int64.of_int Sys.max_array_length then R.error (Failure (Printf.sprintf "expected max_table_entries < %d, got %ld" Sys.max_array_length max_table_entries)) else R.ok (Int32.to_int max_table_entries) ) >>= fun max_table_entries -> let block_size = get_header_block_size buf in let rec to_shift acc = function | 0 -> R.error (Failure "block size is zero") | 1 -> R.ok acc | n when n mod 2 = 1 -> R.error (Failure (Printf.sprintf "block_size is not a power of 2: %lx" block_size)) | n -> to_shift (acc + 1) (n / 2) in to_shift 0 (Int32.to_int block_size) >>= fun block_size_shift -> let block_size_sectors_shift = block_size_shift - sector_shift in let checksum = get_header_checksum buf in let bytes = copy_header_parent_unique_id buf in ( match (Uuidm.of_bytes bytes) with | None -> R.error (Failure (Printf.sprintf "Failed to decode UUID: %s" (String.escaped bytes))) | Some x -> R.ok x ) >>= fun parent_unique_id -> let parent_time_stamp = get_header_parent_time_stamp buf in UTF16.unmarshal (Cstruct.sub buf unicode_offset 512) 512 >>= fun parent_unicode_name -> let parent_locators_buf = Cstruct.shift buf (unicode_offset + 512) in let parent_locators = Array.make 8 Parent_locator.null in let rec loop = function | 8 -> R.ok () | i -> let buf = Cstruct.shift parent_locators_buf (Parent_locator.sizeof * i) in Parent_locator.unmarshal buf >>= fun p -> parent_locators.(i) <- p; loop (i + 1) in loop 0 >>= fun () -> let expected_checksum = Checksum.(sub_int32 (of_cstruct (Cstruct.sub buf 0 sizeof)) checksum) in ( if checksum <> expected_checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" expected_checksum checksum)) else R.ok () ) >>= fun () -> R.ok { table_offset; max_table_entries; block_size_sectors_shift; checksum; parent_unique_id; parent_time_stamp; parent_unicode_name; parent_locators } let compute_checksum t = let buf = Cstruct.of_bigarray (Bigarray.(Array1.create char c_layout sizeof)) in let t = marshal buf t in t.checksum end module BAT = struct type t = { max_table_entries: int; data: Cstruct.t; mutable highest_value: int32; } let unused = 0xffffffffl let unused' = 0xffffffffL let get t i = Cstruct.BE.get_uint32 t.data (i * 4) let set t i j = Cstruct.BE.set_uint32 t.data (i * 4) j; if j <> unused && j > t.highest_value then t.highest_value <- j let length t = t.max_table_entries let int64_from_uint32 u32 = let (&&&) = Int64.logand in Int64.(of_int32 u32 &&& 0x0000_0000_ffff_ffffL) let fold f t initial = let rec loop acc i = if i = t.max_table_entries then acc else let v = get t i |> int64_from_uint32 in if v = unused' then loop acc (i + 1) else loop (f i v acc) (i + 1) in loop initial 0 let equal t1 t2 = true && t1.highest_value = t2.highest_value && t1.max_table_entries = t2.max_table_entries && (try for i = 0 to length t1 - 1 do if get t1 i <> get t2 i then raise Not_found done; true with Not_found -> false) We always round up the size of the BAT to the next sector let sizeof_bytes (header: Header.t) = let size_needed = header.Header.max_table_entries * 4 in The BAT is always extended to a sector boundary roundup_sector size_needed let of_buffer (header: Header.t) (data: Cstruct.t) = for i = 0 to (Cstruct.len data) / 4 - 1 do Cstruct.BE.set_uint32 data (i * 4) unused done; { max_table_entries = header.Header.max_table_entries; data; highest_value = -1l; } let to_string (t: t) = let used = ref [] in for i = 0 to length t - 1 do if get t i <> unused then used := (i, get t i) :: !used done; Printf.sprintf "(%d rounded to %d)[ %s ] with highest_value = %ld" (length t) (Cstruct.len t.data / 4) (String.concat "; " (List.map (fun (i, x) -> Printf.sprintf "(%d, %lx)" i x) (List.rev !used))) t.highest_value let unmarshal (buf: Cstruct.t) (header: Header.t) = let t = { data = buf; max_table_entries = header.Header.max_table_entries; highest_value = -1l; } in for i = 0 to length t - 1 do if get t i > t.highest_value then t.highest_value <- get t i done; t let marshal (buf: Cstruct.t) (t: t) = Cstruct.blit t.data 0 buf 0 (Cstruct.len t.data) let dump t = Printf.printf "BAT\n"; Printf.printf "-=-\n"; for i = 0 to t.max_table_entries - 1 do Printf.printf "%d\t:0x%lx\n" i (get t i) done end module Batmap_header = struct [%%cstruct type header = { magic: uint8_t [@len 8]; offset: uint64_t; size_in_sectors: uint32_t; major_version: uint16_t; minor_version: uint16_t; checksum: uint32_t; marker: uint8_t; } [@@big_endian]] let magic = "tdbatmap" let current_major_version = 1 let current_minor_version = 2 let sizeof = roundup_sector sizeof_header type t = { offset: int64; size_in_sectors: int; major_version: int; minor_version: int; checksum: int32; marker: int } let unmarshal (buf: Cstruct.t) = let open Rresult in let open Rresult.R.Infix in let magic' = copy_header_magic buf in ( if magic' <> magic then R.error (Failure (Printf.sprintf "Expected cookie %s, got %s" magic magic')) else R.ok () ) >>= fun () -> let offset = get_header_offset buf in let size_in_sectors = Int32.to_int (get_header_size_in_sectors buf) in let major_version = get_header_major_version buf in let minor_version = get_header_minor_version buf in ( if major_version <> current_major_version || minor_version <> current_minor_version then R.error (Failure (Printf.sprintf "Unexpected BATmap version: %d.%d" major_version minor_version)) else R.ok () ) >>= fun () -> let checksum = get_header_checksum buf in let marker = get_header_marker buf in R.ok { offset; size_in_sectors; major_version; minor_version; checksum; marker } let marshal (buf: Cstruct.t) (t: t) = for i = 0 to Cstruct.len buf - 1 do Cstruct.set_uint8 buf i 0 done; set_header_offset buf t.offset; set_header_size_in_sectors buf (Int32.of_int t.size_in_sectors); set_header_major_version buf t.major_version; set_header_minor_version buf t.minor_version; set_header_checksum buf t.checksum; set_header_marker buf t.marker let offset (x: Header.t) = Int64.(x.Header.table_offset ++ (of_int (BAT.sizeof_bytes x))) end module Batmap = struct type t = Cstruct.t let sizeof_bytes (x: Header.t) = (x.Header.max_table_entries + 7) lsr 3 let sizeof (x: Header.t) = roundup_sector (sizeof_bytes x) let set t n = let byte = Cstruct.get_uint8 t (n / 8) in let bit = n mod 8 in let mask = 0x80 lsr bit in Cstruct.set_uint8 t (n / 8) (byte lor mask) let get t n = let byte = Cstruct.get_uint8 t (n / 8) in let bit = n mod 8 in let mask = 0x80 lsr bit in byte land mask <> mask let unmarshal (buf: Cstruct.t) (h: Header.t) (bh: Batmap_header.t) = let open Rresult in let open Rresult.R.Infix in let needed = Cstruct.sub buf 0 (sizeof_bytes h) in let checksum = Checksum.of_cstruct buf in ( if checksum <> bh.Batmap_header.checksum then R.error (Failure (Printf.sprintf "Invalid checksum. Expected %08lx got %08lx" bh.Batmap_header.checksum checksum)) else R.ok () ) >>= fun () -> R.ok needed end module Bitmap = struct type t = | Full | Partial of Cstruct.t let get t sector_in_block = match t with | Full -> true | Partial buf -> let sector_in_block = Int64.to_int sector_in_block in let bitmap_byte = Cstruct.get_uint8 buf (sector_in_block / 8) in let bitmap_bit = sector_in_block mod 8 in let mask = 0x80 lsr bitmap_bit in (bitmap_byte land mask) = mask let set t sector_in_block = match t with | Partial buf -> let sector_in_block = Int64.to_int sector_in_block in let bitmap_byte = Cstruct.get_uint8 buf (sector_in_block / 8) in let bitmap_bit = sector_in_block mod 8 in let mask = 0x80 lsr bitmap_bit in if (bitmap_byte land mask) = mask else begin let byte_offset = sector_in_block / 8 in Cstruct.set_uint8 buf byte_offset (bitmap_byte lor mask); let sector_start = (byte_offset lsr sector_shift) lsl sector_shift in Some (Int64.of_int sector_start, Cstruct.sub buf sector_start sector_size) end let setv t sector_in_block remaining = let rec loop updates sector remaining = match updates, remaining with | None, 0L -> None | Some (offset, bufs), 0L -> Some (offset, List.rev bufs) | _, _n -> let sector' = Int64.succ sector in let remaining' = Int64.pred remaining in begin match updates, set t sector with | _, None -> loop updates sector' remaining' | Some (offset, _), Some (offset', _) when offset = offset' -> loop updates sector' remaining' | Some (offset, bufs), Some (offset', buf) when offset' = Int64.succ offset -> loop (Some(offset, buf :: bufs)) sector' remaining' | None, Some (offset', buf) -> loop (Some (offset', [ buf ])) sector' remaining' | _, _ -> end in loop None sector_in_block remaining end module Bitmap_cache = struct type t = { all_zeroes: Cstruct.t; all_ones: Cstruct.t; } let all_ones size = if size = Cstruct.len sector_all_ones then sector_all_ones else constant size 0xff let all_zeroes size = if size = Cstruct.len sector_all_zeroes then sector_all_zeroes else constant size 0x0 let make t = let sizeof_bitmap = Header.sizeof_bitmap t in let cache = ref None in let all_ones = all_ones sizeof_bitmap in let all_zeroes = all_zeroes sizeof_bitmap in { cache; all_ones; all_zeroes } end module Sector = struct type t = Cstruct.t let dump t = if Cstruct.len t = 0 then Printf.printf "Empty sector\n" else for i=0 to Cstruct.len t - 1 do if (i mod 16 = 15) then Printf.printf "%02x\n" (Cstruct.get_uint8 t i) else Printf.printf "%02x " (Cstruct.get_uint8 t i) done end module Vhd = struct type 'a t = { filename: string; rw: bool; handle: 'a; header: Header.t; footer: Footer.t; parent: 'a t option; bat: BAT.t; batmap: (Batmap_header.t * Batmap.t) option; bitmap_cache: Bitmap_cache.t; } let resize t new_size = if new_size > t.footer.Footer.original_size then invalid_arg "Vhd.resize"; { t with footer = { t.footer with Footer.current_size = new_size } } let rec dump t = Printf.printf "VHD file: %s\n" t.filename; Header.dump t.header; Footer.dump t.footer; match t.parent with | None -> () | Some parent -> dump parent let used_max_table_entries t = Some tools will create a larger - than - necessary BAT for small .vhds to allow the virtual size to be changed later . allow the virtual size to be changed later. *) let max_table_entries = t.header.Header.max_table_entries in let block_size_bytes_shift = t.header.Header.block_size_sectors_shift + sector_shift in let current_size_blocks = Int64.(to_int (shift_right (add t.footer.Footer.current_size (sub (1L lsl block_size_bytes_shift) 1L)) block_size_bytes_shift)) in if current_size_blocks > max_table_entries then failwith (Printf.sprintf "max_table_entries (%d) < current size (%d) expressed in blocks (1 << %d)" max_table_entries current_size_blocks block_size_bytes_shift); current_size_blocks type block_marker = | Start of (string * int64) | End of (string * int64) let check_overlapping_blocks t = let tomarkers name start length = [Start (name,start); End (name,Int64.sub (Int64.add start length) 1L)] in let blocks = tomarkers "footer_at_top" 0L 512L in let blocks = (tomarkers "header" t.footer.Footer.data_offset 1024L) @ blocks in let blocks = if t.footer.Footer.disk_type = Disk_type.Differencing_hard_disk then begin let locators = Array.mapi (fun i l -> (i,l)) t.header.Header.parent_locators in let locators = Array.to_list locators in let open Parent_locator in let locators = List.filter (fun (_,l) -> l.platform_code <> Platform_code.None) locators in let locations = List.map (fun (i,l) -> let name = Printf.sprintf "locator block %d" i in let start = l.platform_data_offset in let length = Int64.of_int32 l.platform_data_space in tomarkers name start length) locators in (List.flatten locations) @ blocks end else blocks in let bat_start = t.header.Header.table_offset in let bat_size = Int64.of_int t.header.Header.max_table_entries in let bat = tomarkers "BAT" bat_start bat_size in let blocks = bat @ blocks in let bat_blocks = ref [] in for i = 0 to BAT.length t.bat - 1 do let e = BAT.get t.bat i in if e <> BAT.unused then begin let name = Printf.sprintf "block %d" i in let start = Int64.mul 512L (Int64.of_int32 (BAT.get t.bat i)) in let size = Int64.shift_left 1L (t.header.Header.block_size_sectors_shift + sector_shift) in bat_blocks := (tomarkers name start size) @ !bat_blocks end done; let blocks = blocks @ !bat_blocks in let get_pos = function | Start (_,a) -> a | End (_,a) -> a in let to_string = function | Start (name,pos) -> Printf.sprintf "%Lx START of section '%s'" pos name | End (name,pos) -> Printf.sprintf "%Lx END of section '%s'" pos name in let l = List.sort (fun a b -> compare (get_pos a) (get_pos b)) blocks in List.iter (fun marker -> Printf.printf "%s\n" (to_string marker)) l exception EmptyVHD let get_top_unused_offset header bat = let open Int64 in try let last_block_start = let max_entry = bat.BAT.highest_value in if max_entry = -1l then raise EmptyVHD; 512L ** (of_int32 max_entry) in last_block_start ++ (of_int (Header.sizeof_bitmap header)) ++ (1L lsl (header.Header.block_size_sectors_shift + sector_shift)) with | EmptyVHD -> let pos = add header.Header.table_offset (mul 4L (of_int header.Header.max_table_entries)) in pos let get_free_sector header bat = let open Int64 in let next_free_byte = get_top_unused_offset header bat in to_int32 ((next_free_byte ++ 511L) lsr sector_shift) module Field = struct type 'a f = { name: string; get: 'a t -> string; } let _features = "features" let _data_offset = "data-offset" let _timestamp = "time-stamp" let _creator_application = "creator-application" let _creator_version = "creator_version" let _creator_host_os = "creator-host-os" let _original_size = "original-size" let _current_size = "current-size" let _geometry = "geometry" let _disk_type = "disk-type" let _footer_checksum = "footer-checksum" let _uuid = "uuid" let _saved_state = "saved-state" let _table_offset = "table-offset" let _max_table_entries = "max-table-entries" let _block_size_sectors_shift = "block-size-sectors-shift" let _header_checksum = "header-checksum" let _parent_uuid = "parent_unique_id" let _parent_time_stamp = "parent-time-stamp" let _parent_unicode_name = "parent-unicode-name" let _parent_locator_prefix = "parent-locator-" let _parent_locator_prefix_len = String.length _parent_locator_prefix let _batmap_version = "batmap-version" let _batmap_offset = "batmap-offset" let _batmap_size_in_sectors = "batmap-size-in-sectors" let _batmap_checksum = "batmap-checksum" let list = [ _features; _data_offset; _timestamp; _creator_application; _creator_version; _creator_host_os; _original_size; _current_size; _geometry; _disk_type; _footer_checksum; _uuid; _saved_state; _table_offset; _max_table_entries; _block_size_sectors_shift; _header_checksum; _parent_uuid; _parent_time_stamp; _parent_unicode_name ] @ (List.map (fun x -> _parent_locator_prefix ^ (string_of_int x)) [0; 1; 2; 3; 4; 5; 6;7] ) @ [ _batmap_version; _batmap_offset; _batmap_size_in_sectors; _batmap_checksum ] let startswith prefix x = let prefix' = String.length prefix and x' = String.length x in prefix' <= x' && (String.sub x 0 prefix' = prefix) let get t key = let opt f = function | None -> None | Some x -> Some (f x) in if key = _features then Some (String.concat ", " (List.map Feature.to_string t.footer.Footer.features)) else if key = _data_offset then Some (Int64.to_string t.footer.Footer.data_offset) else if key = _timestamp then Some (Int32.to_string t.footer.Footer.time_stamp) else if key = _creator_application then Some t.footer.Footer.creator_application else if key = _creator_version then Some (Int32.to_string t.footer.Footer.creator_version) else if key = _creator_host_os then Some (Host_OS.to_string t.footer.Footer.creator_host_os) else if key = _original_size then Some (Int64.to_string t.footer.Footer.original_size) else if key = _current_size then Some (Int64.to_string t.footer.Footer.current_size) else if key = _geometry then Some (Geometry.to_string t.footer.Footer.geometry) else if key = _disk_type then Some (Disk_type.to_string t.footer.Footer.disk_type) else if key = _footer_checksum then Some (Int32.to_string t.footer.Footer.checksum) else if key = _uuid then Some (Uuidm.to_string t.footer.Footer.uid) else if key = _saved_state then Some (string_of_bool t.footer.Footer.saved_state) else if key = _table_offset then Some (Int64.to_string t.header.Header.table_offset) else if key = _max_table_entries then Some (string_of_int t.header.Header.max_table_entries) else if key = _block_size_sectors_shift then Some (string_of_int t.header.Header.block_size_sectors_shift) else if key = _header_checksum then Some (Int32.to_string t.header.Header.checksum) else if key = _parent_uuid then Some (Uuidm.to_string t.header.Header.parent_unique_id) else if key = _parent_time_stamp then Some (Int32.to_string t.header.Header.parent_time_stamp) else if key = _parent_unicode_name then Some (UTF16.to_utf8_exn t.header.Header.parent_unicode_name) else if startswith _parent_locator_prefix key then begin try let i = int_of_string (String.sub key _parent_locator_prefix_len (String.length key - _parent_locator_prefix_len)) in Some (Parent_locator.to_string t.header.Header.parent_locators.(i)) with _ -> None end else if key = _batmap_version then opt (fun (t, _) -> Printf.sprintf "%d.%d" t.Batmap_header.major_version t.Batmap_header.minor_version) t.batmap else if key = _batmap_offset then opt (fun (t, _) -> Int64.to_string t.Batmap_header.offset) t.batmap else if key = _batmap_size_in_sectors then opt (fun (t, _) -> string_of_int t.Batmap_header.size_in_sectors) t.batmap else if key = _batmap_checksum then opt (fun (t, _) -> Int32.to_string t.Batmap_header.checksum) t.batmap else None type 'a t = 'a f end end module Raw = struct type 'a t = { filename: string; handle: 'a; } end type size = { total: int64; TODO : rename to ' data ' empty: int64; copy: int64; } let empty = { total = 0L; metadata = 0L; empty = 0L; copy = 0L } module Stream = functor(A: S.ASYNC) -> struct open A type 'a ll = | Cons of 'a * (unit -> 'a ll t) | End let rec iter f = function | Cons(x, rest) -> f x >>= fun () -> rest () >>= fun x -> iter f x | End -> return () let rec fold_left f initial xs = match xs with | End -> return initial | Cons (x, rest) -> f initial x >>= fun initial' -> rest () >>= fun xs -> fold_left f initial' xs type 'a stream = { elements: 'a Element.t ll; size: size; } end module Fragment = struct type t = | Header of Header.t | Footer of Footer.t | BAT of BAT.t | Batmap of Batmap.t | Block of int64 * Cstruct.t end module From_input = functor (I: S.INPUT) -> struct open I type 'a ll = | Cons of 'a * (unit -> 'a ll t) | End let (>>|=) m f = match m with | Error e -> fail e | Ok x -> f x let (>+>) m f = return (Cons(m, f)) open Memory let openstream size_opt fd = let buffer = alloc Footer.sizeof in read fd buffer >>= fun () -> Footer.unmarshal buffer >>|= fun footer -> Fragment.Footer footer >+> fun () -> skip_to fd footer.Footer.data_offset >>= fun () -> let buffer = alloc Header.sizeof in read fd buffer >>= fun () -> Header.unmarshal buffer >>|= fun header -> Fragment.Header header >+> fun () -> BAT is at the table offset skip_to fd header.Header.table_offset >>= fun () -> let buffer = alloc (BAT.sizeof_bytes header) in read fd buffer >>= fun () -> let bat = BAT.unmarshal buffer header in Fragment.BAT bat >+> fun () -> let module M = Map.Make(Int64) in let phys_to_virt = BAT.fold (fun idx sector acc -> M.add sector idx acc) bat M.empty in let bitmap = alloc (Header.sizeof_bitmap header) in let data = alloc (1 lsl (header.Header.block_size_sectors_shift + sector_shift)) in let rec block blocks andthen = if M.is_empty blocks then andthen () else let s, idx = M.min_binding blocks in let physical_block_offset = Int64.(shift_left (of_int idx) header.Header.block_size_sectors_shift) in skip_to fd Int64.(shift_left s sector_shift) >>= fun () -> read fd bitmap >>= fun () -> let bitmap = Bitmap.Partial bitmap in let num_sectors = 1 lsl header.Header.block_size_sectors_shift in let length_of_span from = let this = Bitmap.get bitmap (Int64.of_int from) in let rec loop length i = if i < num_sectors && Bitmap.get bitmap (Int64.of_int i) = this then loop (length+1) (i+1) else length in loop 0 from in let rec sector i andthen = if i = num_sectors then andthen () else let len = length_of_span i in let frag = Cstruct.sub data 0 (len lsl sector_shift) in read fd frag >>= fun () -> let physical_offset = Int64.(add physical_block_offset (of_int i)) in if Bitmap.get bitmap (Int64.of_int i) then Fragment.Block(physical_offset, frag) >+> fun () -> sector (i + len) andthen else sector (i + len) andthen in sector 0 (fun () -> block (M.remove s blocks) andthen) in block phys_to_virt (fun () -> let buffer = alloc Footer.sizeof in ( match size_opt with | None -> return () | Some s -> let (&&&) = Int64.logand in let footer_offset = Int64.(sub s 1L &&& lognot 0b1_1111_1111L) in offset is last 512 - byte - aligned block in the file skip_to fd footer_offset) >>= fun () -> read fd buffer >>= fun () -> Footer.unmarshal buffer >>|= fun footer -> Fragment.Footer footer >+> fun () -> return End) end module From_file = functor(F: S.FILE) -> struct open F let (>>|=) m f = match m with | Error e -> fail e | Ok x -> f x let search filename path = let rec loop = function | [] -> return None | x :: xs -> let possibility = Filename.concat x filename in ( F.exists possibility >>= function | true -> return (Some possibility) | false -> loop xs ) in if Filename.is_relative filename then loop path else loop [ "" ] let rec unaligned_really_write fd offset buffer = let open Int64 in let sector_start = (offset lsr sector_shift) lsl sector_shift in let current = Memory.alloc sector_size in really_read fd sector_start current >>= fun () -> let adjusted_len = offset ++ (of_int (Cstruct.len buffer)) -- sector_start in let write_this_time = max adjusted_len 512L in let remaining_to_write = adjusted_len -- write_this_time in let useful_bytes_to_write = Stdlib.min (Cstruct.len buffer) (to_int (write_this_time -- offset ++ sector_start)) in Cstruct.blit buffer 0 current (to_int (offset -- sector_start)) useful_bytes_to_write; really_write fd sector_start current >>= fun () -> if remaining_to_write <= 0L then return () else unaligned_really_write fd (offset ++ (of_int useful_bytes_to_write)) (Cstruct.shift buffer useful_bytes_to_write) module Footer_IO = struct let read fd pos = let buf = Memory.alloc Footer.sizeof in really_read fd pos buf >>= fun () -> Footer.unmarshal buf >>|= fun x -> return x let write sector fd pos t = let t = Footer.marshal sector t in really_write fd pos sector >>= fun () -> return t end module Parent_locator_IO = struct open Parent_locator let read fd t = let l = Int32.to_int t.platform_data_length in let l_rounded = roundup_sector l in ( if l_rounded = 0 then return (Cstruct.create 0) else let platform_data = Memory.alloc l_rounded in really_read fd t.platform_data_offset platform_data >>= fun () -> return platform_data ) >>= fun platform_data -> let platform_data = Cstruct.sub platform_data 0 l in return { t with platform_data } let write fd t = if t.platform_code <> Platform_code.None then unaligned_really_write fd t.platform_data_offset t.platform_data else return () end module Header_IO = struct open Header let get_parent_filename t search_path = let rec test checked_so_far n = if n >= Array.length t.parent_locators then fail (Failure (Printf.sprintf "Failed to find parent (tried [ %s ] with search_path %s)" (String.concat "; " checked_so_far) (String.concat "; " search_path) )) else let l = t.parent_locators.(n) in let open Parent_locator in match to_filename l with | Some path -> ( search path search_path >>= function | None -> test (path :: checked_so_far) (n + 1) | Some path -> return path ) | None -> test checked_so_far (n + 1) in test [] 0 let read fd pos = let buf = Memory.alloc sizeof in really_read fd pos buf >>= fun () -> unmarshal buf >>|= fun t -> let rec read_parent_locator = function | 8 -> return () | n -> let p = t.parent_locators.(n) in Parent_locator_IO.read fd p >>= fun p -> t.parent_locators.(n) <- p; read_parent_locator (n + 1) in read_parent_locator 0 >>= fun () -> return t let write buf fd pos t = let t' = marshal buf t in let rec write_parent_locator = function | 8 -> return () | n -> let p = t.parent_locators.(n) in Parent_locator_IO.write fd p >>= fun () -> write_parent_locator (n + 1) in really_write fd pos buf >>= fun () -> write_parent_locator 0 >>= fun () -> return t' end module BAT_IO = struct open BAT let read fd (header: Header.t) = let buf = Memory.alloc (sizeof_bytes header) in really_read fd header.Header.table_offset buf >>= fun () -> return (unmarshal buf header) let write buf fd (header: Header.t) t = marshal buf t; really_write fd header.Header.table_offset buf end module Batmap_IO = struct let read fd (header: Header.t) = let buf = Memory.alloc Batmap_header.sizeof in really_read fd (Batmap_header.offset header) buf >>= fun () -> match Batmap_header.unmarshal buf with | Error _ -> return None | Ok h -> let batmap = Memory.alloc (h.Batmap_header.size_in_sectors * sector_size) in ( really_read fd h.Batmap_header.offset batmap >>= fun () -> match Batmap.unmarshal batmap header h with | Error _ -> return None | Ok batmap -> return (Some (h, batmap))) end module Bitmap_IO = struct open Bitmap let read fd (header: Header.t) (bat: BAT.t) (block: int) = let open Int64 in let pos = (of_int32 (BAT.get bat block)) lsl sector_shift in let bitmap = Memory.alloc (Header.sizeof_bitmap header) in really_read fd pos bitmap >>= fun () -> return (Partial bitmap) end module Vhd_IO = struct open Vhd let write_trailing_footer buf handle t = let sector = Vhd.get_free_sector t.Vhd.header t.Vhd.bat in let offset = Int64.(shift_left (of_int32 sector) sector_shift) in Footer_IO.write buf handle offset t.Vhd.footer >>= fun _ -> return () let write_metadata t = let footer_buf = Memory.alloc Footer.sizeof in Footer_IO.write footer_buf t.Vhd.handle 0L t.Vhd.footer >>= fun footer -> write_trailing_footer footer_buf t.Vhd.handle t >>= fun () -> let t ={ t with Vhd.footer } in let buf = Memory.alloc Header.sizeof in Header_IO.write buf t.Vhd.handle t.Vhd.footer.Footer.data_offset t.Vhd.header >>= fun header -> let t = { t with Vhd.header } in let buf = Memory.alloc (BAT.sizeof_bytes header) in BAT_IO.write buf t.Vhd.handle t.Vhd.header t.Vhd.bat >>= fun () -> return t let create_dynamic ~filename ~size ?(uuid = Uuidm.v `V4) ?(saved_state=false) ?(features=[]) () = The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT *) let data_offset = 512L in let table_offset = 2048L in let open Int64 in let header = Header.create ~table_offset ~current_size:size () in let size = (of_int header.Header.max_table_entries) lsl (header.Header.block_size_sectors_shift + sector_shift) in let footer = Footer.create ~features ~data_offset ~current_size:size ~disk_type:Disk_type.Dynamic_hard_disk ~uid:uuid ~saved_state () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let batmap = None in let bitmap_cache = Bitmap_cache.make header in F.create filename >>= fun handle -> let t = { filename; rw = true; handle; header; footer; parent = None; bat; batmap; bitmap_cache } in write_metadata t >>= fun t -> return t let make_relative_path base target = assert (not (Filename.is_relative base)); assert (not (Filename.is_relative target)); let to_list path = let rec loop acc path = if Filename.dirname path = "/" then Filename.basename path :: acc else loop (Filename.basename path :: acc) (Filename.dirname path) in loop [] path in let base = to_list (Filename.dirname base) in let target = to_list target in let rec remove_common = function | [], y -> [], y | x, [] -> x, [] | x :: xs, y :: ys when x = y -> remove_common (xs, ys) | xs, ys -> xs, ys in let base, target = remove_common (base, target) in let base = List.map (fun _ -> "..") base in String.concat "/" (base @ target) let create_difference ~filename ~parent ?(relative_path = true) ?(uuid=Uuidm.v `V4) ?(saved_state=false) ?(features=[]) () = let data_offset = 512L in let table_offset = 2048L in let footer = Footer.create ~features ~data_offset ~time_stamp:(F.now ()) ~current_size:parent.Vhd.footer.Footer.current_size ~disk_type:Disk_type.Differencing_hard_disk ~uid:uuid ~saved_state () in let parent_filename = if relative_path then make_relative_path filename parent.Vhd.filename else parent.Vhd.filename in let parent_locators = Parent_locator.from_filename parent_filename in F.get_modification_time parent.Vhd.filename >>= fun parent_time_stamp -> let header = Header.create ~table_offset ~current_size:parent.Vhd.footer.Footer.current_size ~block_size_sectors_shift:parent.Vhd.header.Header.block_size_sectors_shift ~parent_unique_id:parent.Vhd.footer.Footer.uid ~parent_time_stamp ~parent_unicode_name:(UTF16.of_utf8 parent.Vhd.filename) ~parent_locators () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in F.create filename >>= fun handle -> F.openfile parent.Vhd.filename false >>= fun parent_handle -> let parent = { parent with handle = parent_handle } in let batmap = None in let bitmap_cache = Bitmap_cache.make header in let t = { filename; rw = true; handle; header; footer; parent = Some parent; bat; batmap; bitmap_cache } in write_metadata t >>= fun t -> return t let rec openchain ?(path = ["."]) filename rw = search filename path >>= function | None -> fail (Failure (Printf.sprintf "Failed to find %s (search path = %s)" filename (String.concat ":" path))) | Some filename -> F.openfile filename rw >>= fun handle -> Footer_IO.read handle 0L >>= fun footer -> Header_IO.read handle (Int64.of_int Footer.sizeof) >>= fun header -> BAT_IO.read handle header >>= fun bat -> (match footer.Footer.disk_type with | Disk_type.Differencing_hard_disk -> let path = Filename.dirname filename :: path in Header_IO.get_parent_filename header path >>= fun parent_filename -> openchain ~path parent_filename false >>= fun p -> return (Some p) | _ -> return None) >>= fun parent -> Batmap_IO.read handle header >>= fun batmap -> let bitmap_cache = Bitmap_cache.make header in return { filename; rw; handle; header; footer; bat; bitmap_cache; batmap; parent } let openfile filename rw = F.openfile filename rw >>= fun handle -> Footer_IO.read handle 0L >>= fun footer -> Header_IO.read handle (Int64.of_int Footer.sizeof) >>= fun header -> BAT_IO.read handle header >>= fun bat -> Batmap_IO.read handle header >>= fun batmap -> let bitmap_cache = Bitmap_cache.make header in return { filename; rw; handle; header; footer; bat; bitmap_cache; batmap; parent = None } let close t = ( if t.Vhd.rw then (write_metadata t >>= fun _ -> return ()) else return () ) >>= fun () -> let rec close t = F.close t.Vhd.handle >>= fun () -> match t.Vhd.parent with | None -> return () | Some p -> close p in close t let get_bitmap t block_num = match !(t.Vhd.bitmap_cache.Bitmap_cache.cache) with | Some (block_num', bitmap) when block_num' = block_num -> return bitmap | _ -> Bitmap_IO.read t.Vhd.handle t.Vhd.header t.Vhd.bat block_num >>= fun bitmap -> t.Vhd.bitmap_cache.Bitmap_cache.cache := Some(block_num, bitmap); return bitmap let rec get_sector_location t sector = let open Int64 in if sector lsl sector_shift > t.Vhd.footer.Footer.current_size perhaps elements in the vhd chain have different sizes else let maybe_get_from_parent () = match t.Vhd.footer.Footer.disk_type,t.Vhd.parent with | Disk_type.Differencing_hard_disk,Some vhd2 -> get_sector_location vhd2 sector | Disk_type.Differencing_hard_disk,None -> fail (Failure "Sector in parent but no parent found!") | Disk_type.Dynamic_hard_disk,_ -> return None | Disk_type.Fixed_hard_disk,_ -> fail (Failure "Fixed disks are not supported") in let block_num = to_int (sector lsr t.Vhd.header.Header.block_size_sectors_shift) in let sector_in_block = rem sector (1L lsl t.Vhd.header.Header.block_size_sectors_shift) in if BAT.get t.Vhd.bat block_num = BAT.unused then maybe_get_from_parent () else begin get_bitmap t block_num >>= fun bitmap -> let in_this_bitmap = Bitmap.get bitmap sector_in_block in match t.Vhd.footer.Footer.disk_type, in_this_bitmap with | _, true -> let data_sector = (of_int32 (BAT.get t.Vhd.bat block_num)) ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) ++ sector_in_block in return (Some(t, data_sector)) | Disk_type.Dynamic_hard_disk, false -> return None | Disk_type.Differencing_hard_disk, false -> maybe_get_from_parent () | Disk_type.Fixed_hard_disk, _ -> fail (Failure "Fixed disks are not supported") end let read_sector t sector data = let open Int64 in if sector < 0L || (sector lsl sector_shift >= t.Vhd.footer.Footer.current_size) then fail (Invalid_sector(sector, t.Vhd.footer.Footer.current_size lsr sector_shift)) else get_sector_location t sector >>= function | None -> return false | Some (t, offset) -> really_read t.Vhd.handle (offset lsl sector_shift) data >>= fun () -> return true let parallel f xs = let ts = List.map f xs in let rec join = function | [] -> return () | t :: ts -> t >>= fun () -> join ts in join ts let rec write_physical t (offset, bufs) = match bufs with | [] -> return () | b :: bs -> really_write t offset b >>= fun () -> write_physical t (Int64.(add offset (of_int (Cstruct.len b))), bs) let count_sectors bufs = let rec loop acc = function | [] -> acc | b :: bs -> loop (Cstruct.len b / sector_size + acc) bs in loop 0 bufs let quantise block_size_in_sectors offset bufs = let open Int64 in let block = to_int (div offset (of_int block_size_in_sectors)) in let sector = to_int (rem offset (of_int block_size_in_sectors)) in let rec loop acc (offset, bufs) (block, sector) = function | [] -> let acc = if bufs = [] then acc else (offset, bufs) :: acc in List.rev acc | b :: bs -> let remaining_this_block = block_size_in_sectors - sector in let available = Cstruct.len b / sector_size in if available = 0 then loop acc (offset, bufs) (block, sector) bs else if available < remaining_this_block then loop acc (offset, b :: bufs) (block, sector + available) bs else if available = remaining_this_block then loop ((offset, List.rev (b :: bufs)) :: acc) (add offset (of_int available), []) (block + 1, 0) bs else let b' = Cstruct.sub b 0 (remaining_this_block * sector_size) in let b'' = Cstruct.shift b (remaining_this_block * sector_size) in loop ((offset, List.rev (b' :: bufs)) :: acc) (add offset (of_int remaining_this_block), []) (block + 1, 0) (b'' :: bs) in List.rev (loop [] (offset, []) (block, sector) bufs) let write t offset bufs = let block_size_in_sectors = 1 lsl t.Vhd.header.Header.block_size_sectors_shift in let _bitmap_size = Header.sizeof_bitmap t.Vhd.header in We permute data and bitmap sector writes , but only flush the BAT at the end . In the event of a crash during this operation , arbitrary data sectors will have been written but we will never expose garbage ( as would happen if we flushed the BAT before writing the data blocks . In the event of a crash during this operation, arbitrary data sectors will have been written but we will never expose garbage (as would happen if we flushed the BAT before writing the data blocks. *) let open Int64 in let rec loop (write_bat, acc) = function | [] -> return (write_bat, acc) | (offset, bufs) :: rest -> let block_num = to_int (offset lsr t.Vhd.header.Header.block_size_sectors_shift) in assert (block_num < (BAT.length t.Vhd.bat)); let nsectors = of_int (count_sectors bufs) in ( let size_sectors = t.Vhd.footer.Footer.current_size lsr sector_shift in if offset < 0L then fail (Invalid_sector(offset, size_sectors)) else if (add offset nsectors) > size_sectors then fail (Invalid_sector(add offset nsectors, size_sectors)) else return () ) >>= fun () -> let sector_in_block = rem offset (of_int block_size_in_sectors) in if BAT.get t.Vhd.bat block_num <> BAT.unused then begin let bitmap_sector = of_int32 (BAT.get t.Vhd.bat block_num) in let data_sector = bitmap_sector ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) ++ sector_in_block in let data_writes = [ (data_sector lsl sector_shift), bufs ] in ( get_bitmap t block_num >>= fun bitmap -> match Bitmap.setv bitmap sector_in_block nsectors with | None -> return [] | Some (offset, bufs) -> return [ (bitmap_sector lsl sector_shift) ++ offset, bufs] ) >>= fun bitmap_writes -> loop (write_bat, acc @ bitmap_writes @ data_writes) rest end else begin BAT.set t.Vhd.bat block_num (Vhd.get_free_sector t.Vhd.header t.Vhd.bat); let bitmap_sector = of_int32 (BAT.get t.Vhd.bat block_num) in let block_start = bitmap_sector ++ (of_int (Header.sizeof_bitmap t.Vhd.header) lsr sector_shift) in let data_sector = block_start ++ sector_in_block in let data_writes = [ (data_sector lsl sector_shift), bufs ] in We will have to write the bitmap anyway , but if we have no parent then we write all 1s since we 're expected to physically zero the block . write all 1s since we're expected to physically zero the block. *) let bitmap_writes = if t.Vhd.parent = None then [ (bitmap_sector lsl sector_shift), [ t.Vhd.bitmap_cache.Bitmap_cache.all_ones ] ] else let bitmap_size = Header.sizeof_bitmap t.Vhd.header in let bitmap = Memory.alloc bitmap_size in Cstruct.blit t.Vhd.bitmap_cache.Bitmap_cache.all_zeroes 0 bitmap 0 bitmap_size; ignore (Bitmap.setv (Bitmap.Partial bitmap) sector_in_block nsectors); [ (bitmap_sector lsl sector_shift), [ bitmap ] ] in let zeroes offset length = let rec zero acc remaining = if remaining = 0L then acc else let this = min remaining (Int64.of_int sectors_in_2mib) in let buf = Cstruct.sub empty_2mib 0 (Int64.to_int this * sector_size) in zero (buf :: acc) (Int64.sub remaining this) in [ offset lsl sector_shift, zero [] length ] in let before = zeroes block_start sector_in_block in let trailing_sectors = sub (of_int block_size_in_sectors) (add sector_in_block nsectors) in let after = zeroes (add (add block_start sector_in_block) nsectors) trailing_sectors in loop (true, (acc @ bitmap_writes @ before @ data_writes @ after)) rest end in loop (false, []) (quantise block_size_in_sectors offset bufs) >>= fun (write_bat, data_writes) -> parallel (write_physical t.Vhd.handle) data_writes >>= fun () -> if write_bat then begin let bat_buffer = Memory.alloc (BAT.sizeof_bytes t.Vhd.header) in BAT_IO.write bat_buffer t.Vhd.handle t.Vhd.header t.Vhd.bat end else return () end module Raw_IO = struct open Raw let openfile filename rw = F.openfile filename rw >>= fun handle -> return { filename; handle } let close t = F.close t.handle let create ~filename ~size () = F.create filename >>= fun handle -> F.really_write handle size (Cstruct.create 0) >>= fun () -> return { filename; handle } end include Stream(F) Test whether a block is in any BAT in the path to the root . If so then we will look up all sectors . look up all sectors. *) let rec in_any_bat vhd i = i < vhd.Vhd.header.Header.max_table_entries && match BAT.get vhd.Vhd.bat i <> BAT.unused, vhd.Vhd.parent with | true, _ -> true | false, Some parent -> in_any_bat parent i | false, None -> false let rec coalesce_request acc s = let open Int64 in s >>= fun next -> match next, acc with | End, None -> return End | End, Some x -> return (Cons(x, fun () -> return End)) | Cons(`Sectors s, next), None -> return(Cons(`Sectors s, fun () -> coalesce_request None (next ()))) | Cons(`Sectors _, _next), Some x -> return(Cons(x, fun () -> coalesce_request None s)) | Cons(`Empty n, next), None -> coalesce_request (Some(`Empty n)) (next ()) | Cons(`Empty n, next), Some(`Empty m) -> coalesce_request (Some(`Empty (n ++ m))) (next ()) | Cons(`Empty _n, _next), Some x -> return (Cons(x, fun () -> coalesce_request None s)) | Cons(`Copy(h, ofs, len), next), None -> coalesce_request (Some (`Copy(h, ofs, len))) (next ()) | Cons(`Copy(h, ofs, len), next), Some(`Copy(h', ofs', len')) -> if ofs ++ len = ofs' && h == h' then coalesce_request (Some(`Copy(h, ofs, len ++ len'))) (next ()) else if ofs' ++ len' = ofs && h == h' then coalesce_request (Some(`Copy(h, ofs', len ++ len'))) (next ()) else return (Cons(`Copy(h', ofs', len'), fun () -> coalesce_request None s)) | Cons(`Copy(_h, _ofs, _len), _next), Some x -> return(Cons(x, fun () -> coalesce_request None s)) let twomib_bytes = 2 * 1024 * 1024 let twomib_sectors = twomib_bytes / 512 let rec expand_empty_elements twomib_empty s = let open Int64 in s >>= function | End -> return End | Cons(`Empty n, next) -> let rec copy n = let this = to_int (min n (of_int twomib_sectors)) in let block = Cstruct.sub twomib_empty 0 (this * 512) in let n = n -- (of_int this) in let next () = if n > 0L then copy n else expand_empty_elements twomib_empty (next ()) in return (Cons(`Sectors block, next)) in copy n | Cons(x, next) -> return (Cons(x, fun () -> expand_empty_elements twomib_empty (next ()))) let expand_empty s = let open Int64 in let size = { s.size with empty = 0L; metadata = s.size.metadata ++ s.size.empty } in let twomib_empty = let b = Cstruct.create twomib_bytes in for i = 0 to twomib_bytes - 1 do Cstruct.set_uint8 b i 0 done; b in expand_empty_elements twomib_empty (return s.elements) >>= fun elements -> return { elements; size } let rec expand_copy_elements buffer s = let open Int64 in s >>= function | End -> return End | Cons(`Copy(h, sector_start, sector_len), next) -> let rec copy sector_start sector_len = let this = to_int (min sector_len (of_int twomib_sectors)) in let data = Cstruct.sub buffer 0 (this * 512) in really_read h (sector_start ** 512L) data >>= fun () -> let sector_start = sector_start ++ (of_int this) in let sector_len = sector_len -- (of_int this) in let next () = if sector_len > 0L then copy sector_start sector_len else expand_copy_elements buffer (next ()) in return (Cons(`Sectors data, next)) in copy sector_start sector_len | Cons(x, next) -> return (Cons(x, fun () -> expand_copy_elements buffer (next ()))) let expand_copy s = let open Int64 in let size = { s.size with copy = 0L; metadata = s.size.metadata ++ s.size.copy } in let buffer = Memory.alloc twomib_bytes in expand_copy_elements buffer (return s.elements) >>= fun elements -> return { elements; size } module Vhd_input = struct If we 're streaming a fully consolidated disk ( where from = None ) then we include blocks if they 're in any BAT on the path to the tree root . If from = Some from then we must take the two paths to the tree root : t , from : vhd list and include blocks where x | x \in ( from - t ) " we must revert changes specific to the ' from ' branch " and x | x \in ( t - from ) " we must include changes specific to the ' t ' branch " blocks if they're in any BAT on the path to the tree root. If from = Some from then we must take the two paths to the tree root: t, from : vhd list and include blocks where x | x \in (from - t) "we must revert changes specific to the 'from' branch" and x | x \in (t - from) "we must include changes specific to the 't' branch" *) let include_block from t = match from with | None -> in_any_bat t | Some from -> let module E = struct We ca n't simply compare filenames as strings ( consider " ./././foo " and " foo " ) . We use the combination of the vhd 's builtin uuid ( which should be enough by itself ) and the basename , just in case there exist duplicate uuids in the wild ( because no - one else seems to really care to check ) We use the combination of the vhd's builtin uuid (which should be enough by itself) and the basename, just in case there exist duplicate uuids in the wild (because no-one else seems to really care to check) *) type key = Uuidm.t * string type t = (key * BAT.t) let _to_string ((uuid, filename), _) = Printf.sprintf "%s:%s" (Uuidm.to_string uuid) filename let compare x y = compare (fst x) (fst y) end in let module BATS = Set.Make(E) in let rec make t = let rest = match t.Vhd.parent with | None -> BATS.empty | Some x -> make x in BATS.add ((t.Vhd.footer.Footer.uid, Filename.basename t.Vhd.filename), t.Vhd.bat) rest in let t_branch = make t in let from_branch = make from in let to_include = BATS.(union (diff t_branch from_branch) (diff from_branch t_branch)) in fun i -> BATS.fold (fun (_, bat) acc -> acc || (i < BAT.length bat && BAT.get bat i <> BAT.unused)) to_include false let raw_common ?from ?(raw: 'a) (vhd: fd Vhd.t) = let block_size_sectors_shift = vhd.Vhd.header.Header.block_size_sectors_shift in let max_table_entries = Vhd.used_max_table_entries vhd in let empty_block = `Empty (Int64.shift_left 1L block_size_sectors_shift) in let empty_sector = `Empty 1L in let include_block = include_block from vhd in let rec block i = let next_block () = block (i + 1) in if i = max_table_entries then return End else begin if not(include_block i) then return (Cons(empty_block, next_block)) else begin let absolute_block_start = Int64.(shift_left (of_int i) block_size_sectors_shift) in let rec sector j = let next_sector () = sector (j + 1) in let absolute_sector = Int64.(add absolute_block_start (of_int j)) in if j = 1 lsl block_size_sectors_shift then next_block () else match raw with | None -> begin Vhd_IO.get_sector_location vhd absolute_sector >>= function | None -> return (Cons(empty_sector, next_sector)) | Some (vhd', offset) -> return (Cons(`Copy(vhd'.Vhd.handle, offset, 1L), next_sector)) end | Some raw -> return (Cons(`Copy(raw, absolute_sector, 1L), next_sector)) in sector 0 end end in let rec count totals i = if i = max_table_entries then totals else begin if not(include_block i) then count { totals with empty = Int64.(add totals.empty (shift_left 1L (block_size_sectors_shift + sector_shift))) } (i + 1) else count { totals with copy = Int64.(add totals.copy (shift_left 1L (block_size_sectors_shift + sector_shift))) } (i + 1) end in coalesce_request None (block 0) >>= fun elements -> let size = count { empty with total = vhd.Vhd.footer.Footer.current_size } 0 in return { elements; size } let raw ?from (vhd: fd Vhd.t) = raw_common ?from vhd let vhd_common ?from ?raw ?(emit_batmap=false)(t: fd Vhd.t) = let block_size_sectors_shift = t.Vhd.header.Header.block_size_sectors_shift in let max_table_entries = Vhd.used_max_table_entries t in The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT Batmap_header | iff batmap Batmap | byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT Batmap_header | iff batmap Batmap | *) let data_offset = 512L in let table_offset = 2048L in let size = t.Vhd.footer.Footer.current_size in let disk_type = match from with | None -> Disk_type.Dynamic_hard_disk | Some _ -> Disk_type.Differencing_hard_disk in let footer = Footer.create ~data_offset ~current_size:size ~disk_type () in ( match from with | None -> return (Header.create ~table_offset ~current_size:size ~block_size_sectors_shift ()) | Some from -> let parent_locators = Parent_locator.from_filename from.Vhd.filename in F.get_modification_time from.Vhd.filename >>= fun parent_time_stamp -> let h = Header.create ~table_offset ~current_size:size ~block_size_sectors_shift ~parent_unique_id:from.Vhd.footer.Footer.uid ~parent_time_stamp ~parent_unicode_name:(UTF16.of_utf8 from.Vhd.filename) ~parent_locators () in return h ) >>= fun header -> let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let sizeof_bat = BAT.sizeof_bytes header in let sizeof_bitmap = Header.sizeof_bitmap header in let bitmap = Memory.alloc sizeof_bitmap in for i = 0 to sizeof_bitmap - 1 do Cstruct.set_uint8 bitmap i 0xff done; let sizeof_data_sectors = 1 lsl block_size_sectors_shift in let sizeof_data = 1 lsl (block_size_sectors_shift + sector_shift) in let include_block = include_block from t in Calculate where the first data block can go . Note the is already rounded up to the next sector boundary . rounded up to the next sector boundary. *) let next_free_sector_in_bytes = Int64.(table_offset ++ (of_int sizeof_bat)) in let batmap_header = Memory.alloc Batmap_header.sizeof in let batmap = Memory.alloc (Batmap.sizeof header) in for i = 0 to Batmap.sizeof header - 1 do Cstruct.set_uint8 batmap i 0 done; let first_block = if emit_batmap then Int64.(next_free_sector_in_bytes ++ (of_int Batmap_header.sizeof) ++ (of_int (Batmap.sizeof header))) else next_free_sector_in_bytes in let next_byte = ref first_block in for i = 0 to max_table_entries - 1 do if include_block i then begin BAT.set bat i (Int64.(to_int32(!next_byte lsr sector_shift))); Batmap.set batmap i; next_byte := Int64.(!next_byte ++ (of_int sizeof_bitmap) ++ (of_int sizeof_data)) end done; Batmap_header.marshal batmap_header { Batmap_header.offset = Int64.(next_free_sector_in_bytes ++ 512L); size_in_sectors = Batmap.sizeof header lsr sector_shift; major_version = Batmap_header.current_major_version; minor_version = Batmap_header.current_minor_version; checksum = Checksum.of_cstruct batmap; marker = 0; }; let write_sectors buf andthen = return(Cons(`Sectors buf, andthen)) in let rec block i andthen = let rec sector j = let next () = if j = sizeof_data_sectors - 1 then block (i + 1) andthen else sector (j + 1) in let absolute_sector = Int64.(add (shift_left (of_int i) block_size_sectors_shift) (of_int j)) in match raw with | None -> begin Vhd_IO.get_sector_location t absolute_sector >>= function | None -> return (Cons(`Empty 1L, next)) | Some (vhd', offset) -> return (Cons(`Copy(vhd'.Vhd.handle, offset, 1L), next)) end | Some raw -> return (Cons(`Copy(raw, absolute_sector, 1L), next)) in if i >= max_table_entries then andthen () else if include_block i then return(Cons(`Sectors bitmap, fun () -> sector 0)) else block (i + 1) andthen in let batmap andthen = if emit_batmap then write_sectors batmap_header (fun () -> write_sectors batmap andthen) else andthen () in assert(Footer.sizeof = 512); assert(Header.sizeof = 1024); let buf = Memory.alloc (max Footer.sizeof (max Header.sizeof sizeof_bat)) in let (_: Footer.t) = Footer.marshal buf footer in coalesce_request None (return (Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> let (_: Header.t) = Header.marshal buf header in write_sectors (Cstruct.sub buf 0 Header.sizeof) (fun () -> return(Cons(`Empty 1L, fun () -> BAT.marshal buf bat; write_sectors (Cstruct.sub buf 0 sizeof_bat) (fun () -> let (_: Footer.t) = Footer.marshal buf footer in batmap (fun () -> block 0 (fun () -> return(Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> return End)) ) ) ) )) ) ))) >>= fun elements -> let rec count totals i = if i = max_table_entries then totals else begin if not(include_block i) then count totals (i + 1) else count { totals with copy = Int64.(add totals.copy (shift_left 1L (block_size_sectors_shift + sector_shift))); metadata = Int64.(add totals.metadata (of_int sizeof_bitmap)) } (i + 1) end in let size = { empty with metadata = Int64.of_int ((2 * Footer.sizeof + Header.sizeof + sizeof_bat) / 512); empty = 512L; total = t.Vhd.footer.Footer.current_size } in let size = count size 0 in return { elements; size } let vhd ?from ?emit_batmap (t: fd Vhd.t) = vhd_common ?from ?emit_batmap t end module Hybrid_input = struct let raw ?from (raw: 'a) (vhd: fd Vhd.t) = Vhd_input.raw_common ?from ~raw vhd let vhd ?from (raw: 'a) (vhd: fd Vhd.t) = Vhd_input.vhd_common ?from ~raw vhd end module Raw_input = struct open Raw let vhd t = The physical disk layout will be : byte 0 - 511 : backup footer byte 512 - 1535 : file header ... empty sector-- this is where we 'll put the parent locator byte 2048 - ... : BAT byte 0 - 511: backup footer byte 512 - 1535: file header ... empty sector-- this is where we'll put the parent locator byte 2048 - ...: BAT *) let data_offset = 512L in let table_offset = 2048L in F.get_file_size t.filename >>= fun current_size -> let header = Header.create ~table_offset ~current_size () in let current_size = Int64.(shift_left (of_int header.Header.max_table_entries) (header.Header.block_size_sectors_shift + sector_shift)) in let footer = Footer.create ~data_offset ~current_size ~disk_type:Disk_type.Dynamic_hard_disk () in let bat_buffer = Memory.alloc (BAT.sizeof_bytes header) in let bat = BAT.of_buffer header bat_buffer in let sizeof_bat = BAT.sizeof_bytes header in let sizeof_bitmap = Header.sizeof_bitmap header in let bitmap = Memory.alloc sizeof_bitmap in for i = 0 to sizeof_bitmap - 1 do Cstruct.set_uint8 bitmap i 0xff done; let sizeof_data = 1 lsl (header.Header.block_size_sectors_shift + sector_shift) in let include_block i = let length = Int64.(shift_left 1L (sector_shift + header.Header.block_size_sectors_shift)) in let offset = Int64.(shift_left (of_int i) (sector_shift + header.Header.block_size_sectors_shift)) in F.lseek_data t.Raw.handle offset >>= fun data -> return (Int64.add offset length > data) in Calculate where the first data block will go . Note the is already rounded up to the next sector boundary . rounded up to the next sector boundary. *) let first_block = Int64.(table_offset ++ (of_int sizeof_bat)) in let next_byte = ref first_block in let blocks = header.Header.max_table_entries in let rec loop i = if i = blocks then return () else include_block i >>= function | true -> BAT.set bat i (Int64.(to_int32(!next_byte lsr sector_shift))); next_byte := Int64.(!next_byte ++ (of_int sizeof_bitmap) ++ (of_int sizeof_data)); loop (i+1) | false -> loop (i+1) in loop 0 >>= fun () -> let write_sectors buf _from andthen = return(Cons(`Sectors buf, andthen)) in let rec block i andthen = if i >= blocks then andthen () else include_block i >>= function | true -> let length = Int64.(shift_left 1L header.Header.block_size_sectors_shift) in let sector = Int64.(shift_left (of_int i) header.Header.block_size_sectors_shift) in return (Cons(`Sectors bitmap, fun () -> return (Cons(`Copy(t.Raw.handle, sector, length), fun () -> block (i+1) andthen)))) | false -> block (i + 1) andthen in assert(Footer.sizeof = 512); assert(Header.sizeof = 1024); let buf = Memory.alloc (max Footer.sizeof (max Header.sizeof sizeof_bat)) in let (_: Footer.t) = Footer.marshal buf footer in coalesce_request None (return (Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> let (_: Header.t) = Header.marshal buf header in write_sectors (Cstruct.sub buf 0 Header.sizeof) 0 (fun () -> return(Cons(`Empty 1L, fun () -> BAT.marshal buf bat; write_sectors (Cstruct.sub buf 0 sizeof_bat) 0 (fun () -> let (_: Footer.t) = Footer.marshal buf footer in block 0 (fun () -> return(Cons(`Sectors(Cstruct.sub buf 0 Footer.sizeof), fun () -> return End)) ) ) )) ) ))) >>= fun elements -> let metadata = Int64.of_int ((2 * Footer.sizeof + Header.sizeof + sizeof_bat + sizeof_bitmap * blocks)) in let size = { empty with metadata; total = current_size; copy = current_size } in return { elements; size } let raw t = F.get_file_size t.filename >>= fun bytes -> let open Int64 in let bytes = roundup_sector bytes in let size = { total = bytes; metadata = 0L; empty = 0L; copy = bytes; } in let rec copy sector_start sector_len = if sector_len = 0L then return End else let bytes_start = Int64.shift_left sector_start sector_shift in F.lseek_data t.handle bytes_start >>= fun bytes_next_data_start -> let sector_next_data_start = Int64.shift_right bytes_next_data_start sector_shift in let empty_sectors = Int64.sub sector_next_data_start sector_start in if empty_sectors > 0L then return (Cons(`Empty empty_sectors, fun () -> copy sector_next_data_start (Int64.sub sector_len empty_sectors))) else We want to copy at least one sector , so we 're not interested in holes " closer " than that . than that. *) F.lseek_hole t.handle Int64.(shift_left (succ sector_next_data_start) sector_shift) >>= fun bytes_next_hole_start -> let sector_next_hole_start = Int64.shift_right bytes_next_hole_start sector_shift in let sector_data_length = Int64.sub sector_next_hole_start sector_next_data_start in return (Cons(`Copy(t.handle, sector_next_data_start, sector_data_length), fun () -> copy sector_next_hole_start (Int64.sub sector_len sector_data_length))) in copy 0L (bytes lsr sector_shift) >>= fun elements -> return { size; elements } end end
1671aae0eb0e03198bb7f592973c4d980223d856c397e40f164a44bbed1553de
fukamachi/clozure-cl
x8632env.lisp
-*- Mode : Lisp ; Package : CCL ; -*- ;;; Copyright ( C ) 2005 - 2009 Clozure Associates This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; (in-package "CCL") (defconstant $numx8632saveregs 0) (defconstant $numx8632argregs 2) (defconstant x8632-nonvolatile-registers-mask 0) (defconstant x8632-arg-registers-mask (logior (ash 1 x8632::arg_z) (ash 1 x8632::arg_y))) (defconstant x8632-temp-registers-mask (logior (ash 1 x8632::temp0) (ash 1 x8632::temp1))) (defconstant x8632-tagged-registers-mask (logior x8632-temp-registers-mask x8632-arg-registers-mask x8632-nonvolatile-registers-mask)) (defconstant x8632-temp-node-regs (make-mask x8632::temp0 x8632::temp1 x8632::arg_y x8632::arg_z)) (defconstant x8632-nonvolatile-node-regs 0) (defconstant x8632-node-regs (logior x8632-temp-node-regs x8632-nonvolatile-node-regs)) (defconstant x8632-imm-regs (make-mask x8632::imm0)) Fine if we assume SSE support ; not so hot when using x87 (defconstant x8632-temp-fp-regs (make-mask (logand x8632::fp0 7) (logand x8632::fp1 7) (logand x8632::fp2 7) (logand x8632::fp3 7) (logand x8632::fp4 7) (logand x8632::fp5 7) (logand x8632::fp6 7) (logand x8632::fp7 7))) (defconstant x8632-cr-fields (make-mask 0)) ;;; hmm. (defconstant $undo-x86-c-frame 16) (ccl::provide "X8632ENV")
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/lib/x8632env.lisp
lisp
Package : CCL ; -*- file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at not so hot when using x87 hmm.
Copyright ( C ) 2005 - 2009 Clozure Associates This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these (in-package "CCL") (defconstant $numx8632saveregs 0) (defconstant $numx8632argregs 2) (defconstant x8632-nonvolatile-registers-mask 0) (defconstant x8632-arg-registers-mask (logior (ash 1 x8632::arg_z) (ash 1 x8632::arg_y))) (defconstant x8632-temp-registers-mask (logior (ash 1 x8632::temp0) (ash 1 x8632::temp1))) (defconstant x8632-tagged-registers-mask (logior x8632-temp-registers-mask x8632-arg-registers-mask x8632-nonvolatile-registers-mask)) (defconstant x8632-temp-node-regs (make-mask x8632::temp0 x8632::temp1 x8632::arg_y x8632::arg_z)) (defconstant x8632-nonvolatile-node-regs 0) (defconstant x8632-node-regs (logior x8632-temp-node-regs x8632-nonvolatile-node-regs)) (defconstant x8632-imm-regs (make-mask x8632::imm0)) (defconstant x8632-temp-fp-regs (make-mask (logand x8632::fp0 7) (logand x8632::fp1 7) (logand x8632::fp2 7) (logand x8632::fp3 7) (logand x8632::fp4 7) (logand x8632::fp5 7) (logand x8632::fp6 7) (logand x8632::fp7 7))) (defconstant x8632-cr-fields (make-mask 0)) (defconstant $undo-x86-c-frame 16) (ccl::provide "X8632ENV")
a9baf14ed8972f23a0f1ebc62f13cf5254e9f391afb644e60dcf5cbdbb56a2db
fulcrologic/fulcro-rad-datomic
indexed_access_common_spec.clj
(ns com.fulcrologic.rad.database-adapters.indexed-access-common-spec (:require [cljc.java-time.local-date :as ld] [cljc.java-time.local-date-time :as ldt] [clojure.test :refer [use-fixtures]] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true] [com.fulcrologic.rad.attributes :as attr :refer [defattr]] [com.fulcrologic.rad.database-adapters.datomic-options :as do] [com.fulcrologic.rad.database-adapters.indexed-access :as ia] [com.fulcrologic.rad.type-support.date-time :as dt] [fulcro-spec.core :refer [=> assertions component specification]])) (use-fixtures :once (fn [t] (dt/with-timezone "America/Los_Angeles" (t)))) (def mock-env {::attr/key->attribute {}}) (def default-coercion-acts-as-identity-function (prop/for-all [v (gen/one-of [gen/small-integer gen/boolean gen/big-ratio gen/double gen/string]) k gen/keyword] (= v (ia/default-coercion mock-env k k v)))) (specification "default-coercion" (assertions "Acts as identity for most data" (:shrunk (tc/quick-check 100 default-coercion-acts-as-identity-function)) => nil) (component "Local Date coercion" (dt/with-timezone "America/Los_Angeles" (let [dt (ld/of 2020 1 4)] (assertions "Converts to a local inst for most keys" (ia/default-coercion mock-env :x :x dt) => #inst "2020-01-04T08:00:00" "If the keyword has the name `end`, sets it to end of day" (ia/default-coercion mock-env :x/end :x dt) => #inst "2020-01-05T08:00:00")))) (component "Local Date-time coercion" (dt/with-timezone "America/Los_Angeles" (let [dt (ldt/of 2020 1 4 12 30 0)] (assertions "Converts to a local inst" (ia/default-coercion {} :x :x dt) => #inst "2020-01-04T20:30:00" (ia/default-coercion {} :x/end :x dt) => #inst "2020-01-04T20:30:00"))))) (def exclusive-end-string-gives-next-string (prop/for-all [start gen/string other gen/string] (let [next (ia/exclusive-end start)] (and (< (compare start next) 0) (or (<= (compare other start) 0) (<= (compare next other) 0)))))) (def exclusive-end-of-inst-gives-next-inst (prop/for-all [start gen/large-integer other gen/large-integer] (let [start (dt/new-date start) other (dt/new-date other) next (ia/exclusive-end start)] (and (< (compare start next) 0) (or (<= (compare other start) 0) (<= (compare next other) 0)))))) (specification "exclusive-end" (assertions (compare "" "\u0000") => -1 "returns one bigger for integers" (ia/exclusive-end 1) => 2 "returns the next string" (:shrunk (tc/quick-check 100 exclusive-end-string-gives-next-string)) => nil "returns the next Date" (:shrunk (tc/quick-check 100 exclusive-end-of-inst-gives-next-inst)) => nil)) (defattr invoice-owner+date+filters :invoice/owner+date+filters :tuple {do/attribute-schema {:db/tupleAttrs [:invoice/owner :invoice/date :invoice/number :invoice/status :invoice/customer]}}) (specification "search-parameters->range+filters" :focus (component "Ranges" (assertions "For a sequence of single-valued items that start the tuple: uses exclusive end on the final element to allocate a range" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42}) => {:range {:start [42] :end [43]} :filters {}} (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/date (ld/of 2020 1 1)}) => {:range {:start [42 #inst "2020-01-01T08:00"] :end [42 (ia/exclusive-end #inst "2020-01-01T08:00")]} :filters {}} "Extended keyword range on integers uses exclusive-end" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice.owner/start 42 :invoice.owner/end 50}) => {:range {:start [42] :end [51]} :filters {}} "Extended keyword range on local dates uses coercion, and end-of-day" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice.date/start (ld/of 2020 1 1) :invoice.date/end (ld/of 2020 1 31)}) => {:range {:start [42 #inst "2020-01-01T08"] :end [42 #inst "2020-02-01T08"]} :filters {}})) (component "Filters" (assertions "Uses explicit value when a literal" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/customer 9}) => {:range {:start [42] :end [43]} :filters {:invoice/customer 9}} "Supports coercion" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/customer (ld/of 2020 1 1)}) => {:range {:start [42] :end [43]} :filters {:invoice/customer #inst "2020-01-01T08:00"}}) (let [{:keys [filters] :as params} (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice.owner/start 42 :invoice.owner/end 43 :invoice.date/end #inst "2020-01-01" :invoice.customer/subset #{1 3 45}}) cust-filter (get filters :invoice/customer) date-filter (get filters :invoice/date)] (assertions "generates a working lambda for subsets" (fn? cust-filter) => true (cust-filter 1) => true (cust-filter 9) => false "Generates a working lambda for dates" (fn? date-filter) => true (date-filter #inst "2019-02-01") => true (date-filter #inst "2020-02-01") => false))))
null
https://raw.githubusercontent.com/fulcrologic/fulcro-rad-datomic/801f69ba370cf0c604d255139495b76373a2b497/src/test/com/fulcrologic/rad/database_adapters/indexed_access_common_spec.clj
clojure
(ns com.fulcrologic.rad.database-adapters.indexed-access-common-spec (:require [cljc.java-time.local-date :as ld] [cljc.java-time.local-date-time :as ldt] [clojure.test :refer [use-fixtures]] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true] [com.fulcrologic.rad.attributes :as attr :refer [defattr]] [com.fulcrologic.rad.database-adapters.datomic-options :as do] [com.fulcrologic.rad.database-adapters.indexed-access :as ia] [com.fulcrologic.rad.type-support.date-time :as dt] [fulcro-spec.core :refer [=> assertions component specification]])) (use-fixtures :once (fn [t] (dt/with-timezone "America/Los_Angeles" (t)))) (def mock-env {::attr/key->attribute {}}) (def default-coercion-acts-as-identity-function (prop/for-all [v (gen/one-of [gen/small-integer gen/boolean gen/big-ratio gen/double gen/string]) k gen/keyword] (= v (ia/default-coercion mock-env k k v)))) (specification "default-coercion" (assertions "Acts as identity for most data" (:shrunk (tc/quick-check 100 default-coercion-acts-as-identity-function)) => nil) (component "Local Date coercion" (dt/with-timezone "America/Los_Angeles" (let [dt (ld/of 2020 1 4)] (assertions "Converts to a local inst for most keys" (ia/default-coercion mock-env :x :x dt) => #inst "2020-01-04T08:00:00" "If the keyword has the name `end`, sets it to end of day" (ia/default-coercion mock-env :x/end :x dt) => #inst "2020-01-05T08:00:00")))) (component "Local Date-time coercion" (dt/with-timezone "America/Los_Angeles" (let [dt (ldt/of 2020 1 4 12 30 0)] (assertions "Converts to a local inst" (ia/default-coercion {} :x :x dt) => #inst "2020-01-04T20:30:00" (ia/default-coercion {} :x/end :x dt) => #inst "2020-01-04T20:30:00"))))) (def exclusive-end-string-gives-next-string (prop/for-all [start gen/string other gen/string] (let [next (ia/exclusive-end start)] (and (< (compare start next) 0) (or (<= (compare other start) 0) (<= (compare next other) 0)))))) (def exclusive-end-of-inst-gives-next-inst (prop/for-all [start gen/large-integer other gen/large-integer] (let [start (dt/new-date start) other (dt/new-date other) next (ia/exclusive-end start)] (and (< (compare start next) 0) (or (<= (compare other start) 0) (<= (compare next other) 0)))))) (specification "exclusive-end" (assertions (compare "" "\u0000") => -1 "returns one bigger for integers" (ia/exclusive-end 1) => 2 "returns the next string" (:shrunk (tc/quick-check 100 exclusive-end-string-gives-next-string)) => nil "returns the next Date" (:shrunk (tc/quick-check 100 exclusive-end-of-inst-gives-next-inst)) => nil)) (defattr invoice-owner+date+filters :invoice/owner+date+filters :tuple {do/attribute-schema {:db/tupleAttrs [:invoice/owner :invoice/date :invoice/number :invoice/status :invoice/customer]}}) (specification "search-parameters->range+filters" :focus (component "Ranges" (assertions "For a sequence of single-valued items that start the tuple: uses exclusive end on the final element to allocate a range" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42}) => {:range {:start [42] :end [43]} :filters {}} (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/date (ld/of 2020 1 1)}) => {:range {:start [42 #inst "2020-01-01T08:00"] :end [42 (ia/exclusive-end #inst "2020-01-01T08:00")]} :filters {}} "Extended keyword range on integers uses exclusive-end" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice.owner/start 42 :invoice.owner/end 50}) => {:range {:start [42] :end [51]} :filters {}} "Extended keyword range on local dates uses coercion, and end-of-day" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice.date/start (ld/of 2020 1 1) :invoice.date/end (ld/of 2020 1 31)}) => {:range {:start [42 #inst "2020-01-01T08"] :end [42 #inst "2020-02-01T08"]} :filters {}})) (component "Filters" (assertions "Uses explicit value when a literal" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/customer 9}) => {:range {:start [42] :end [43]} :filters {:invoice/customer 9}} "Supports coercion" (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice/owner 42 :invoice/customer (ld/of 2020 1 1)}) => {:range {:start [42] :end [43]} :filters {:invoice/customer #inst "2020-01-01T08:00"}}) (let [{:keys [filters] :as params} (ia/search-parameters->range+filters {} invoice-owner+date+filters {} {:invoice.owner/start 42 :invoice.owner/end 43 :invoice.date/end #inst "2020-01-01" :invoice.customer/subset #{1 3 45}}) cust-filter (get filters :invoice/customer) date-filter (get filters :invoice/date)] (assertions "generates a working lambda for subsets" (fn? cust-filter) => true (cust-filter 1) => true (cust-filter 9) => false "Generates a working lambda for dates" (fn? date-filter) => true (date-filter #inst "2019-02-01") => true (date-filter #inst "2020-02-01") => false))))
db0f4edce16eb6ffb4b45fd1b0e8a41e4f65509f1ffdd05fe9e8aba4bed4f928
Odie/gd-edit
game_dirs.clj
(ns gd-edit.game-dirs (:require [clojure.java.io :as io] [gd-edit.utils :as u] [gd-edit.globals :as globals] [gd-edit.vdf-parser :as vdf] [com.rpl.specter :as specter] [taoensso.timbre :as t] [clojure.string :as str]) (:import [com.sun.jna.platform.win32 WinReg Advapi32Util])) (declare looks-like-game-dir) (defn- parse-int "Try to parse the given string as an int. Returns Integer or nil." [s] (try (Integer/parseInt s) (catch Exception _ nil))) (defn get-steam-path "Get steam installation path" [] (u/log-exceptions-with t/debug (Advapi32Util/registryGetStringValue WinReg/HKEY_CURRENT_USER "SOFTWARE\\Valve\\Steam" "SteamPath"))) (defn get-steam-library-folders "Retrieves the library folders as defined in steamapps/libraryfolders.vdf" [] (let [lib-folder-file (io/file (get-steam-path) "steamapps/libraryfolders.vdf")] (when (.exists lib-folder-file) (as-> lib-folder-file $ (vdf/parse $) (get $ "libraryfolders") (filter #(parse-int (key %)) $) (specter/transform [specter/ALL specter/FIRST] parse-int $) ;; Sort by the directory priority (sort-by first $) ;; Grab the directories only (map second $) (map #(get % "path") $) )))) (defn- standard-game-dirs "Get the game's expected installation paths" [] (cond (u/running-osx?) [(u/expand-home "~/Dropbox/Public/GrimDawn")] (u/running-linux?) [""] :else (->> (concat [(get-steam-path)] (get-steam-library-folders)) (remove nil?) (map #(str % "\\steamapps\\common\\Grim Dawn"))))) (defn- clean-list "Removes nil from collection and return a list" [coll] (->> coll (distinct) (remove nil?) (into []))) (defn get-game-dir-search-list "Returns all possible locations where the game dir might be found. Note that this function respects the :game-dir setting in the user's settings.edn file." ([] (get-game-dir-search-list @globals/settings)) ([settings] (clean-list (into [(get settings :game-dir)] (standard-game-dirs))))) (defn get-steam-cloud-save-dirs [] (when (u/running-windows?) (let [userdata-dir (io/file (get-steam-path) "userdata")] (->> (io/file userdata-dir) (.listFiles) (filter #(.isDirectory %1)) (map #(io/file % "219990\\remote\\save\\main")) (filter #(.exists %)) (map #(.getPath %)))))) (declare get-game-dir) (defn get-local-save-dir [] (cond (u/running-osx?) (u/expand-home "~/Dropbox/Public/GrimDawn/main") (u/running-linux?) "" :else (.getPath (io/file (u/home-dir) "Documents\\My Games\\Grim Dawn\\save\\main")))) (defn get-save-dir-search-list "Returns all possible locations where the save dir might be found. Note that this function respects the :save-dir setting in the user's setting.edn file." [] (cond (u/running-osx?) (clean-list [(get @globals/settings :save-dir) (get-local-save-dir)]) :else (clean-list (concat [(get @globals/settings :save-dir) (get-local-save-dir)] (get-steam-cloud-save-dirs))))) (defn save-dir->mod-save-dir [save-dir] (let [p (u/filepath->components (str save-dir)) target-idx (.lastIndexOf p "main") p (if (not= target-idx -1) (assoc p target-idx "user") p)] (cond-> (->> p u/components->filepath io/file) (not= java.io.File (type save-dir)) (.getAbsolutePath)))) (defn get-all-save-file-dirs [] (->> (map save-dir->mod-save-dir (get-save-dir-search-list)) (concat (get-save-dir-search-list)) (map io/file) (map #(.listFiles %1)) (apply concat) (filter #(.isDirectory %1)) (filter #(.exists (io/file %1 "player.gdc"))))) ;;------------------------------------------------------------------------------ Path construction & File fetching utils ;;------------------------------------------------------------------------------ (def database-file "database/database.arz") (def templates-file "database/templates.arc") (def localization-file "resources/Text_EN.arc") (def texture-file "resources/Items.arc") (def level-file "resources/Levels.arc") (defn get-game-dir ([] (get-game-dir (get-game-dir-search-list))) ([game-dirs] (->> game-dirs (filter looks-like-game-dir) (first)))) (defn get-gdx1-dir "Returns the directory for Ashes of Malmouth dlc." [] (io/file (get-game-dir) "gdx1")) (defn get-gdx2-dir "Returns the directory for Forgotten Gods dlc." [] (io/file (get-game-dir) "gdx2")) (defn get-mod-dir "Returns the configured mod's directory" [] (:moddir @globals/settings)) (defn get-file-override-dirs "Returns a list of directories to look for game asset files in" [] [(get-game-dir) (get-gdx1-dir) (get-gdx2-dir) (get-mod-dir)]) (defn files-with-extension [directory ext] (->> (io/file directory) file-seq (filter #(and (.isFile %) (u/case-insensitive= (u/file-extension %) ext))))) (defn get-mod-db-file [mod-dir] (when mod-dir (let [components (u/path-components (str mod-dir)) mod-name (last components)] (->> (file-seq (io/file mod-dir "database")) (filter #(u/case-insensitive= (u/path-basename %) mod-name)) first)))) (defn get-db-file-overrides [] (->> (concat [(io/file (get-game-dir) database-file) (io/file (get-gdx1-dir) "database/GDX1.arz") (io/file (get-gdx2-dir) "database/GDX2.arz")] [(get-mod-db-file (get-mod-dir))]) (filter u/path-exists?) (into []))) (defn get-file-and-overrides "Given the relative path of a game asset file, return a vector of all matched files. For example, each mod is likely to have a database file and a localization file. When we're processing a the database file, then, it's not enough to just process the base game's database file, but all active mods also. This function builds such a list for callers to process." [relative-path] (if (= relative-path database-file) (get-db-file-overrides) (->> (get-file-override-dirs) (map #(io/file % relative-path)) (filter #(u/path-exists? %)) (into [])))) (defn looks-like-game-dir [path] (if (and (u/path-exists? (io/file path database-file)) (u/path-exists? (io/file path localization-file))) true false)) (defn is-cloud-save-dir? [dir] (->> (get-steam-cloud-save-dirs) (map #(.getParent (io/file %))) (some #(str/starts-with? dir %)))) (defn is-mod-save-dir? [dir] (->> (get-save-dir-search-list) (map save-dir->mod-save-dir) (some #(str/starts-with? dir %)))) (defn is-character-from-cloud-save? [character] (is-cloud-save-dir? (:meta-character-loaded-from character))) (defn is-character-from-mod-save? [character] (is-mod-save-dir? (:meta-character-loaded-from character))) (defn save-dir-type [dir] (let [cloud? (is-cloud-save-dir? dir) custom? (is-mod-save-dir? dir) builder (StringBuilder.)] (if cloud? (.append builder "cloud") (.append builder "local")) (when custom? (.append builder " custom")) (.toString builder))) ;;------------------------------------------------------------------------------ ;; Transfer stash ;;------------------------------------------------------------------------------ (defn get-transfer-stash [character] (when-not (empty? character) (let [target-file (if (:hardcore-mode character) "transfer.gsh" "transfer.gst") target-dir (cond->> ;; Grab the "top" of the save directory (->> (get-save-dir-search-list) (map #(.getParentFile (io/file %)))) ;; If a mod is active, navigate to its directory (and (is-character-from-mod-save? character) (not-empty(get-mod-dir))) (map #(io/file % (u/last-path-component (:moddir @globals/settings)))) Grab the first item that has the stash file we 're looking for :then (some #(when (or (.exists (io/file % "transfer.gst")) (.exists (io/file % "transfer.gsh"))) %)))] (io/file target-dir target-file))))
null
https://raw.githubusercontent.com/Odie/gd-edit/d1ac46fd6eb89c9571199641d9cc2f95e68d139b/src/gd_edit/game_dirs.clj
clojure
Sort by the directory priority Grab the directories only ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Transfer stash ------------------------------------------------------------------------------ Grab the "top" of the save directory If a mod is active, navigate to its directory
(ns gd-edit.game-dirs (:require [clojure.java.io :as io] [gd-edit.utils :as u] [gd-edit.globals :as globals] [gd-edit.vdf-parser :as vdf] [com.rpl.specter :as specter] [taoensso.timbre :as t] [clojure.string :as str]) (:import [com.sun.jna.platform.win32 WinReg Advapi32Util])) (declare looks-like-game-dir) (defn- parse-int "Try to parse the given string as an int. Returns Integer or nil." [s] (try (Integer/parseInt s) (catch Exception _ nil))) (defn get-steam-path "Get steam installation path" [] (u/log-exceptions-with t/debug (Advapi32Util/registryGetStringValue WinReg/HKEY_CURRENT_USER "SOFTWARE\\Valve\\Steam" "SteamPath"))) (defn get-steam-library-folders "Retrieves the library folders as defined in steamapps/libraryfolders.vdf" [] (let [lib-folder-file (io/file (get-steam-path) "steamapps/libraryfolders.vdf")] (when (.exists lib-folder-file) (as-> lib-folder-file $ (vdf/parse $) (get $ "libraryfolders") (filter #(parse-int (key %)) $) (specter/transform [specter/ALL specter/FIRST] parse-int $) (sort-by first $) (map second $) (map #(get % "path") $) )))) (defn- standard-game-dirs "Get the game's expected installation paths" [] (cond (u/running-osx?) [(u/expand-home "~/Dropbox/Public/GrimDawn")] (u/running-linux?) [""] :else (->> (concat [(get-steam-path)] (get-steam-library-folders)) (remove nil?) (map #(str % "\\steamapps\\common\\Grim Dawn"))))) (defn- clean-list "Removes nil from collection and return a list" [coll] (->> coll (distinct) (remove nil?) (into []))) (defn get-game-dir-search-list "Returns all possible locations where the game dir might be found. Note that this function respects the :game-dir setting in the user's settings.edn file." ([] (get-game-dir-search-list @globals/settings)) ([settings] (clean-list (into [(get settings :game-dir)] (standard-game-dirs))))) (defn get-steam-cloud-save-dirs [] (when (u/running-windows?) (let [userdata-dir (io/file (get-steam-path) "userdata")] (->> (io/file userdata-dir) (.listFiles) (filter #(.isDirectory %1)) (map #(io/file % "219990\\remote\\save\\main")) (filter #(.exists %)) (map #(.getPath %)))))) (declare get-game-dir) (defn get-local-save-dir [] (cond (u/running-osx?) (u/expand-home "~/Dropbox/Public/GrimDawn/main") (u/running-linux?) "" :else (.getPath (io/file (u/home-dir) "Documents\\My Games\\Grim Dawn\\save\\main")))) (defn get-save-dir-search-list "Returns all possible locations where the save dir might be found. Note that this function respects the :save-dir setting in the user's setting.edn file." [] (cond (u/running-osx?) (clean-list [(get @globals/settings :save-dir) (get-local-save-dir)]) :else (clean-list (concat [(get @globals/settings :save-dir) (get-local-save-dir)] (get-steam-cloud-save-dirs))))) (defn save-dir->mod-save-dir [save-dir] (let [p (u/filepath->components (str save-dir)) target-idx (.lastIndexOf p "main") p (if (not= target-idx -1) (assoc p target-idx "user") p)] (cond-> (->> p u/components->filepath io/file) (not= java.io.File (type save-dir)) (.getAbsolutePath)))) (defn get-all-save-file-dirs [] (->> (map save-dir->mod-save-dir (get-save-dir-search-list)) (concat (get-save-dir-search-list)) (map io/file) (map #(.listFiles %1)) (apply concat) (filter #(.isDirectory %1)) (filter #(.exists (io/file %1 "player.gdc"))))) Path construction & File fetching utils (def database-file "database/database.arz") (def templates-file "database/templates.arc") (def localization-file "resources/Text_EN.arc") (def texture-file "resources/Items.arc") (def level-file "resources/Levels.arc") (defn get-game-dir ([] (get-game-dir (get-game-dir-search-list))) ([game-dirs] (->> game-dirs (filter looks-like-game-dir) (first)))) (defn get-gdx1-dir "Returns the directory for Ashes of Malmouth dlc." [] (io/file (get-game-dir) "gdx1")) (defn get-gdx2-dir "Returns the directory for Forgotten Gods dlc." [] (io/file (get-game-dir) "gdx2")) (defn get-mod-dir "Returns the configured mod's directory" [] (:moddir @globals/settings)) (defn get-file-override-dirs "Returns a list of directories to look for game asset files in" [] [(get-game-dir) (get-gdx1-dir) (get-gdx2-dir) (get-mod-dir)]) (defn files-with-extension [directory ext] (->> (io/file directory) file-seq (filter #(and (.isFile %) (u/case-insensitive= (u/file-extension %) ext))))) (defn get-mod-db-file [mod-dir] (when mod-dir (let [components (u/path-components (str mod-dir)) mod-name (last components)] (->> (file-seq (io/file mod-dir "database")) (filter #(u/case-insensitive= (u/path-basename %) mod-name)) first)))) (defn get-db-file-overrides [] (->> (concat [(io/file (get-game-dir) database-file) (io/file (get-gdx1-dir) "database/GDX1.arz") (io/file (get-gdx2-dir) "database/GDX2.arz")] [(get-mod-db-file (get-mod-dir))]) (filter u/path-exists?) (into []))) (defn get-file-and-overrides "Given the relative path of a game asset file, return a vector of all matched files. For example, each mod is likely to have a database file and a localization file. When we're processing a the database file, then, it's not enough to just process the base game's database file, but all active mods also. This function builds such a list for callers to process." [relative-path] (if (= relative-path database-file) (get-db-file-overrides) (->> (get-file-override-dirs) (map #(io/file % relative-path)) (filter #(u/path-exists? %)) (into [])))) (defn looks-like-game-dir [path] (if (and (u/path-exists? (io/file path database-file)) (u/path-exists? (io/file path localization-file))) true false)) (defn is-cloud-save-dir? [dir] (->> (get-steam-cloud-save-dirs) (map #(.getParent (io/file %))) (some #(str/starts-with? dir %)))) (defn is-mod-save-dir? [dir] (->> (get-save-dir-search-list) (map save-dir->mod-save-dir) (some #(str/starts-with? dir %)))) (defn is-character-from-cloud-save? [character] (is-cloud-save-dir? (:meta-character-loaded-from character))) (defn is-character-from-mod-save? [character] (is-mod-save-dir? (:meta-character-loaded-from character))) (defn save-dir-type [dir] (let [cloud? (is-cloud-save-dir? dir) custom? (is-mod-save-dir? dir) builder (StringBuilder.)] (if cloud? (.append builder "cloud") (.append builder "local")) (when custom? (.append builder " custom")) (.toString builder))) (defn get-transfer-stash [character] (when-not (empty? character) (let [target-file (if (:hardcore-mode character) "transfer.gsh" "transfer.gst") target-dir (cond->> (->> (get-save-dir-search-list) (map #(.getParentFile (io/file %)))) (and (is-character-from-mod-save? character) (not-empty(get-mod-dir))) (map #(io/file % (u/last-path-component (:moddir @globals/settings)))) Grab the first item that has the stash file we 're looking for :then (some #(when (or (.exists (io/file % "transfer.gst")) (.exists (io/file % "transfer.gsh"))) %)))] (io/file target-dir target-file))))
74dda3fe79778c608e3661bd00e83806d7f30a6761d7902da980ca1ca76f2c37
pebrc/ninety-nine-clojure
logic_test.clj
(ns ninety-nine-clojure.logic-test (:require [clojure.test :refer :all] [ninety-nine-clojure.logic :refer :all])) (deftest infix-and (is true (infix true and true))) (deftest infix-nested (is true (infix true and (false or true) ))) (deftest infix-double-operator (is true (infix true and not false))) (deftest infix-nested-first (is true (infix (false or true) and true))) (deftest infix-one-unary (is true (infix (not false and true)))) (deftest infix-with-unary-last (is true (infix (false or not false)))) (deftest infix-with-two-unary-ops (is true (infix (not false and not false)))) (deftest gray-1 (is (= ["0" "1"]( gray 1)))) (deftest gray-2 (is (= ["00" "01" "11" "10"] (gray 2)))) (deftest gray-3 (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray* 3)))) (deftest gray-3-memoized (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray 3)))) (deftest gray-bitwise-1 (is (= ["0" "1"]( gray-seq-bitwise 1)))) (deftest gray-bitwise-2 (is (= ["00" "01" "11" "10"] (gray-seq-bitwise 2)))) (deftest gray-bitwise-3 (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray-seq-bitwise 3)))) (deftest huffmann-acceptance (is (= '([a "0"] [c "100"] [b "101"] [f "1100"] [e "1101"] [d "111"]) (-> '([a 45] [b 13] [c 12] [d 16] [e 9] [f 5]) build-huffman-tree map-symbols )))) (deftest huffmann-empties-both-queues (is (= '([\a "00"] [\space "01"] [\b "10"] [\c "11"]) (-> (frequencies "a bc") build-huffman-tree map-symbols)))) (defn normalize-to-length [encoded] (-> (map (fn [[v code]] [v (count code)]) encoded) sort)) ;;; I assume subtle differences during tree building are OK as long as ;;; the resulting code lengths for each value are identical ;;; Therefore I am comparing code lengths by normalizing the expected ;;; results and the actual results to a sorted sequence of tuples of ;;; value and code length (deftest huffman-wikipedia-example (is (= (-> '([\space "111"] [\a "010"] [\e "000"] [\f "1101"] [\h "1010"] [\i "1000"] [\m "0111"] [\n "0010"] [\s "1011"] [\t "0110"] [\l "11001"] [\o "00110"] [\p "10011"] [\r "11000"] [\u "00111"] [\x "10010"]) normalize-to-length) (-> (frequencies "this is an example of a huffman tree") build-huffman-tree map-symbols normalize-to-length)))) (deftest huffman-rosetta-example (is (= (-> '([\n "000"] [\s "0010"] [\m "0011"] [\o "0100"] [\t "01010"] [\x "01011"] [\p "01100"] [\l "01101"] [\r "01110"] [\u "01111"] [\c "10000"] [\d "10001"] [\i "1001"] [\space "101"] [\a "1100"] [\e "1101"] [\f "1110"] [\g "11110"] [\h "11111"]) normalize-to-length) (-> (frequencies "this is an example for huffman encoding") build-huffman-tree map-symbols normalize-to-length))))
null
https://raw.githubusercontent.com/pebrc/ninety-nine-clojure/4aec31b42bd47509c3ef3d1b874eb1f5c1172f54/test/ninety_nine_clojure/logic_test.clj
clojure
I assume subtle differences during tree building are OK as long as the resulting code lengths for each value are identical Therefore I am comparing code lengths by normalizing the expected results and the actual results to a sorted sequence of tuples of value and code length
(ns ninety-nine-clojure.logic-test (:require [clojure.test :refer :all] [ninety-nine-clojure.logic :refer :all])) (deftest infix-and (is true (infix true and true))) (deftest infix-nested (is true (infix true and (false or true) ))) (deftest infix-double-operator (is true (infix true and not false))) (deftest infix-nested-first (is true (infix (false or true) and true))) (deftest infix-one-unary (is true (infix (not false and true)))) (deftest infix-with-unary-last (is true (infix (false or not false)))) (deftest infix-with-two-unary-ops (is true (infix (not false and not false)))) (deftest gray-1 (is (= ["0" "1"]( gray 1)))) (deftest gray-2 (is (= ["00" "01" "11" "10"] (gray 2)))) (deftest gray-3 (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray* 3)))) (deftest gray-3-memoized (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray 3)))) (deftest gray-bitwise-1 (is (= ["0" "1"]( gray-seq-bitwise 1)))) (deftest gray-bitwise-2 (is (= ["00" "01" "11" "10"] (gray-seq-bitwise 2)))) (deftest gray-bitwise-3 (is (= ["000" "001" "011" "010" "110" "111" "101" "100"] (gray-seq-bitwise 3)))) (deftest huffmann-acceptance (is (= '([a "0"] [c "100"] [b "101"] [f "1100"] [e "1101"] [d "111"]) (-> '([a 45] [b 13] [c 12] [d 16] [e 9] [f 5]) build-huffman-tree map-symbols )))) (deftest huffmann-empties-both-queues (is (= '([\a "00"] [\space "01"] [\b "10"] [\c "11"]) (-> (frequencies "a bc") build-huffman-tree map-symbols)))) (defn normalize-to-length [encoded] (-> (map (fn [[v code]] [v (count code)]) encoded) sort)) (deftest huffman-wikipedia-example (is (= (-> '([\space "111"] [\a "010"] [\e "000"] [\f "1101"] [\h "1010"] [\i "1000"] [\m "0111"] [\n "0010"] [\s "1011"] [\t "0110"] [\l "11001"] [\o "00110"] [\p "10011"] [\r "11000"] [\u "00111"] [\x "10010"]) normalize-to-length) (-> (frequencies "this is an example of a huffman tree") build-huffman-tree map-symbols normalize-to-length)))) (deftest huffman-rosetta-example (is (= (-> '([\n "000"] [\s "0010"] [\m "0011"] [\o "0100"] [\t "01010"] [\x "01011"] [\p "01100"] [\l "01101"] [\r "01110"] [\u "01111"] [\c "10000"] [\d "10001"] [\i "1001"] [\space "101"] [\a "1100"] [\e "1101"] [\f "1110"] [\g "11110"] [\h "11111"]) normalize-to-length) (-> (frequencies "this is an example for huffman encoding") build-huffman-tree map-symbols normalize-to-length))))
f4ea4cdfd79c9d80cb3fada9d6b1e6315aa9ab3ea22efdcb6b5c00c993818f31
jeffshrager/biobike
javascript.lisp
;; Copyright ( c ) 2005 , Gigamonkeys Consulting All rights reserved . ;; (in-package :com.gigamonkeys.foo.javascript) (defclass javascript (language) () (:default-initargs :special-operator-symbol 'javascript-special-operator :macro-symbol 'javascript-macro :input-readtable (let ((readtable (copy-readtable))) (setf (readtable-case readtable) :preserve) readtable) :input-package (find-package :com.gigamonkeys.foo.javascript) :output-file-type "js")) (defun new-env (key value env) (acons key value env)) (defun statement-or-expression (env) (cdr (assoc 'statement-or-expression env))) (defparameter *javascript* (make-instance 'javascript)) (defvar *javascript-gensym-counter* 0) (defun javascript-gensym (&optional (prefix "g$")) (make-symbol (format nil "~a~d" prefix (incf *javascript-gensym-counter*)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; File compiler implementation (defmethod comment ((language javascript) text) (format nil "// ~a" text)) (defmethod top-level-environment ((language javascript)) '((statement-or-expression . :statement))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Language implementation (defmethod special-operator-symbol ((language javascript)) 'javascript-special-operator) (defmethod macro-symbol ((language javascript)) 'javascript-macro) (defmethod process-sexp ((language javascript) processor form environment) (if (consp form) (destructuring-bind (name &rest arguments) form (if (method-name name) (process-method-call language processor environment (method-name name) (first arguments) (rest arguments)) (process-function-call language processor environment name arguments))) (process-javascript-scalar processor form)) (maybe-semicolon processor environment)) (defun method-name (name) (cond ((and (consp name) (eql (first name) 'method)) (second name)) ((and (symbolp name) (char= (char (string name) 0) #\.)) (intern (subseq (string name) 1) (symbol-package name))) (t nil))) (defun process-method-call (language processor environment method-name object arguments) (process language processor object (new-env 'statement-or-expression :expression environment)) (raw-string processor ".") (process language processor method-name (new-env 'statement-or-expression :expression environment)) (raw-string processor "(") (loop for (arg . rest) on arguments do (process language processor arg (new-env 'statement-or-expression :expression environment)) when rest do (raw-string processor ", ")) (raw-string processor ")")) (defun process-function-call (language processor environment name arguments) (let ((function-expression-statement-p (and (consp name) (eql (car name) 'function) (eql (statement-or-expression environment) :statement)))) (when function-expression-statement-p (raw-string processor "(")) (process language processor name (new-env 'statement-or-expression :expression environment)) (when function-expression-statement-p (raw-string processor ")")) (raw-string processor "(") (loop for (arg . rest) on arguments do (process language processor arg (new-env 'statement-or-expression :expression environment)) when rest do (raw-string processor ", ")) (raw-string processor ")"))) (defun process-javascript-scalar (processor value) ;; This is where better smarts about translating Lisp values to Javascript syntax goes . ( E.g. ( foo x 123.4d0 ) does n't work because this function will generate 123.4d0 in the Javascript ;; output. (etypecase value (string (raw-string processor (format nil "~s" value))) (symbol (raw-string processor (format nil "~a" (dash-to-intercap value)))) (number (raw-string processor (format nil "~a" value))) (character (raw-string processor (javascript-character-text value))))) (defun javascript-character-text (char) (case char (#\Tab "'\\t'") (#\Newline "'\\n'") (#\Return "'\\r'") (#\Backspace "'\\b'") (#\vt "'\\v'") (#\Page "'\\f'") (#\Null "'\\0'") (t (format nil "'~a'" char)))) (defun dash-to-intercap (symbol) (with-output-to-string (s) (loop with up = nil for char across (symbol-name symbol) when (char= char #\-) do (setf up t) else do (write-char (if up (char-upcase char) char) s) (setf up nil)))) (defmethod process-special-form :after ((language javascript) processor form environment) (when (eql (special-op-type (car form)) :expression) ;; The special form is naturally an expression but if it is being ;; proceessed as a statement then we need to tack on a ;; semicolon. If it's already a statement then it will have taken ;; care of emitting any necessary semicolon. (maybe-semicolon processor environment))) (defun maybe-semicolon (processor environment) (ecase (statement-or-expression environment) (:statement (raw-string processor ";")) (:expression))) (defmacro define-javascript-macro (name (&rest parameters) &body body) `(define-macro ,name javascript-macro (,@parameters) ,@body)) (defmacro define-javascript-special-operator (name statement-or-expression (processor &rest parameters) &body body) "Special ops that are always statements are responsible for outputting their own semicolon if necessary. This allows statements such as blocks to *not* emit a semicolon." (multiple-value-bind (parameters env) (parse-&environment parameters) `(eval-when (:compile-toplevel :load-toplevel :execute) (remprop ',name 'javascript-special-operator) (remprop ',name 'javascript-special-operator-type) (define-special-operator ,name javascript-special-operator (,processor ,@parameters &environment ,env) (macrolet ((out (&rest stuff) `(progn ,@(compile-special-op-body ',processor stuff))) (emit (thing) `(raw-string ,',processor ,thing))) (flet ((statement (thing) (process *javascript* ,processor thing (new-env 'statement-or-expression :statement ,env))) (expression (thing) (process *javascript* ,processor thing (new-env 'statement-or-expression :expression ,env))) (name (thing) (raw-string ,processor (dash-to-intercap thing)))) #-lispworks (declare (ignorable (function statement) (function expression) (function name))) (out ,@body)))) (setf (get ',name 'javascript-special-operator-type) ,statement-or-expression)))) (defun special-op-type (name) (get name 'javascript-special-operator-type)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Operators -- special operators that produce expressions . (macrolet ((define-unary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor expr) ,(format nil "~(~a~)(" op) (expression expr) ")"))))) (define-unary-ops delete void typeof ~ !)) (macrolet ((define-binary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor &rest expressions) "(" (loop for (e . rest) on expressions do (expression e) when rest do (out ,(format nil " ~(~a~) " op))) ")"))))) ;; In theory, we could keep track of precedence levels and avoid ;; over parenthesizing in the generated code. Though it's not clear ;; that's actually worth it or even a good idea. (define-binary-ops * / %) (define-binary-ops + -) ;;(define-binary-ops << >> >>>) ;;(define-binary-ops < > <= >= instanceof in) (define-binary-ops instanceof in) ;;(define-binary-ops == != === !===) (define-binary-ops &) (define-binary-ops ^) (define-binary-ops \|) ;; hmmm. This may not be the best name. Unless we put the reader into a special mode. (define-binary-ops &&) (define-binary-ops \|\|)) (macrolet ((define-true-binary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor e1 e2) "(" (expression e1) (out ,(format nil " ~(~a~) " op)) (expression e2) ")"))))) (define-true-binary-ops << >> >>>) (define-true-binary-ops < > <= >= instanceof in) (define-true-binary-ops == != === !===)) (macrolet ((define-assignment-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor lvalue rvalue &environment env) (process *javascript* processor lvalue (new-env 'statement-or-expression :expression env)) (raw-string processor ,(format nil " ~a " (symbol-name op))) (process *javascript* processor rvalue (new-env 'statement-or-expression :expression env))))))) (define-assignment-ops = *= /= %= += -= <<= >>= >>>= &= ^= \|=)) (define-javascript-special-operator comment :statement (processor &rest lines) :freshline (dolist (line lines) (out "// " (emit line) :newline))) (define-javascript-special-operator array :expression (processor &rest elements) "[" (loop for (e . rest) on elements do (expression e) when rest do (out ", ")) "]") (define-javascript-special-operator object :expression (processor &rest elements) "{ " (loop for (key value . rest) on elements by #'cddr do (out "\"" (name key) "\" : " (expression value)) when rest do (out ", ")) " }") (define-javascript-special-operator @ :expression (processor expr &rest slots) (expression expr) (loop for slot in slots do (if (symbolp slot) (out "." (name slot)) (out "[" (expression slot) "]")))) (define-javascript-special-operator ref :expression (processor expr &rest slots) (expression expr) (loop for slot in slots do (out "[" (expression slot) "]"))) (define-javascript-special-operator new :expression (processor expr &rest args) "new " (expression expr) (out "(" (loop for (e . rest) on args do (expression e) when rest do (out ", ")) ")")) (define-javascript-special-operator ++ :expression (processor lvalue &optional post) (if (eql post :post) (out (expression lvalue) "++") (out "++" (expression lvalue)))) (define-javascript-special-operator -- :expression (processor lvalue &optional post) (if (eql post :post) (out (expression lvalue) "--") (out "--" (expression lvalue)))) (define-javascript-special-operator ? :expression (processor condition then &optional (else 'null) &environment env) (process *javascript* processor condition (new-env 'statement-or-expression :expression env)) (raw-string processor " ? ") (process *javascript* processor then (new-env 'statement-or-expression :expression env)) (raw-string processor " : ") (process *javascript* processor else (new-env 'statement-or-expression :expression env))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Statements -- special operators that produce statements (define-javascript-special-operator progn :expression (processor &rest body) "(" (loop for (e . rest) on body do (out (expression e)) (when rest (out ", "))) ")") (define-javascript-special-operator prog :statement (processor &rest body) (loop for s in body do (out (statement s) :freshline))) ;; Block -- we handle this a bit specially to avoid creating redundant ;; blocks in the generated code. In the case where a block contains ;; only another block (or a macro that expands into a block) we strip ;; the inner block. (define-javascript-special-operator block :statement (processor &rest body &environment env) (when (and body (not (cdr body))) (loop while (macro-form-p *javascript* (car body)) do (setf (car body) (expand-macro-form *javascript* (car body) env))) (loop while (and body (not (cdr body)) (consp (car body)) (eql (caar body) 'block)) do (setf body (rest (car body))))) (out "{" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent "}")) Var -- can only define one variable at a time . (define-javascript-special-operator var :statement (processor variable &optional value) :freshline "var " (name variable) (when value (out " = " (expression value))) ";") ;; If (define-javascript-special-operator if :statement (processor condition then &optional else) "if (" (expression condition) ") " (statement then) (when else (out " else " (statement else)))) ;; Do-While (define-javascript-special-operator do-while :statement (processor body condition) "do " (statement body) " while (" (expression condition) ");") ;; While (define-javascript-special-operator while :statement (processor condition body) "while (" (expression condition) ") " (statement body)) ;; For (define-javascript-special-operator for :statement (processor var-test-step statement) (destructuring-bind (var test &optional step) var-test-step (let* ((var-p (and (consp var) (eql (first var) 'var))) (initialised (and (consp var) (if var-p (third var) (second var))))) (if var-p (setf var (second var))) (if (eql test 'in) (out "for (" (if var-p (out "var ")) (expression var) " in " (expression step) ") " (statement statement)) (out "for (" (if var-p (out "var ")) (if initialised (statement `(= ,var ,initialised)) (statement var)) " " (statement test) " " (expression step) ") " (statement statement)))))) ;; Continue (define-javascript-special-operator continue :statement (processor &optional id) "continue" (when id (out " " (name id))) ";") Break (define-javascript-special-operator break :statement (processor &optional id) "break" (when id (out " " (name id))) ";") ;; Return #+(or)(define-javascript-special-operator return :statement (processor &optional expr) "return" (when expr (out " " (expression expr))) ";") (define-javascript-special-operator return :statement (processor &optional expr &environment env) (loop while (macro-form-p *javascript* expr) do (setf expr (expand-macro-form *javascript* expr env))) (cond ((and (consp expr) (consp (car expr))) (loop while (macro-form-p *javascript* (car expr)) do (setf expr (cons (expand-macro-form *javascript* (car expr) env) (cdr expr)))) (if (redundant-function-p expr) (loop for form in (cddar expr) do (out (statement form) :freshline)) (out "return " (expression expr) ";"))) ((redundant-apply-p expr) (destructuring-bind (name (function empty &rest body) this &optional args) expr (declare (ignore name this args function empty)) (loop for form in body do (out (statement form) :freshline)))) ((redundant-call-p expr) (destructuring-bind (name (function empty &rest body) this &rest args) expr (declare (ignore name this args function empty)) (loop for form in body do (out (statement form) :freshline)))) (t (out "return" (when expr (out " " (expression expr))) ";")))) Is this needed anymore ? wo n't work for Lispscript since we generate calls to apply . On the other hand , Lispscript has its ;;; own way of avoiding generating redundant scopes. Maybe. (defun redundant-function-p (expr) (and (consp expr) (consp (car expr)) (eql (caar expr) 'function) (eql (cadar expr) '()))) Bit of a hack to help out Lispscript generation . (defun redundant-apply-p (expr) (and (consp expr) (eql (car expr) 'com.gigamonkeys.foo.lispscript::|.apply|) (destructuring-bind (name function this &optional args) expr (declare (ignore name function)) (and (eql this 'com.gigamonkeys.foo.lispscript::|this|) (equal args '(array)))))) (defun redundant-call-p (expr) (and (consp expr) (eql (car expr) 'com.gigamonkeys.foo.lispscript::|.call|) (destructuring-bind (name function this &rest args) expr (declare (ignore name function)) (and (eql this 'com.gigamonkeys.foo.lispscript::|this|) (null args))))) ;; With (define-javascript-special-operator with :statement (processor expr stmt) "with (" (expression expr) ") " (statement stmt)) Switch (define-javascript-special-operator switch :statement (processor expr &rest clauses) "switch (" (expression expr) ") {" :newline :indent (loop for (e . statements) in clauses do (if (eql e :default) (out "default:" :newline :indent) (out "case " (expression e) ":" :newline :indent)) (loop for s in statements do (statement s) (out :freshline)) (out :freshline :unindent)) :freshline :unindent "}") ;; Labeled statement (define-javascript-special-operator label :statement (processor label statement) (name label) ": " (statement statement)) ;; Throw (define-javascript-special-operator throw :statement (processor expr) "throw " (expression expr) ";") ;; Try (define-javascript-special-operator try :statement (processor &rest body) (flet ((key (e) (if (consp e) (first e)))) (let ((catch-clause (find 'catch body :key #'key)) (finally-clause (find 'finally body :key #'key))) (when catch-clause (assert (let ((next (cdr (member catch-clause body)))) (or (null next) (eql (car next) finally-clause))))) (when finally-clause (assert (null (cdr (member finally-clause body))))) (setf body (ldiff body (or (member catch-clause body) (member finally-clause body)))) (out "try {" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent :freshline "}" (when catch-clause (destructuring-bind (var &rest body) (rest catch-clause) (out " catch (" (name var) ") {" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent :freshline "}"))) (when finally-clause (out " finally {" :newline :indent (loop for stmt in (rest finally-clause) do (out (statement stmt) :freshline)) :unindent :freshline "}")))))) Function -- two kinds , named and anonymous . The former is a ;; statement; the latter an expression. (define-javascript-special-operator function :statement (processor &rest body &environment env) (flet ((params (params) (out "(" (loop for (p . rest) on params do (out (name p)) (when rest (out ", "))) ")")) (body (body) (process *javascript* processor `(block ,@body) (new-env 'statement-or-expression :statement env)))) (if (and (symbolp (first body)) (not (null (first body)))) (destructuring-bind (name (&rest params) &rest body) body (out "function " (name name) " " (params params) " " (body body))) (destructuring-bind ((&rest params) &rest body) body (when (eql (statement-or-expression env) :expression) (raw-string processor "(")) (out "function " (params params) " " (body body)) (when (eql (statement-or-expression env) :expression) (raw-string processor ")")))))) (define-javascript-special-operator augment-environment :statement (processor (&rest pairs) &body body &environment env) (let ((env (append pairs env))) (loop for form in body do (process *javascript* processor form env))))
null
https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/ThirdParty/monkeylib/foo/javascript.lisp
lisp
File compiler implementation Language implementation This is where better smarts about translating Lisp values to output. The special form is naturally an expression but if it is being proceessed as a statement then we need to tack on a semicolon. If it's already a statement then it will have taken care of emitting any necessary semicolon. In theory, we could keep track of precedence levels and avoid over parenthesizing in the generated code. Though it's not clear that's actually worth it or even a good idea. (define-binary-ops << >> >>>) (define-binary-ops < > <= >= instanceof in) (define-binary-ops == != === !===) hmmm. This may not be the best name. Unless we put the reader into a special mode. Statements -- special operators that produce statements Block -- we handle this a bit specially to avoid creating redundant blocks in the generated code. In the case where a block contains only another block (or a macro that expands into a block) we strip the inner block. If Do-While While For Continue Return own way of avoiding generating redundant scopes. Maybe. With Labeled statement Throw Try statement; the latter an expression.
Copyright ( c ) 2005 , Gigamonkeys Consulting All rights reserved . (in-package :com.gigamonkeys.foo.javascript) (defclass javascript (language) () (:default-initargs :special-operator-symbol 'javascript-special-operator :macro-symbol 'javascript-macro :input-readtable (let ((readtable (copy-readtable))) (setf (readtable-case readtable) :preserve) readtable) :input-package (find-package :com.gigamonkeys.foo.javascript) :output-file-type "js")) (defun new-env (key value env) (acons key value env)) (defun statement-or-expression (env) (cdr (assoc 'statement-or-expression env))) (defparameter *javascript* (make-instance 'javascript)) (defvar *javascript-gensym-counter* 0) (defun javascript-gensym (&optional (prefix "g$")) (make-symbol (format nil "~a~d" prefix (incf *javascript-gensym-counter*)))) (defmethod comment ((language javascript) text) (format nil "// ~a" text)) (defmethod top-level-environment ((language javascript)) '((statement-or-expression . :statement))) (defmethod special-operator-symbol ((language javascript)) 'javascript-special-operator) (defmethod macro-symbol ((language javascript)) 'javascript-macro) (defmethod process-sexp ((language javascript) processor form environment) (if (consp form) (destructuring-bind (name &rest arguments) form (if (method-name name) (process-method-call language processor environment (method-name name) (first arguments) (rest arguments)) (process-function-call language processor environment name arguments))) (process-javascript-scalar processor form)) (maybe-semicolon processor environment)) (defun method-name (name) (cond ((and (consp name) (eql (first name) 'method)) (second name)) ((and (symbolp name) (char= (char (string name) 0) #\.)) (intern (subseq (string name) 1) (symbol-package name))) (t nil))) (defun process-method-call (language processor environment method-name object arguments) (process language processor object (new-env 'statement-or-expression :expression environment)) (raw-string processor ".") (process language processor method-name (new-env 'statement-or-expression :expression environment)) (raw-string processor "(") (loop for (arg . rest) on arguments do (process language processor arg (new-env 'statement-or-expression :expression environment)) when rest do (raw-string processor ", ")) (raw-string processor ")")) (defun process-function-call (language processor environment name arguments) (let ((function-expression-statement-p (and (consp name) (eql (car name) 'function) (eql (statement-or-expression environment) :statement)))) (when function-expression-statement-p (raw-string processor "(")) (process language processor name (new-env 'statement-or-expression :expression environment)) (when function-expression-statement-p (raw-string processor ")")) (raw-string processor "(") (loop for (arg . rest) on arguments do (process language processor arg (new-env 'statement-or-expression :expression environment)) when rest do (raw-string processor ", ")) (raw-string processor ")"))) (defun process-javascript-scalar (processor value) Javascript syntax goes . ( E.g. ( foo x 123.4d0 ) does n't work because this function will generate 123.4d0 in the Javascript (etypecase value (string (raw-string processor (format nil "~s" value))) (symbol (raw-string processor (format nil "~a" (dash-to-intercap value)))) (number (raw-string processor (format nil "~a" value))) (character (raw-string processor (javascript-character-text value))))) (defun javascript-character-text (char) (case char (#\Tab "'\\t'") (#\Newline "'\\n'") (#\Return "'\\r'") (#\Backspace "'\\b'") (#\vt "'\\v'") (#\Page "'\\f'") (#\Null "'\\0'") (t (format nil "'~a'" char)))) (defun dash-to-intercap (symbol) (with-output-to-string (s) (loop with up = nil for char across (symbol-name symbol) when (char= char #\-) do (setf up t) else do (write-char (if up (char-upcase char) char) s) (setf up nil)))) (defmethod process-special-form :after ((language javascript) processor form environment) (when (eql (special-op-type (car form)) :expression) (maybe-semicolon processor environment))) (defun maybe-semicolon (processor environment) (ecase (statement-or-expression environment) (:statement (raw-string processor ";")) (:expression))) (defmacro define-javascript-macro (name (&rest parameters) &body body) `(define-macro ,name javascript-macro (,@parameters) ,@body)) (defmacro define-javascript-special-operator (name statement-or-expression (processor &rest parameters) &body body) "Special ops that are always statements are responsible for outputting their own semicolon if necessary. This allows statements such as blocks to *not* emit a semicolon." (multiple-value-bind (parameters env) (parse-&environment parameters) `(eval-when (:compile-toplevel :load-toplevel :execute) (remprop ',name 'javascript-special-operator) (remprop ',name 'javascript-special-operator-type) (define-special-operator ,name javascript-special-operator (,processor ,@parameters &environment ,env) (macrolet ((out (&rest stuff) `(progn ,@(compile-special-op-body ',processor stuff))) (emit (thing) `(raw-string ,',processor ,thing))) (flet ((statement (thing) (process *javascript* ,processor thing (new-env 'statement-or-expression :statement ,env))) (expression (thing) (process *javascript* ,processor thing (new-env 'statement-or-expression :expression ,env))) (name (thing) (raw-string ,processor (dash-to-intercap thing)))) #-lispworks (declare (ignorable (function statement) (function expression) (function name))) (out ,@body)))) (setf (get ',name 'javascript-special-operator-type) ,statement-or-expression)))) (defun special-op-type (name) (get name 'javascript-special-operator-type)) Operators -- special operators that produce expressions . (macrolet ((define-unary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor expr) ,(format nil "~(~a~)(" op) (expression expr) ")"))))) (define-unary-ops delete void typeof ~ !)) (macrolet ((define-binary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor &rest expressions) "(" (loop for (e . rest) on expressions do (expression e) when rest do (out ,(format nil " ~(~a~) " op))) ")"))))) (define-binary-ops * / %) (define-binary-ops + -) (define-binary-ops instanceof in) (define-binary-ops &) (define-binary-ops ^) (define-binary-ops &&) (define-binary-ops \|\|)) (macrolet ((define-true-binary-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor e1 e2) "(" (expression e1) (out ,(format nil " ~(~a~) " op)) (expression e2) ")"))))) (define-true-binary-ops << >> >>>) (define-true-binary-ops < > <= >= instanceof in) (define-true-binary-ops == != === !===)) (macrolet ((define-assignment-ops (&rest ops) `(progn ,@(loop for op in ops collect `(define-javascript-special-operator ,op :expression (processor lvalue rvalue &environment env) (process *javascript* processor lvalue (new-env 'statement-or-expression :expression env)) (raw-string processor ,(format nil " ~a " (symbol-name op))) (process *javascript* processor rvalue (new-env 'statement-or-expression :expression env))))))) (define-assignment-ops = *= /= %= += -= <<= >>= >>>= &= ^= \|=)) (define-javascript-special-operator comment :statement (processor &rest lines) :freshline (dolist (line lines) (out "// " (emit line) :newline))) (define-javascript-special-operator array :expression (processor &rest elements) "[" (loop for (e . rest) on elements do (expression e) when rest do (out ", ")) "]") (define-javascript-special-operator object :expression (processor &rest elements) "{ " (loop for (key value . rest) on elements by #'cddr do (out "\"" (name key) "\" : " (expression value)) when rest do (out ", ")) " }") (define-javascript-special-operator @ :expression (processor expr &rest slots) (expression expr) (loop for slot in slots do (if (symbolp slot) (out "." (name slot)) (out "[" (expression slot) "]")))) (define-javascript-special-operator ref :expression (processor expr &rest slots) (expression expr) (loop for slot in slots do (out "[" (expression slot) "]"))) (define-javascript-special-operator new :expression (processor expr &rest args) "new " (expression expr) (out "(" (loop for (e . rest) on args do (expression e) when rest do (out ", ")) ")")) (define-javascript-special-operator ++ :expression (processor lvalue &optional post) (if (eql post :post) (out (expression lvalue) "++") (out "++" (expression lvalue)))) (define-javascript-special-operator -- :expression (processor lvalue &optional post) (if (eql post :post) (out (expression lvalue) "--") (out "--" (expression lvalue)))) (define-javascript-special-operator ? :expression (processor condition then &optional (else 'null) &environment env) (process *javascript* processor condition (new-env 'statement-or-expression :expression env)) (raw-string processor " ? ") (process *javascript* processor then (new-env 'statement-or-expression :expression env)) (raw-string processor " : ") (process *javascript* processor else (new-env 'statement-or-expression :expression env))) (define-javascript-special-operator progn :expression (processor &rest body) "(" (loop for (e . rest) on body do (out (expression e)) (when rest (out ", "))) ")") (define-javascript-special-operator prog :statement (processor &rest body) (loop for s in body do (out (statement s) :freshline))) (define-javascript-special-operator block :statement (processor &rest body &environment env) (when (and body (not (cdr body))) (loop while (macro-form-p *javascript* (car body)) do (setf (car body) (expand-macro-form *javascript* (car body) env))) (loop while (and body (not (cdr body)) (consp (car body)) (eql (caar body) 'block)) do (setf body (rest (car body))))) (out "{" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent "}")) Var -- can only define one variable at a time . (define-javascript-special-operator var :statement (processor variable &optional value) :freshline "var " (name variable) (when value (out " = " (expression value))) ";") (define-javascript-special-operator if :statement (processor condition then &optional else) "if (" (expression condition) ") " (statement then) (when else (out " else " (statement else)))) (define-javascript-special-operator do-while :statement (processor body condition) "do " (statement body) " while (" (expression condition) ");") (define-javascript-special-operator while :statement (processor condition body) "while (" (expression condition) ") " (statement body)) (define-javascript-special-operator for :statement (processor var-test-step statement) (destructuring-bind (var test &optional step) var-test-step (let* ((var-p (and (consp var) (eql (first var) 'var))) (initialised (and (consp var) (if var-p (third var) (second var))))) (if var-p (setf var (second var))) (if (eql test 'in) (out "for (" (if var-p (out "var ")) (expression var) " in " (expression step) ") " (statement statement)) (out "for (" (if var-p (out "var ")) (if initialised (statement `(= ,var ,initialised)) (statement var)) " " (statement test) " " (expression step) ") " (statement statement)))))) (define-javascript-special-operator continue :statement (processor &optional id) "continue" (when id (out " " (name id))) ";") Break (define-javascript-special-operator break :statement (processor &optional id) "break" (when id (out " " (name id))) ";") #+(or)(define-javascript-special-operator return :statement (processor &optional expr) "return" (when expr (out " " (expression expr))) ";") (define-javascript-special-operator return :statement (processor &optional expr &environment env) (loop while (macro-form-p *javascript* expr) do (setf expr (expand-macro-form *javascript* expr env))) (cond ((and (consp expr) (consp (car expr))) (loop while (macro-form-p *javascript* (car expr)) do (setf expr (cons (expand-macro-form *javascript* (car expr) env) (cdr expr)))) (if (redundant-function-p expr) (loop for form in (cddar expr) do (out (statement form) :freshline)) (out "return " (expression expr) ";"))) ((redundant-apply-p expr) (destructuring-bind (name (function empty &rest body) this &optional args) expr (declare (ignore name this args function empty)) (loop for form in body do (out (statement form) :freshline)))) ((redundant-call-p expr) (destructuring-bind (name (function empty &rest body) this &rest args) expr (declare (ignore name this args function empty)) (loop for form in body do (out (statement form) :freshline)))) (t (out "return" (when expr (out " " (expression expr))) ";")))) Is this needed anymore ? wo n't work for Lispscript since we generate calls to apply . On the other hand , Lispscript has its (defun redundant-function-p (expr) (and (consp expr) (consp (car expr)) (eql (caar expr) 'function) (eql (cadar expr) '()))) Bit of a hack to help out Lispscript generation . (defun redundant-apply-p (expr) (and (consp expr) (eql (car expr) 'com.gigamonkeys.foo.lispscript::|.apply|) (destructuring-bind (name function this &optional args) expr (declare (ignore name function)) (and (eql this 'com.gigamonkeys.foo.lispscript::|this|) (equal args '(array)))))) (defun redundant-call-p (expr) (and (consp expr) (eql (car expr) 'com.gigamonkeys.foo.lispscript::|.call|) (destructuring-bind (name function this &rest args) expr (declare (ignore name function)) (and (eql this 'com.gigamonkeys.foo.lispscript::|this|) (null args))))) (define-javascript-special-operator with :statement (processor expr stmt) "with (" (expression expr) ") " (statement stmt)) Switch (define-javascript-special-operator switch :statement (processor expr &rest clauses) "switch (" (expression expr) ") {" :newline :indent (loop for (e . statements) in clauses do (if (eql e :default) (out "default:" :newline :indent) (out "case " (expression e) ":" :newline :indent)) (loop for s in statements do (statement s) (out :freshline)) (out :freshline :unindent)) :freshline :unindent "}") (define-javascript-special-operator label :statement (processor label statement) (name label) ": " (statement statement)) (define-javascript-special-operator throw :statement (processor expr) "throw " (expression expr) ";") (define-javascript-special-operator try :statement (processor &rest body) (flet ((key (e) (if (consp e) (first e)))) (let ((catch-clause (find 'catch body :key #'key)) (finally-clause (find 'finally body :key #'key))) (when catch-clause (assert (let ((next (cdr (member catch-clause body)))) (or (null next) (eql (car next) finally-clause))))) (when finally-clause (assert (null (cdr (member finally-clause body))))) (setf body (ldiff body (or (member catch-clause body) (member finally-clause body)))) (out "try {" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent :freshline "}" (when catch-clause (destructuring-bind (var &rest body) (rest catch-clause) (out " catch (" (name var) ") {" :newline :indent (loop for stmt in body do (out (statement stmt) :freshline)) :unindent :freshline "}"))) (when finally-clause (out " finally {" :newline :indent (loop for stmt in (rest finally-clause) do (out (statement stmt) :freshline)) :unindent :freshline "}")))))) Function -- two kinds , named and anonymous . The former is a (define-javascript-special-operator function :statement (processor &rest body &environment env) (flet ((params (params) (out "(" (loop for (p . rest) on params do (out (name p)) (when rest (out ", "))) ")")) (body (body) (process *javascript* processor `(block ,@body) (new-env 'statement-or-expression :statement env)))) (if (and (symbolp (first body)) (not (null (first body)))) (destructuring-bind (name (&rest params) &rest body) body (out "function " (name name) " " (params params) " " (body body))) (destructuring-bind ((&rest params) &rest body) body (when (eql (statement-or-expression env) :expression) (raw-string processor "(")) (out "function " (params params) " " (body body)) (when (eql (statement-or-expression env) :expression) (raw-string processor ")")))))) (define-javascript-special-operator augment-environment :statement (processor (&rest pairs) &body body &environment env) (let ((env (append pairs env))) (loop for form in body do (process *javascript* processor form env))))
6ac6adf4ceff79b7462c9c7d10174321cf6461530531247d88ef4b33d6b2cc49
shop-planner/shop3
pfile1.lisp
(in-package :shop-user) (defproblem umt.pfile1 UM-TRANSLOG-2 ( ;;; ;;; facts ;;; (REGION REGION0) (CITY CITY0) (CITY CITY1) (LOCATION LOCATION0) (LOCATION LOCATION1) (LOCATION LOCATION2) (LOCATION LOCATION3) (LOCATION LOCATION4) (LOCATION LOCATION5) (VEHICLE TRUCK0) (VEHICLE TRUCK1) (VEHICLE TRUCK2) (VEHICLE TRUCK3) (VEHICLE TRUCK4) (VEHICLE TRUCK5) (VEHICLE AIRPLANE0) (VEHICLE AIRPLANE1) (VEHICLE AIRPLANE2) (PLANE-RAMP PLANE_RAMP0) (PLANE-RAMP PLANE_RAMP1) (PLANE-RAMP PLANE_RAMP2) (PLANE-RAMP PLANE_RAMP3) (PACKAGE PACKAGE0) (PACKAGE PACKAGE1) (PACKAGE PACKAGE2) (ROUTE ROAD_ROUTE0) (ROUTE ROAD_ROUTE1) (ROUTE AIR_ROUTE0) (ROUTE AIR_ROUTE1) (ROUTE AIR_ROUTE2) (ROUTE AIR_ROUTE3) (ROUTE AIR_ROUTE4) (ROUTE AIR_ROUTE5) (ROUTE AIR_ROUTE6) (ROUTE AIR_ROUTE7) (ROUTE AIR_ROUTE8) (ROUTE AIR_ROUTE9) (ROUTE AIR_ROUTE10) (ROUTE AIR_ROUTE11) ;;; ;;; initial states ;;; (PV-COMPATIBLE REGULARP REGULARV) (PV-COMPATIBLE BULKY FLATBED) (PV-COMPATIBLE LIQUID TANKER) (PV-COMPATIBLE CARS AUTO) (PV-COMPATIBLE REGULARP AIR) (PV-COMPATIBLE MAIL AIR) (PV-COMPATIBLE MAIL REGULARV) (PV-COMPATIBLE GRANULAR HOPPER) (RV-COMPATIBLE AIR-ROUTE AIRPLANE) (RV-COMPATIBLE RAIL-ROUTE TRAIN) (RV-COMPATIBLE ROAD-ROUTE TRUCK) (IN-REGION CITY0 REGION0) (LOCAL-HEIGHT CITY0 23) (LOCAL-WEIGHT CITY0 284) (IN-REGION CITY1 REGION0) (LOCAL-HEIGHT CITY1 17) (LOCAL-WEIGHT CITY1 228) (IN-CITY LOCATION0 CITY0) (HEIGHT-CAP-L LOCATION0 20) (LENGTH-CAP-L LOCATION0 48) (WIDTH-CAP-L LOCATION0 29) (VOLUME-CAP-L LOCATION0 396) (TCENTER LOCATION0) (TYPEL LOCATION0 AIRPORT) (AVAILABLEL LOCATION0) (HUB LOCATION0) (IN-CITY LOCATION1 CITY0) (HEIGHT-CAP-L LOCATION1 11) (LENGTH-CAP-L LOCATION1 29) (WIDTH-CAP-L LOCATION1 33) (VOLUME-CAP-L LOCATION1 110) (TCENTER LOCATION1) (TYPEL LOCATION1 AIRPORT) (AVAILABLEL LOCATION1) (HUB LOCATION1) (IN-CITY LOCATION2 CITY1) (HEIGHT-CAP-L LOCATION2 21) (LENGTH-CAP-L LOCATION2 31) (WIDTH-CAP-L LOCATION2 13) (VOLUME-CAP-L LOCATION2 230) (TCENTER LOCATION2) (TYPEL LOCATION2 AIRPORT) (AVAILABLEL LOCATION2) (IN-CITY LOCATION3 CITY1) (HEIGHT-CAP-L LOCATION3 10) (LENGTH-CAP-L LOCATION3 35) (WIDTH-CAP-L LOCATION3 27) (VOLUME-CAP-L LOCATION3 311) (TCENTER LOCATION3) (TYPEL LOCATION3 AIRPORT) (AVAILABLEL LOCATION3) (HUB LOCATION3) (IN-CITY LOCATION4 CITY0) (HEIGHT-CAP-L LOCATION4 27) (LENGTH-CAP-L LOCATION4 46) (WIDTH-CAP-L LOCATION4 26) (VOLUME-CAP-L LOCATION4 484) (IN-CITY LOCATION5 CITY1) (HEIGHT-CAP-L LOCATION5 24) (LENGTH-CAP-L LOCATION5 20) (WIDTH-CAP-L LOCATION5 26) (VOLUME-CAP-L LOCATION5 336) (DISTANCE LOCATION0 LOCATION1 55) (DISTANCE LOCATION1 LOCATION0 55) (DISTANCE LOCATION0 LOCATION2 68) (DISTANCE LOCATION2 LOCATION0 68) (DISTANCE LOCATION0 LOCATION3 14) (DISTANCE LOCATION3 LOCATION0 14) (DISTANCE LOCATION0 LOCATION4 15) (DISTANCE LOCATION4 LOCATION0 15) (DISTANCE LOCATION0 LOCATION5 2) (DISTANCE LOCATION5 LOCATION0 2) (DISTANCE LOCATION0 LOCATION0 0) (DISTANCE LOCATION1 LOCATION2 42) (DISTANCE LOCATION2 LOCATION1 42) (DISTANCE LOCATION1 LOCATION3 18) (DISTANCE LOCATION3 LOCATION1 18) (DISTANCE LOCATION1 LOCATION4 20) (DISTANCE LOCATION4 LOCATION1 20) (DISTANCE LOCATION1 LOCATION5 33) (DISTANCE LOCATION5 LOCATION1 33) (DISTANCE LOCATION1 LOCATION1 0) (DISTANCE LOCATION2 LOCATION3 3) (DISTANCE LOCATION3 LOCATION2 3) (DISTANCE LOCATION2 LOCATION4 25) (DISTANCE LOCATION4 LOCATION2 25) (DISTANCE LOCATION2 LOCATION5 8) (DISTANCE LOCATION5 LOCATION2 8) (DISTANCE LOCATION2 LOCATION2 0) (DISTANCE LOCATION3 LOCATION4 61) (DISTANCE LOCATION4 LOCATION3 61) (DISTANCE LOCATION3 LOCATION5 43) (DISTANCE LOCATION5 LOCATION3 43) (DISTANCE LOCATION3 LOCATION3 0) (DISTANCE LOCATION4 LOCATION5 63) (DISTANCE LOCATION5 LOCATION4 63) (DISTANCE LOCATION4 LOCATION4 0) (DISTANCE LOCATION5 LOCATION5 0) (TYPEV TRUCK0 HOPPER) (TYPEVP TRUCK0 TRUCK) (AT-VEHICLE TRUCK0 LOCATION3) (GAS-LEFT TRUCK0 426) (GPM TRUCK0 3) (LENGTH-V TRUCK0 10) (HEIGHT-V TRUCK0 1) (WIDTH-V TRUCK0 8) (WEIGHT-CAP-V TRUCK0 272) (VOLUME-CAP-V TRUCK0 80) (WEIGHT-LOAD-V TRUCK0 0) (VOLUME-LOAD-V TRUCK0 0) (WEIGHT-V TRUCK0 20) (AVAILABLEV TRUCK0) (TYPEV TRUCK1 HOPPER) (TYPEVP TRUCK1 TRUCK) (AT-VEHICLE TRUCK1 LOCATION2) (GAS-LEFT TRUCK1 278) (GPM TRUCK1 3) (LENGTH-V TRUCK1 7) (HEIGHT-V TRUCK1 7) (WIDTH-V TRUCK1 7) (WEIGHT-CAP-V TRUCK1 112) (VOLUME-CAP-V TRUCK1 240) (WEIGHT-LOAD-V TRUCK1 0) (VOLUME-LOAD-V TRUCK1 0) (WEIGHT-V TRUCK1 14) (AVAILABLEV TRUCK1) (TYPEV TRUCK2 HOPPER) (TYPEVP TRUCK2 TRUCK) (AT-VEHICLE TRUCK2 LOCATION0) (GAS-LEFT TRUCK2 236) (GPM TRUCK2 1) (LENGTH-V TRUCK2 6) (HEIGHT-V TRUCK2 1) (WIDTH-V TRUCK2 1) (WEIGHT-CAP-V TRUCK2 372) (VOLUME-CAP-V TRUCK2 6) (WEIGHT-LOAD-V TRUCK2 0) (VOLUME-LOAD-V TRUCK2 0) (WEIGHT-V TRUCK2 18) (AVAILABLEV TRUCK2) (TYPEV TRUCK3 HOPPER) (TYPEVP TRUCK3 TRUCK) (AT-VEHICLE TRUCK3 LOCATION0) (GAS-LEFT TRUCK3 161) (GPM TRUCK3 2) (LENGTH-V TRUCK3 7) (HEIGHT-V TRUCK3 5) (WIDTH-V TRUCK3 6) (WEIGHT-CAP-V TRUCK3 498) (VOLUME-CAP-V TRUCK3 210) (WEIGHT-LOAD-V TRUCK3 0) (VOLUME-LOAD-V TRUCK3 0) (WEIGHT-V TRUCK3 21) (AVAILABLEV TRUCK3) (TYPEV TRUCK4 HOPPER) (TYPEVP TRUCK4 TRUCK) (AT-VEHICLE TRUCK4 LOCATION1) (GAS-LEFT TRUCK4 268) (GPM TRUCK4 3) (LENGTH-V TRUCK4 11) (HEIGHT-V TRUCK4 10) (WIDTH-V TRUCK4 10) (WEIGHT-CAP-V TRUCK4 413) (VOLUME-CAP-V TRUCK4 770) (WEIGHT-LOAD-V TRUCK4 0) (VOLUME-LOAD-V TRUCK4 0) (WEIGHT-V TRUCK4 26) (AVAILABLEV TRUCK4) (TYPEV TRUCK5 HOPPER) (TYPEVP TRUCK5 TRUCK) (AT-VEHICLE TRUCK5 LOCATION0) (GAS-LEFT TRUCK5 347) (GPM TRUCK5 2) (LENGTH-V TRUCK5 17) (HEIGHT-V TRUCK5 4) (WIDTH-V TRUCK5 10) (WEIGHT-CAP-V TRUCK5 113) (VOLUME-CAP-V TRUCK5 475) (WEIGHT-LOAD-V TRUCK5 0) (VOLUME-LOAD-V TRUCK5 0) (WEIGHT-V TRUCK5 16) (AVAILABLEV TRUCK5) (TYPEV AIRPLANE0 AIR) (TYPEVP AIRPLANE0 AIRPLANE) (AT-VEHICLE AIRPLANE0 LOCATION0) (GAS-LEFT AIRPLANE0 54) (GPM AIRPLANE0 3) (LENGTH-V AIRPLANE0 13) (HEIGHT-V AIRPLANE0 8) (WIDTH-V AIRPLANE0 4) (WEIGHT-CAP-V AIRPLANE0 35) (VOLUME-CAP-V AIRPLANE0 416) (WEIGHT-LOAD-V AIRPLANE0 0) (VOLUME-LOAD-V AIRPLANE0 0) (WEIGHT-V AIRPLANE0 19) (TYPEV AIRPLANE1 AIR) (TYPEVP AIRPLANE1 AIRPLANE) (AT-VEHICLE AIRPLANE1 LOCATION2) (GAS-LEFT AIRPLANE1 56) (GPM AIRPLANE1 1) (LENGTH-V AIRPLANE1 14) (HEIGHT-V AIRPLANE1 7) (WIDTH-V AIRPLANE1 10) (WEIGHT-CAP-V AIRPLANE1 168) (VOLUME-CAP-V AIRPLANE1 685) (WEIGHT-LOAD-V AIRPLANE1 0) (VOLUME-LOAD-V AIRPLANE1 0) (WEIGHT-V AIRPLANE1 37) (AVAILABLEV AIRPLANE1) (TYPEV AIRPLANE2 AIR) (TYPEVP AIRPLANE2 AIRPLANE) (AT-VEHICLE AIRPLANE2 LOCATION3) (GAS-LEFT AIRPLANE2 350) (GPM AIRPLANE2 3) (LENGTH-V AIRPLANE2 14) (HEIGHT-V AIRPLANE2 8) (WIDTH-V AIRPLANE2 6) (WEIGHT-CAP-V AIRPLANE2 331) (VOLUME-CAP-V AIRPLANE2 470) (WEIGHT-LOAD-V AIRPLANE2 0) (VOLUME-LOAD-V AIRPLANE2 0) (WEIGHT-V AIRPLANE2 33) (AVAILABLEV AIRPLANE2) (AT-EQUIPMENT PLANE_RAMP0 LOCATION0) (AT-EQUIPMENT PLANE_RAMP1 LOCATION1) (AT-EQUIPMENT PLANE_RAMP2 LOCATION2) (AT-EQUIPMENT PLANE_RAMP3 LOCATION3) (TYPEP PACKAGE0 GRANULAR) (AT-PACKAGEL PACKAGE0 LOCATION4) (VOLUME-P PACKAGE0 23) (WEIGHT-P PACKAGE0 13) (TYPEP PACKAGE1 GRANULAR) (AT-PACKAGEL PACKAGE1 LOCATION5) (VOLUME-P PACKAGE1 9) (WEIGHT-P PACKAGE1 12) (TYPEP PACKAGE2 GRANULAR) (AT-PACKAGEL PACKAGE2 LOCATION5) (VOLUME-P PACKAGE2 10) (WEIGHT-P PACKAGE2 21) (CONNECT-CITY ROAD_ROUTE0 ROAD-ROUTE CITY0 CITY1) (HEIGHT-CAP-R ROAD_ROUTE0 16) (WEIGHT-CAP-R ROAD_ROUTE0 533) (AVAILABLER ROAD_ROUTE0) (CONNECT-CITY ROAD_ROUTE1 ROAD-ROUTE CITY1 CITY0) (HEIGHT-CAP-R ROAD_ROUTE1 16) (WEIGHT-CAP-R ROAD_ROUTE1 286) (AVAILABLER ROAD_ROUTE1) (CONNECT-LOC AIR_ROUTE0 AIR-ROUTE LOCATION0 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE0 16) (WEIGHT-CAP-R AIR_ROUTE0 169) (SERVES LOCATION0 REGION0) (SERVES LOCATION1 REGION0) (AVAILABLER AIR_ROUTE0) (CONNECT-LOC AIR_ROUTE1 AIR-ROUTE LOCATION0 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE1 9) (WEIGHT-CAP-R AIR_ROUTE1 188) (AVAILABLER AIR_ROUTE1) (CONNECT-LOC AIR_ROUTE2 AIR-ROUTE LOCATION0 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE2 12) (WEIGHT-CAP-R AIR_ROUTE2 454) (SERVES LOCATION3 REGION0) (AVAILABLER AIR_ROUTE2) (CONNECT-LOC AIR_ROUTE3 AIR-ROUTE LOCATION1 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE3 27) (WEIGHT-CAP-R AIR_ROUTE3 317) (AVAILABLER AIR_ROUTE3) (CONNECT-LOC AIR_ROUTE4 AIR-ROUTE LOCATION1 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE4 18) (WEIGHT-CAP-R AIR_ROUTE4 542) (AVAILABLER AIR_ROUTE4) (CONNECT-LOC AIR_ROUTE5 AIR-ROUTE LOCATION1 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE5 24) (WEIGHT-CAP-R AIR_ROUTE5 365) (AVAILABLER AIR_ROUTE5) (CONNECT-LOC AIR_ROUTE6 AIR-ROUTE LOCATION2 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE6 15) (WEIGHT-CAP-R AIR_ROUTE6 224) (AVAILABLER AIR_ROUTE6) (CONNECT-LOC AIR_ROUTE7 AIR-ROUTE LOCATION2 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE7 24) (WEIGHT-CAP-R AIR_ROUTE7 306) (AVAILABLER AIR_ROUTE7) (CONNECT-LOC AIR_ROUTE8 AIR-ROUTE LOCATION2 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE8 12) (WEIGHT-CAP-R AIR_ROUTE8 326) (AVAILABLER AIR_ROUTE8) (CONNECT-LOC AIR_ROUTE9 AIR-ROUTE LOCATION3 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE9 29) (WEIGHT-CAP-R AIR_ROUTE9 75) (AVAILABLER AIR_ROUTE9) (CONNECT-LOC AIR_ROUTE10 AIR-ROUTE LOCATION3 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE10 26) (WEIGHT-CAP-R AIR_ROUTE10 323) (AVAILABLER AIR_ROUTE10) (CONNECT-LOC AIR_ROUTE11 AIR-ROUTE LOCATION3 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE11 30) (WEIGHT-CAP-R AIR_ROUTE11 63) (AVAILABLER AIR_ROUTE11) (VOLUME-LOAD-L LOCATION0 0) (VOLUME-LOAD-L LOCATION1 0) (VOLUME-LOAD-L LOCATION2 0) (VOLUME-LOAD-L LOCATION3 0) (VOLUME-LOAD-L LOCATION4 23) (VOLUME-LOAD-L LOCATION5 19) ) ;;; ;;; goals ;;; (:ordered (:task assert-goals ((DELIVERED PACKAGE0 LOCATION1) (DELIVERED PACKAGE1 LOCATION4) (DELIVERED PACKAGE2 LOCATION5) (CLEAR)) nil) (:task pre-check) (:unordered (:TASK DELIVERED PACKAGE0 LOCATION1) (:TASK DELIVERED PACKAGE1 LOCATION4) (:TASK DELIVERED PACKAGE2 LOCATION5) ) (:task !clean-domain)))
null
https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/examples/UMT2/pfile1.lisp
lisp
facts initial states goals
(in-package :shop-user) (defproblem umt.pfile1 UM-TRANSLOG-2 ( (REGION REGION0) (CITY CITY0) (CITY CITY1) (LOCATION LOCATION0) (LOCATION LOCATION1) (LOCATION LOCATION2) (LOCATION LOCATION3) (LOCATION LOCATION4) (LOCATION LOCATION5) (VEHICLE TRUCK0) (VEHICLE TRUCK1) (VEHICLE TRUCK2) (VEHICLE TRUCK3) (VEHICLE TRUCK4) (VEHICLE TRUCK5) (VEHICLE AIRPLANE0) (VEHICLE AIRPLANE1) (VEHICLE AIRPLANE2) (PLANE-RAMP PLANE_RAMP0) (PLANE-RAMP PLANE_RAMP1) (PLANE-RAMP PLANE_RAMP2) (PLANE-RAMP PLANE_RAMP3) (PACKAGE PACKAGE0) (PACKAGE PACKAGE1) (PACKAGE PACKAGE2) (ROUTE ROAD_ROUTE0) (ROUTE ROAD_ROUTE1) (ROUTE AIR_ROUTE0) (ROUTE AIR_ROUTE1) (ROUTE AIR_ROUTE2) (ROUTE AIR_ROUTE3) (ROUTE AIR_ROUTE4) (ROUTE AIR_ROUTE5) (ROUTE AIR_ROUTE6) (ROUTE AIR_ROUTE7) (ROUTE AIR_ROUTE8) (ROUTE AIR_ROUTE9) (ROUTE AIR_ROUTE10) (ROUTE AIR_ROUTE11) (PV-COMPATIBLE REGULARP REGULARV) (PV-COMPATIBLE BULKY FLATBED) (PV-COMPATIBLE LIQUID TANKER) (PV-COMPATIBLE CARS AUTO) (PV-COMPATIBLE REGULARP AIR) (PV-COMPATIBLE MAIL AIR) (PV-COMPATIBLE MAIL REGULARV) (PV-COMPATIBLE GRANULAR HOPPER) (RV-COMPATIBLE AIR-ROUTE AIRPLANE) (RV-COMPATIBLE RAIL-ROUTE TRAIN) (RV-COMPATIBLE ROAD-ROUTE TRUCK) (IN-REGION CITY0 REGION0) (LOCAL-HEIGHT CITY0 23) (LOCAL-WEIGHT CITY0 284) (IN-REGION CITY1 REGION0) (LOCAL-HEIGHT CITY1 17) (LOCAL-WEIGHT CITY1 228) (IN-CITY LOCATION0 CITY0) (HEIGHT-CAP-L LOCATION0 20) (LENGTH-CAP-L LOCATION0 48) (WIDTH-CAP-L LOCATION0 29) (VOLUME-CAP-L LOCATION0 396) (TCENTER LOCATION0) (TYPEL LOCATION0 AIRPORT) (AVAILABLEL LOCATION0) (HUB LOCATION0) (IN-CITY LOCATION1 CITY0) (HEIGHT-CAP-L LOCATION1 11) (LENGTH-CAP-L LOCATION1 29) (WIDTH-CAP-L LOCATION1 33) (VOLUME-CAP-L LOCATION1 110) (TCENTER LOCATION1) (TYPEL LOCATION1 AIRPORT) (AVAILABLEL LOCATION1) (HUB LOCATION1) (IN-CITY LOCATION2 CITY1) (HEIGHT-CAP-L LOCATION2 21) (LENGTH-CAP-L LOCATION2 31) (WIDTH-CAP-L LOCATION2 13) (VOLUME-CAP-L LOCATION2 230) (TCENTER LOCATION2) (TYPEL LOCATION2 AIRPORT) (AVAILABLEL LOCATION2) (IN-CITY LOCATION3 CITY1) (HEIGHT-CAP-L LOCATION3 10) (LENGTH-CAP-L LOCATION3 35) (WIDTH-CAP-L LOCATION3 27) (VOLUME-CAP-L LOCATION3 311) (TCENTER LOCATION3) (TYPEL LOCATION3 AIRPORT) (AVAILABLEL LOCATION3) (HUB LOCATION3) (IN-CITY LOCATION4 CITY0) (HEIGHT-CAP-L LOCATION4 27) (LENGTH-CAP-L LOCATION4 46) (WIDTH-CAP-L LOCATION4 26) (VOLUME-CAP-L LOCATION4 484) (IN-CITY LOCATION5 CITY1) (HEIGHT-CAP-L LOCATION5 24) (LENGTH-CAP-L LOCATION5 20) (WIDTH-CAP-L LOCATION5 26) (VOLUME-CAP-L LOCATION5 336) (DISTANCE LOCATION0 LOCATION1 55) (DISTANCE LOCATION1 LOCATION0 55) (DISTANCE LOCATION0 LOCATION2 68) (DISTANCE LOCATION2 LOCATION0 68) (DISTANCE LOCATION0 LOCATION3 14) (DISTANCE LOCATION3 LOCATION0 14) (DISTANCE LOCATION0 LOCATION4 15) (DISTANCE LOCATION4 LOCATION0 15) (DISTANCE LOCATION0 LOCATION5 2) (DISTANCE LOCATION5 LOCATION0 2) (DISTANCE LOCATION0 LOCATION0 0) (DISTANCE LOCATION1 LOCATION2 42) (DISTANCE LOCATION2 LOCATION1 42) (DISTANCE LOCATION1 LOCATION3 18) (DISTANCE LOCATION3 LOCATION1 18) (DISTANCE LOCATION1 LOCATION4 20) (DISTANCE LOCATION4 LOCATION1 20) (DISTANCE LOCATION1 LOCATION5 33) (DISTANCE LOCATION5 LOCATION1 33) (DISTANCE LOCATION1 LOCATION1 0) (DISTANCE LOCATION2 LOCATION3 3) (DISTANCE LOCATION3 LOCATION2 3) (DISTANCE LOCATION2 LOCATION4 25) (DISTANCE LOCATION4 LOCATION2 25) (DISTANCE LOCATION2 LOCATION5 8) (DISTANCE LOCATION5 LOCATION2 8) (DISTANCE LOCATION2 LOCATION2 0) (DISTANCE LOCATION3 LOCATION4 61) (DISTANCE LOCATION4 LOCATION3 61) (DISTANCE LOCATION3 LOCATION5 43) (DISTANCE LOCATION5 LOCATION3 43) (DISTANCE LOCATION3 LOCATION3 0) (DISTANCE LOCATION4 LOCATION5 63) (DISTANCE LOCATION5 LOCATION4 63) (DISTANCE LOCATION4 LOCATION4 0) (DISTANCE LOCATION5 LOCATION5 0) (TYPEV TRUCK0 HOPPER) (TYPEVP TRUCK0 TRUCK) (AT-VEHICLE TRUCK0 LOCATION3) (GAS-LEFT TRUCK0 426) (GPM TRUCK0 3) (LENGTH-V TRUCK0 10) (HEIGHT-V TRUCK0 1) (WIDTH-V TRUCK0 8) (WEIGHT-CAP-V TRUCK0 272) (VOLUME-CAP-V TRUCK0 80) (WEIGHT-LOAD-V TRUCK0 0) (VOLUME-LOAD-V TRUCK0 0) (WEIGHT-V TRUCK0 20) (AVAILABLEV TRUCK0) (TYPEV TRUCK1 HOPPER) (TYPEVP TRUCK1 TRUCK) (AT-VEHICLE TRUCK1 LOCATION2) (GAS-LEFT TRUCK1 278) (GPM TRUCK1 3) (LENGTH-V TRUCK1 7) (HEIGHT-V TRUCK1 7) (WIDTH-V TRUCK1 7) (WEIGHT-CAP-V TRUCK1 112) (VOLUME-CAP-V TRUCK1 240) (WEIGHT-LOAD-V TRUCK1 0) (VOLUME-LOAD-V TRUCK1 0) (WEIGHT-V TRUCK1 14) (AVAILABLEV TRUCK1) (TYPEV TRUCK2 HOPPER) (TYPEVP TRUCK2 TRUCK) (AT-VEHICLE TRUCK2 LOCATION0) (GAS-LEFT TRUCK2 236) (GPM TRUCK2 1) (LENGTH-V TRUCK2 6) (HEIGHT-V TRUCK2 1) (WIDTH-V TRUCK2 1) (WEIGHT-CAP-V TRUCK2 372) (VOLUME-CAP-V TRUCK2 6) (WEIGHT-LOAD-V TRUCK2 0) (VOLUME-LOAD-V TRUCK2 0) (WEIGHT-V TRUCK2 18) (AVAILABLEV TRUCK2) (TYPEV TRUCK3 HOPPER) (TYPEVP TRUCK3 TRUCK) (AT-VEHICLE TRUCK3 LOCATION0) (GAS-LEFT TRUCK3 161) (GPM TRUCK3 2) (LENGTH-V TRUCK3 7) (HEIGHT-V TRUCK3 5) (WIDTH-V TRUCK3 6) (WEIGHT-CAP-V TRUCK3 498) (VOLUME-CAP-V TRUCK3 210) (WEIGHT-LOAD-V TRUCK3 0) (VOLUME-LOAD-V TRUCK3 0) (WEIGHT-V TRUCK3 21) (AVAILABLEV TRUCK3) (TYPEV TRUCK4 HOPPER) (TYPEVP TRUCK4 TRUCK) (AT-VEHICLE TRUCK4 LOCATION1) (GAS-LEFT TRUCK4 268) (GPM TRUCK4 3) (LENGTH-V TRUCK4 11) (HEIGHT-V TRUCK4 10) (WIDTH-V TRUCK4 10) (WEIGHT-CAP-V TRUCK4 413) (VOLUME-CAP-V TRUCK4 770) (WEIGHT-LOAD-V TRUCK4 0) (VOLUME-LOAD-V TRUCK4 0) (WEIGHT-V TRUCK4 26) (AVAILABLEV TRUCK4) (TYPEV TRUCK5 HOPPER) (TYPEVP TRUCK5 TRUCK) (AT-VEHICLE TRUCK5 LOCATION0) (GAS-LEFT TRUCK5 347) (GPM TRUCK5 2) (LENGTH-V TRUCK5 17) (HEIGHT-V TRUCK5 4) (WIDTH-V TRUCK5 10) (WEIGHT-CAP-V TRUCK5 113) (VOLUME-CAP-V TRUCK5 475) (WEIGHT-LOAD-V TRUCK5 0) (VOLUME-LOAD-V TRUCK5 0) (WEIGHT-V TRUCK5 16) (AVAILABLEV TRUCK5) (TYPEV AIRPLANE0 AIR) (TYPEVP AIRPLANE0 AIRPLANE) (AT-VEHICLE AIRPLANE0 LOCATION0) (GAS-LEFT AIRPLANE0 54) (GPM AIRPLANE0 3) (LENGTH-V AIRPLANE0 13) (HEIGHT-V AIRPLANE0 8) (WIDTH-V AIRPLANE0 4) (WEIGHT-CAP-V AIRPLANE0 35) (VOLUME-CAP-V AIRPLANE0 416) (WEIGHT-LOAD-V AIRPLANE0 0) (VOLUME-LOAD-V AIRPLANE0 0) (WEIGHT-V AIRPLANE0 19) (TYPEV AIRPLANE1 AIR) (TYPEVP AIRPLANE1 AIRPLANE) (AT-VEHICLE AIRPLANE1 LOCATION2) (GAS-LEFT AIRPLANE1 56) (GPM AIRPLANE1 1) (LENGTH-V AIRPLANE1 14) (HEIGHT-V AIRPLANE1 7) (WIDTH-V AIRPLANE1 10) (WEIGHT-CAP-V AIRPLANE1 168) (VOLUME-CAP-V AIRPLANE1 685) (WEIGHT-LOAD-V AIRPLANE1 0) (VOLUME-LOAD-V AIRPLANE1 0) (WEIGHT-V AIRPLANE1 37) (AVAILABLEV AIRPLANE1) (TYPEV AIRPLANE2 AIR) (TYPEVP AIRPLANE2 AIRPLANE) (AT-VEHICLE AIRPLANE2 LOCATION3) (GAS-LEFT AIRPLANE2 350) (GPM AIRPLANE2 3) (LENGTH-V AIRPLANE2 14) (HEIGHT-V AIRPLANE2 8) (WIDTH-V AIRPLANE2 6) (WEIGHT-CAP-V AIRPLANE2 331) (VOLUME-CAP-V AIRPLANE2 470) (WEIGHT-LOAD-V AIRPLANE2 0) (VOLUME-LOAD-V AIRPLANE2 0) (WEIGHT-V AIRPLANE2 33) (AVAILABLEV AIRPLANE2) (AT-EQUIPMENT PLANE_RAMP0 LOCATION0) (AT-EQUIPMENT PLANE_RAMP1 LOCATION1) (AT-EQUIPMENT PLANE_RAMP2 LOCATION2) (AT-EQUIPMENT PLANE_RAMP3 LOCATION3) (TYPEP PACKAGE0 GRANULAR) (AT-PACKAGEL PACKAGE0 LOCATION4) (VOLUME-P PACKAGE0 23) (WEIGHT-P PACKAGE0 13) (TYPEP PACKAGE1 GRANULAR) (AT-PACKAGEL PACKAGE1 LOCATION5) (VOLUME-P PACKAGE1 9) (WEIGHT-P PACKAGE1 12) (TYPEP PACKAGE2 GRANULAR) (AT-PACKAGEL PACKAGE2 LOCATION5) (VOLUME-P PACKAGE2 10) (WEIGHT-P PACKAGE2 21) (CONNECT-CITY ROAD_ROUTE0 ROAD-ROUTE CITY0 CITY1) (HEIGHT-CAP-R ROAD_ROUTE0 16) (WEIGHT-CAP-R ROAD_ROUTE0 533) (AVAILABLER ROAD_ROUTE0) (CONNECT-CITY ROAD_ROUTE1 ROAD-ROUTE CITY1 CITY0) (HEIGHT-CAP-R ROAD_ROUTE1 16) (WEIGHT-CAP-R ROAD_ROUTE1 286) (AVAILABLER ROAD_ROUTE1) (CONNECT-LOC AIR_ROUTE0 AIR-ROUTE LOCATION0 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE0 16) (WEIGHT-CAP-R AIR_ROUTE0 169) (SERVES LOCATION0 REGION0) (SERVES LOCATION1 REGION0) (AVAILABLER AIR_ROUTE0) (CONNECT-LOC AIR_ROUTE1 AIR-ROUTE LOCATION0 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE1 9) (WEIGHT-CAP-R AIR_ROUTE1 188) (AVAILABLER AIR_ROUTE1) (CONNECT-LOC AIR_ROUTE2 AIR-ROUTE LOCATION0 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE2 12) (WEIGHT-CAP-R AIR_ROUTE2 454) (SERVES LOCATION3 REGION0) (AVAILABLER AIR_ROUTE2) (CONNECT-LOC AIR_ROUTE3 AIR-ROUTE LOCATION1 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE3 27) (WEIGHT-CAP-R AIR_ROUTE3 317) (AVAILABLER AIR_ROUTE3) (CONNECT-LOC AIR_ROUTE4 AIR-ROUTE LOCATION1 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE4 18) (WEIGHT-CAP-R AIR_ROUTE4 542) (AVAILABLER AIR_ROUTE4) (CONNECT-LOC AIR_ROUTE5 AIR-ROUTE LOCATION1 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE5 24) (WEIGHT-CAP-R AIR_ROUTE5 365) (AVAILABLER AIR_ROUTE5) (CONNECT-LOC AIR_ROUTE6 AIR-ROUTE LOCATION2 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE6 15) (WEIGHT-CAP-R AIR_ROUTE6 224) (AVAILABLER AIR_ROUTE6) (CONNECT-LOC AIR_ROUTE7 AIR-ROUTE LOCATION2 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE7 24) (WEIGHT-CAP-R AIR_ROUTE7 306) (AVAILABLER AIR_ROUTE7) (CONNECT-LOC AIR_ROUTE8 AIR-ROUTE LOCATION2 LOCATION3) (HEIGHT-CAP-R AIR_ROUTE8 12) (WEIGHT-CAP-R AIR_ROUTE8 326) (AVAILABLER AIR_ROUTE8) (CONNECT-LOC AIR_ROUTE9 AIR-ROUTE LOCATION3 LOCATION0) (HEIGHT-CAP-R AIR_ROUTE9 29) (WEIGHT-CAP-R AIR_ROUTE9 75) (AVAILABLER AIR_ROUTE9) (CONNECT-LOC AIR_ROUTE10 AIR-ROUTE LOCATION3 LOCATION1) (HEIGHT-CAP-R AIR_ROUTE10 26) (WEIGHT-CAP-R AIR_ROUTE10 323) (AVAILABLER AIR_ROUTE10) (CONNECT-LOC AIR_ROUTE11 AIR-ROUTE LOCATION3 LOCATION2) (HEIGHT-CAP-R AIR_ROUTE11 30) (WEIGHT-CAP-R AIR_ROUTE11 63) (AVAILABLER AIR_ROUTE11) (VOLUME-LOAD-L LOCATION0 0) (VOLUME-LOAD-L LOCATION1 0) (VOLUME-LOAD-L LOCATION2 0) (VOLUME-LOAD-L LOCATION3 0) (VOLUME-LOAD-L LOCATION4 23) (VOLUME-LOAD-L LOCATION5 19) ) (:ordered (:task assert-goals ((DELIVERED PACKAGE0 LOCATION1) (DELIVERED PACKAGE1 LOCATION4) (DELIVERED PACKAGE2 LOCATION5) (CLEAR)) nil) (:task pre-check) (:unordered (:TASK DELIVERED PACKAGE0 LOCATION1) (:TASK DELIVERED PACKAGE1 LOCATION4) (:TASK DELIVERED PACKAGE2 LOCATION5) ) (:task !clean-domain)))
2cbb53321197dbe9ececabbafe6ef2322bf748618db524053086b116fd1eeb1e
patrikja/AFPcourse
ANSI.hs
-- | Some helper functions to form ANSI codes suitable for terminal -- output. module ANSI where data Colour = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White deriving (Eq,Show,Enum) ansiClearScreen :: String ansiClearScreen = "\ESC[2J" ansiGoto :: Int -> Int -> String ansiGoto x y = "\ESC[" ++ show y ++ ";" ++ show x ++ "H" ansiColour :: Colour -> String -> String ansiColour c s = "\ESC[3" ++ show (fromEnum c) ++ "m" ++ s ++ "\ESC[0m"
null
https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/L3/src/ANSI.hs
haskell
| Some helper functions to form ANSI codes suitable for terminal output.
module ANSI where data Colour = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White deriving (Eq,Show,Enum) ansiClearScreen :: String ansiClearScreen = "\ESC[2J" ansiGoto :: Int -> Int -> String ansiGoto x y = "\ESC[" ++ show y ++ ";" ++ show x ++ "H" ansiColour :: Colour -> String -> String ansiColour c s = "\ESC[3" ++ show (fromEnum c) ++ "m" ++ s ++ "\ESC[0m"
0936814ee4502ae4ebf9686ad4b7b05ebc86468b7bfb3f8fe5fa2030cda6b761
dalaing/little-languages
TestLanguage.hs
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} {-# LANGUAGE DeriveFoldable #-} # LANGUAGE DeriveFunctor # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} module TestLanguage ( Type(..) , TypeError(..) , Term(..) , errorRules , errorRulesSrcLoc , languageRules ) where import Control.Monad (ap) import Control.Lens.TH (makeClassyPrisms) import Control.Lens (review, view) import Data.Monoid ((<>)) import Text.Trifecta.Rendering (Renderable (..)) import Prelude.Extras (Eq1(..), Ord1(..), Show1(..)) import Data.Bifunctor (Bifunctor(..)) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) import Data.Constraint import Bound2 (Bound3(..)) import Bifunctor2 (Bifunctor2(..)) import Common.Note (TranslateNote) import Component.Type.Error.ExpectedEq (AsExpectedEq (..), ExpectedEq (..), expectedEqInput, expectedEqSrcLocInput) import Component.Type.Error.Unexpected (AsUnexpected (..), Unexpected (..), unexpectedInput, unexpectedSrcLocInput) import Component.Type.Error.UnknownType (AsUnknownType (..), unknownTypeInput) import Component (ComponentInput, ComponentOutput) import Component.Bool (boolRules) import Component.STLC (stlcRules, stlcErrors, stlcSrcLocErrors) import Component.Term.Bool (AsBoolTerm (..), BoolTerm (..)) import Component.Term.STLC (AsSTLCTerm (..), AsSTLCVar (..), STLCTerm (..), STLCVar (..)) import Component.Type.STLC (AsSTLCType(..), STLCType(..), Context(..)) import Component.Type.Bool (AsBoolType (..), BoolType (..)) import Component.Nat (natRules) import Component.NatBool (natBoolRules) import Component.Term.Nat (AsNatTerm (..), NatTerm (..)) import Component.Term.NatBool (AsNatBoolTerm (..), NatBoolTerm (..)) import Component.Type.Nat (AsNatType (..), NatType (..)) import Component.Note (noteRules) import Component.Term.Note (AsNoteTerm (..), NoteTerm (..)) import Component.Type.Note (AsNoteType (..), NoteType (..)) import Component.Type.Error.FreeVar (FreeVar(..), AsFreeVar(..)) import Component.Type.Error.NotArrow (NotArrow(..), AsNotArrow(..)) import Component.Type.Note.Strip (StripNoteType(..)) import Component.Term.Note.Strip (StripNoteTerm(..)) import Language (mkLanguageDefaultParser) import qualified Extras (Eq1(..), Eq2(..), Eq3(..), Show1(..), Show2(..), Show3(..)) data Type n = BoolTy (BoolType Type n) | NatTy (NatType Type n) | StlcTy (STLCType Type n) | NoteTy (NoteType Type n) deriving (Eq, Ord, Show) instance Extras.Eq1 Type where spanEq1 = Sub Dict instance Extras.Show1 Type where spanShow1 = Sub Dict makeClassyPrisms ''Type instance AsBoolType Type Type where _BoolType = _BoolTy instance AsNatType Type Type where _NatType = _NatTy instance AsSTLCType Type Type where _STLCType = _StlcTy instance AsNoteType Type Type where _NoteType = _NoteTy instance StripNoteType Type Type where mapMaybeNoteType f (BoolTy i) = mapMaybeNoteType f i mapMaybeNoteType f (NatTy n) = mapMaybeNoteType f n mapMaybeNoteType f (StlcTy n) = mapMaybeNoteType f n mapMaybeNoteType f (NoteTy n) = mapMaybeNoteType f n data TypeError n a = TeUnknownType -- (Maybe n) | TeUnexpected (Unexpected Type n a) | TeExpectedEq (ExpectedEq Type n a) | TeFreeVar (FreeVar n a) | TeNotArrow (NotArrow Type n a) deriving (Eq, Ord, Show) instance Extras.Eq2 TypeError where spanEq2 = Sub Dict instance Extras.Show2 TypeError where spanShow2 = Sub Dict makeClassyPrisms ''TypeError instance AsUnknownType TypeError where _UnknownType = _TeUnknownType instance AsUnexpected TypeError Type where _Unexpected = _TeUnexpected . _Unexpected instance AsExpectedEq TypeError Type where _ExpectedEq = _TeExpectedEq . _ExpectedEq instance AsFreeVar TypeError where _FreeVar = _TeFreeVar . _FreeVar instance AsNotArrow TypeError Type where _NotArrow = _TeNotArrow . _NotArrow data Term nTy nTm a = TmBool (BoolTerm Term nTy nTm a) | TmNat (NatTerm Term nTy nTm a) | TmNatBool (NatBoolTerm Term nTy nTm a) | VarSTLC (STLCVar Term nTy nTm a) | TmSTLC (STLCTerm Type Term nTy nTm a) | TmNoted (NoteTerm Term nTy nTm a) deriving (Eq, Ord, Show, Functor, Foldable, Traversable) instance Extras.Eq3 Term where spanEq3 = Sub Dict instance Extras.Show3 Term where spanShow3 = Sub Dict instance (Eq nTy, Eq nTm) => Eq1 (Term nTy nTm) where (==#) = (==) instance (Ord nTy, Ord nTm) => Ord1 (Term nTy nTm) where compare1 = compare instance (Show nTy, Show nTm) => Show1 (Term nTy nTm) where showsPrec1 = showsPrec instance Applicative (Term nTy nTm) where pure = return (<*>) = ap instance Monad (Term nTy nTm) where return = review _TmVar VarSTLC (TmVar x) >>= f = f x TmBool tm >>= f = TmBool (tm >>>>>= f) TmNat tm >>= f = TmNat (tm >>>>>= f) TmNatBool tm >>= f = TmNatBool (tm >>>>>= f) TmSTLC tm >>= f = TmSTLC (tm >>>>>= f) TmNoted tm >>= f = TmNoted (tm >>>>>= f) instance Bifunctor2 Term where bifunctor2 _ = Dict makeClassyPrisms ''Term instance AsBoolTerm Term Term where _BoolTerm = _TmBool instance AsNatTerm Term Term where _NatTerm = _TmNat instance AsNatBoolTerm Term Term where _NatBoolTerm = _TmNatBool instance AsSTLCVar Term Term where _STLCVar = _VarSTLC instance AsSTLCTerm Term Type Term where _STLCTerm = _TmSTLC instance AsNoteTerm Term Term where _NoteTerm = _TmNoted instance StripNoteTerm Term Term where mapMaybeNoteTerm f (TmBool i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNat i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNatBool i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (VarSTLC i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmSTLC i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNoted n) = mapMaybeNoteTerm f n instance Bifunctor (Term nTy) where bimap l r (TmBool i) = TmBool (bimap l r i) bimap l r (TmNat i) = TmNat (bimap l r i) bimap l r (TmNatBool i) = TmNatBool (bimap l r i) bimap l r (VarSTLC i) = VarSTLC (bimap l r i) bimap l r (TmSTLC i) = TmSTLC (bimap l r i) bimap l r (TmNoted i) = TmNoted (bimap l r i) instance Bifoldable (Term nTy) where bifoldMap l r (TmBool i) = bifoldMap l r i bifoldMap l r (TmNat i) = bifoldMap l r i bifoldMap l r (TmNatBool i) = bifoldMap l r i bifoldMap l r (VarSTLC i) = bifoldMap l r i bifoldMap l r (TmSTLC i) = bifoldMap l r i bifoldMap l r (TmNoted i) = bifoldMap l r i instance Bitraversable (Term nTy) where bitraverse l r (TmBool i) = TmBool <$> bitraverse l r i bitraverse l r (TmNat i) = TmNat <$> bitraverse l r i bitraverse l r (TmNatBool i) = TmNatBool <$> bitraverse l r i bitraverse l r (VarSTLC i) = VarSTLC <$> bitraverse l r i bitraverse l r (TmSTLC i) = TmSTLC <$> bitraverse l r i bitraverse l r (TmNoted i) = TmNoted <$> bitraverse l r i errorRules :: ComponentInput r TypeError Type Term errorRules = unknownTypeInput <> unexpectedInput <> expectedEqInput <> stlcErrors errorRulesSrcLoc :: -- ( Show n , n -- ) -- => ComponentInput r TypeError Type Term errorRulesSrcLoc = unknownTypeInput <> unexpectedSrcLocInput <> expectedEqSrcLocInput <> stlcSrcLocErrors languageRules :: -- ( Eq n -- , Show n , TranslateNote n n -- ) -- => ComponentInput (Context Type) TypeError Type Term languageRules = boolRules <> natRules <> natBoolRules <> stlcRules <> noteRules
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/modular/test-lang/src/TestLanguage.hs
haskell
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveTraversable # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE RankNTypes # (Maybe n) ( Show n ) => ( Eq n , Show n ) =>
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} # LANGUAGE DeriveFunctor # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # module TestLanguage ( Type(..) , TypeError(..) , Term(..) , errorRules , errorRulesSrcLoc , languageRules ) where import Control.Monad (ap) import Control.Lens.TH (makeClassyPrisms) import Control.Lens (review, view) import Data.Monoid ((<>)) import Text.Trifecta.Rendering (Renderable (..)) import Prelude.Extras (Eq1(..), Ord1(..), Show1(..)) import Data.Bifunctor (Bifunctor(..)) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) import Data.Constraint import Bound2 (Bound3(..)) import Bifunctor2 (Bifunctor2(..)) import Common.Note (TranslateNote) import Component.Type.Error.ExpectedEq (AsExpectedEq (..), ExpectedEq (..), expectedEqInput, expectedEqSrcLocInput) import Component.Type.Error.Unexpected (AsUnexpected (..), Unexpected (..), unexpectedInput, unexpectedSrcLocInput) import Component.Type.Error.UnknownType (AsUnknownType (..), unknownTypeInput) import Component (ComponentInput, ComponentOutput) import Component.Bool (boolRules) import Component.STLC (stlcRules, stlcErrors, stlcSrcLocErrors) import Component.Term.Bool (AsBoolTerm (..), BoolTerm (..)) import Component.Term.STLC (AsSTLCTerm (..), AsSTLCVar (..), STLCTerm (..), STLCVar (..)) import Component.Type.STLC (AsSTLCType(..), STLCType(..), Context(..)) import Component.Type.Bool (AsBoolType (..), BoolType (..)) import Component.Nat (natRules) import Component.NatBool (natBoolRules) import Component.Term.Nat (AsNatTerm (..), NatTerm (..)) import Component.Term.NatBool (AsNatBoolTerm (..), NatBoolTerm (..)) import Component.Type.Nat (AsNatType (..), NatType (..)) import Component.Note (noteRules) import Component.Term.Note (AsNoteTerm (..), NoteTerm (..)) import Component.Type.Note (AsNoteType (..), NoteType (..)) import Component.Type.Error.FreeVar (FreeVar(..), AsFreeVar(..)) import Component.Type.Error.NotArrow (NotArrow(..), AsNotArrow(..)) import Component.Type.Note.Strip (StripNoteType(..)) import Component.Term.Note.Strip (StripNoteTerm(..)) import Language (mkLanguageDefaultParser) import qualified Extras (Eq1(..), Eq2(..), Eq3(..), Show1(..), Show2(..), Show3(..)) data Type n = BoolTy (BoolType Type n) | NatTy (NatType Type n) | StlcTy (STLCType Type n) | NoteTy (NoteType Type n) deriving (Eq, Ord, Show) instance Extras.Eq1 Type where spanEq1 = Sub Dict instance Extras.Show1 Type where spanShow1 = Sub Dict makeClassyPrisms ''Type instance AsBoolType Type Type where _BoolType = _BoolTy instance AsNatType Type Type where _NatType = _NatTy instance AsSTLCType Type Type where _STLCType = _StlcTy instance AsNoteType Type Type where _NoteType = _NoteTy instance StripNoteType Type Type where mapMaybeNoteType f (BoolTy i) = mapMaybeNoteType f i mapMaybeNoteType f (NatTy n) = mapMaybeNoteType f n mapMaybeNoteType f (StlcTy n) = mapMaybeNoteType f n mapMaybeNoteType f (NoteTy n) = mapMaybeNoteType f n data TypeError n a = | TeUnexpected (Unexpected Type n a) | TeExpectedEq (ExpectedEq Type n a) | TeFreeVar (FreeVar n a) | TeNotArrow (NotArrow Type n a) deriving (Eq, Ord, Show) instance Extras.Eq2 TypeError where spanEq2 = Sub Dict instance Extras.Show2 TypeError where spanShow2 = Sub Dict makeClassyPrisms ''TypeError instance AsUnknownType TypeError where _UnknownType = _TeUnknownType instance AsUnexpected TypeError Type where _Unexpected = _TeUnexpected . _Unexpected instance AsExpectedEq TypeError Type where _ExpectedEq = _TeExpectedEq . _ExpectedEq instance AsFreeVar TypeError where _FreeVar = _TeFreeVar . _FreeVar instance AsNotArrow TypeError Type where _NotArrow = _TeNotArrow . _NotArrow data Term nTy nTm a = TmBool (BoolTerm Term nTy nTm a) | TmNat (NatTerm Term nTy nTm a) | TmNatBool (NatBoolTerm Term nTy nTm a) | VarSTLC (STLCVar Term nTy nTm a) | TmSTLC (STLCTerm Type Term nTy nTm a) | TmNoted (NoteTerm Term nTy nTm a) deriving (Eq, Ord, Show, Functor, Foldable, Traversable) instance Extras.Eq3 Term where spanEq3 = Sub Dict instance Extras.Show3 Term where spanShow3 = Sub Dict instance (Eq nTy, Eq nTm) => Eq1 (Term nTy nTm) where (==#) = (==) instance (Ord nTy, Ord nTm) => Ord1 (Term nTy nTm) where compare1 = compare instance (Show nTy, Show nTm) => Show1 (Term nTy nTm) where showsPrec1 = showsPrec instance Applicative (Term nTy nTm) where pure = return (<*>) = ap instance Monad (Term nTy nTm) where return = review _TmVar VarSTLC (TmVar x) >>= f = f x TmBool tm >>= f = TmBool (tm >>>>>= f) TmNat tm >>= f = TmNat (tm >>>>>= f) TmNatBool tm >>= f = TmNatBool (tm >>>>>= f) TmSTLC tm >>= f = TmSTLC (tm >>>>>= f) TmNoted tm >>= f = TmNoted (tm >>>>>= f) instance Bifunctor2 Term where bifunctor2 _ = Dict makeClassyPrisms ''Term instance AsBoolTerm Term Term where _BoolTerm = _TmBool instance AsNatTerm Term Term where _NatTerm = _TmNat instance AsNatBoolTerm Term Term where _NatBoolTerm = _TmNatBool instance AsSTLCVar Term Term where _STLCVar = _VarSTLC instance AsSTLCTerm Term Type Term where _STLCTerm = _TmSTLC instance AsNoteTerm Term Term where _NoteTerm = _TmNoted instance StripNoteTerm Term Term where mapMaybeNoteTerm f (TmBool i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNat i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNatBool i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (VarSTLC i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmSTLC i) = mapMaybeNoteTerm f i mapMaybeNoteTerm f (TmNoted n) = mapMaybeNoteTerm f n instance Bifunctor (Term nTy) where bimap l r (TmBool i) = TmBool (bimap l r i) bimap l r (TmNat i) = TmNat (bimap l r i) bimap l r (TmNatBool i) = TmNatBool (bimap l r i) bimap l r (VarSTLC i) = VarSTLC (bimap l r i) bimap l r (TmSTLC i) = TmSTLC (bimap l r i) bimap l r (TmNoted i) = TmNoted (bimap l r i) instance Bifoldable (Term nTy) where bifoldMap l r (TmBool i) = bifoldMap l r i bifoldMap l r (TmNat i) = bifoldMap l r i bifoldMap l r (TmNatBool i) = bifoldMap l r i bifoldMap l r (VarSTLC i) = bifoldMap l r i bifoldMap l r (TmSTLC i) = bifoldMap l r i bifoldMap l r (TmNoted i) = bifoldMap l r i instance Bitraversable (Term nTy) where bitraverse l r (TmBool i) = TmBool <$> bitraverse l r i bitraverse l r (TmNat i) = TmNat <$> bitraverse l r i bitraverse l r (TmNatBool i) = TmNatBool <$> bitraverse l r i bitraverse l r (VarSTLC i) = VarSTLC <$> bitraverse l r i bitraverse l r (TmSTLC i) = TmSTLC <$> bitraverse l r i bitraverse l r (TmNoted i) = TmNoted <$> bitraverse l r i errorRules :: ComponentInput r TypeError Type Term errorRules = unknownTypeInput <> unexpectedInput <> expectedEqInput <> stlcErrors , n ComponentInput r TypeError Type Term errorRulesSrcLoc = unknownTypeInput <> unexpectedSrcLocInput <> expectedEqSrcLocInput <> stlcSrcLocErrors , TranslateNote n n ComponentInput (Context Type) TypeError Type Term languageRules = boolRules <> natRules <> natBoolRules <> stlcRules <> noteRules
45c79ffe6a8b772f0e43ba9eaf3eb3b9055386b4fc28bb30148f937c35133305
reborg/clojure-essential-reference
4.clj
< 1 > < 2 > (first output) ; <3> evaluating 1 1 < 4 > 1
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/OtherGenerators/lazy-seq/4.clj
clojure
<3>
< 1 > < 2 > evaluating 1 1 < 4 > 1
fc7deae6effeb757d9e91ac5dd166ba8fb25229a0b21196b48d4c42c715b1cca
kit-ty-kate/visitors
expr13double.ml
open Expr12 open Expr13 let double : expr -> expr = let v = object inherit [_] map method! visit_EConst _env k = EConst (2 * k) end in v # visit_'expr ()
null
https://raw.githubusercontent.com/kit-ty-kate/visitors/fc53cc486178781e0b1e581eced98e07facb7d29/test/expr13double.ml
ocaml
open Expr12 open Expr13 let double : expr -> expr = let v = object inherit [_] map method! visit_EConst _env k = EConst (2 * k) end in v # visit_'expr ()
1588917a7225be28bc98b95495378fd8e96c42b4dcc3b3816f23fae0a9af03a8
mvoidex/hsdev
Base.hs
module HsDev.Tools.Base ( runTool, runTool_, Result, ToolM, runWait, runWait_, tool, tool_, matchRx, splitRx, replaceRx, at, at_, module HsDev.Tools.Types ) where import Control.Monad.Except import Data.Array (assocs) import Data.List (unfoldr, intercalate) import Data.Maybe (fromMaybe) import Data.String import System.Exit import System.Process import Text.Regex.PCRE ((=~), MatchResult(..)) import HsDev.Error import HsDev.Tools.Types import HsDev.Util (liftIOErrors) -- | Run tool, throwing HsDevError on fail runTool :: FilePath -> [String] -> String -> IO String runTool name args input = hsdevLiftIOWith onIOError $ do (code, out, err) <- readProcessWithExitCode name args input case code of ExitFailure ecode -> hsdevError $ ToolError name $ "exited with code " ++ show ecode ++ ": " ++ err ExitSuccess -> return out where onIOError s = ToolError name $ unlines [ "args: [" ++ intercalate ", " args ++ "]", "stdin: " ++ input, "error: " ++ s] | Run tool with not stdin runTool_ :: FilePath -> [String] -> IO String runTool_ name args = runTool name args "" type Result = Either String String type ToolM a = ExceptT String IO a -- | Run command and wait for result runWait :: FilePath -> [String] -> String -> IO Result runWait name args input = do (code, out, err) <- readProcessWithExitCode name args input return $ if code == ExitSuccess && not (null out) then Right out else Left err -- | Run command with no input runWait_ :: FilePath -> [String] -> IO Result runWait_ name args = runWait name args "" -- | Tool tool :: FilePath -> [String] -> String -> ToolM String tool name args input = liftIOErrors $ ExceptT $ runWait name args input -- | Tool with no input tool_ :: FilePath -> [String] -> ToolM String tool_ name args = tool name args "" matchRx :: String -> String -> Maybe (Int -> Maybe String) matchRx pat str = if matched then Just look else Nothing where m :: MatchResult String m = str =~ pat matched = not $ null $ mrMatch m groups = filter (not . null . snd) $ assocs $ mrSubs m look i = lookup i groups splitRx :: String -> String -> [String] splitRx pat = unfoldr split' . Just where split' :: Maybe String -> Maybe (String, Maybe String) split' Nothing = Nothing split' (Just str) = case str =~ pat of (pre, "", "") -> Just (pre, Nothing) (pre, _, post) -> Just (pre, Just post) replaceRx :: String -> String -> String -> String replaceRx pat w = intercalate w . splitRx pat at :: (Int -> Maybe a) -> Int -> a at g i = fromMaybe (error $ "Can't find group " ++ show i) $ g i at_ :: IsString s => (Int -> Maybe s) -> Int -> s at_ g = fromMaybe (fromString "") . g
null
https://raw.githubusercontent.com/mvoidex/hsdev/016646080a6859e4d9b4a1935fc1d732e388db1a/src/HsDev/Tools/Base.hs
haskell
| Run tool, throwing HsDevError on fail | Run command and wait for result | Run command with no input | Tool | Tool with no input
module HsDev.Tools.Base ( runTool, runTool_, Result, ToolM, runWait, runWait_, tool, tool_, matchRx, splitRx, replaceRx, at, at_, module HsDev.Tools.Types ) where import Control.Monad.Except import Data.Array (assocs) import Data.List (unfoldr, intercalate) import Data.Maybe (fromMaybe) import Data.String import System.Exit import System.Process import Text.Regex.PCRE ((=~), MatchResult(..)) import HsDev.Error import HsDev.Tools.Types import HsDev.Util (liftIOErrors) runTool :: FilePath -> [String] -> String -> IO String runTool name args input = hsdevLiftIOWith onIOError $ do (code, out, err) <- readProcessWithExitCode name args input case code of ExitFailure ecode -> hsdevError $ ToolError name $ "exited with code " ++ show ecode ++ ": " ++ err ExitSuccess -> return out where onIOError s = ToolError name $ unlines [ "args: [" ++ intercalate ", " args ++ "]", "stdin: " ++ input, "error: " ++ s] | Run tool with not stdin runTool_ :: FilePath -> [String] -> IO String runTool_ name args = runTool name args "" type Result = Either String String type ToolM a = ExceptT String IO a runWait :: FilePath -> [String] -> String -> IO Result runWait name args input = do (code, out, err) <- readProcessWithExitCode name args input return $ if code == ExitSuccess && not (null out) then Right out else Left err runWait_ :: FilePath -> [String] -> IO Result runWait_ name args = runWait name args "" tool :: FilePath -> [String] -> String -> ToolM String tool name args input = liftIOErrors $ ExceptT $ runWait name args input tool_ :: FilePath -> [String] -> ToolM String tool_ name args = tool name args "" matchRx :: String -> String -> Maybe (Int -> Maybe String) matchRx pat str = if matched then Just look else Nothing where m :: MatchResult String m = str =~ pat matched = not $ null $ mrMatch m groups = filter (not . null . snd) $ assocs $ mrSubs m look i = lookup i groups splitRx :: String -> String -> [String] splitRx pat = unfoldr split' . Just where split' :: Maybe String -> Maybe (String, Maybe String) split' Nothing = Nothing split' (Just str) = case str =~ pat of (pre, "", "") -> Just (pre, Nothing) (pre, _, post) -> Just (pre, Just post) replaceRx :: String -> String -> String -> String replaceRx pat w = intercalate w . splitRx pat at :: (Int -> Maybe a) -> Int -> a at g i = fromMaybe (error $ "Can't find group " ++ show i) $ g i at_ :: IsString s => (Int -> Maybe s) -> Int -> s at_ g = fromMaybe (fromString "") . g