_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 |
|---|---|---|---|---|---|---|---|---|
ff7563688ae90c34d5142a4d86cb7759c9841c42f920373018617351dada243a | WickedShell/clj-mavlink | parser.clj | (ns mavlink.parser
(:require [clojure.test :refer :all]
[clojure.java.io :as io]
[mavlink.checksum :refer :all]
[mavlink.core :refer :all]
[mavlink.type :refer :all]
[mavlink.test_utilities :refer :all])
(:import [com.mavlink CRC]
[java.nio ByteBuffer ByteOrder]))
; This file tests only the mavlink parser.
;
; The string version produces message specific magic bytes
; the other version returns the full checksum
(defn compute-crc-checksum
([^String s]
(let [the-bytes (.getBytes s)
crc (new CRC)]
(doseq [b the-bytes]
(.update-checksum crc (bit-and (long b) 0xff)))
(bit-xor (.getMSB ^CRC crc) (.getLSB ^CRC crc))))
([the-bytes start-idx last-idx crc-seed]
(let [crc (new CRC)]
(doseq [idx (range start-idx last-idx)]
(.update-checksum crc
(if (.isArray (class the-bytes))
(aget ^bytes the-bytes idx)
(.get ^java.nio.ByteBuffer the-bytes (int idx)))))
(when crc-seed
(.update-checksum crc crc-seed))
(.crcValue crc))))
(def mavlink (parse {:xml-sources [{:xml-file "ardupilotmega.xml"
:xml-source (-> "test/resources/ardupilotmega.xml" io/input-stream)}
{:xml-file "common.xml"
:xml-source (-> "test/resources/common.xml" io/input-stream)}
{:xml-file "uAvionix.xml"
:xml-source (-> "test/resources/uAvionix.xml" io/input-stream)}]
:retain-fields? true}))
(deftest clj-mavlink-utilities
(testing "checksums"
(let [s "this is a string test"
byte-string "fe 19 e0 1 1 16 0 0 0 0 93 2 63 0 49 4e 49 54 49 41 4c 5f 4d 4f 44 45 0 0 0 0 2 bb 4c"
len-byte-string (count (clojure.string/split s #" "))
some-bytes (mkbytes byte-string)
buffer (ByteBuffer/wrap some-bytes)
crc-seed (byte 55)
mk-crc-seed (fn [checksum]
(bit-xor (bit-and checksum 0xFF)
(bit-and (bit-shift-right checksum 8) 0xff)))]
(.order buffer ByteOrder/LITTLE_ENDIAN)
; note that compute-crc-checksum makes the magic byte for strings
this is to make it as much like the Java MAVlink packet as possible .
(is (== (mk-crc-seed (compute-checksum (.getBytes s)))
(compute-crc-checksum s))
"checksum string")
(is (== (compute-crc-checksum some-bytes 0 len-byte-string nil)
(compute-crc-checksum buffer 0 len-byte-string nil))
"checksum byte array with no magic byte")
(is (== (compute-crc-checksum some-bytes 0 len-byte-string crc-seed)
(compute-crc-checksum buffer 0 len-byte-string crc-seed))
"checksum byte array with magic byte")
(is (== (compute-checksum some-bytes 1 15 nil)
(compute-crc-checksum some-bytes 1 15 nil)
(compute-checksum buffer 1 15 nil)
(compute-crc-checksum buffer 1 15 nil))
"checksum byte array 15 bytes no magic byte")
(is (== (compute-checksum some-bytes 1 15 crc-seed)
(compute-crc-checksum some-bytes 1 15 crc-seed)
(compute-checksum buffer 1 15 crc-seed)
(compute-crc-checksum buffer 1 15 crc-seed))
"checksum byte array 15 bytes with magic byte")))
(testing "typed-read-write"
(let [buffer (ByteBuffer/allocate 200)
test-values (atom {})]
(.order buffer ByteOrder/LITTLE_ENDIAN)
(doseq [type-key [:uint64_t :int64_t :double :uint32_t :int32_t
:float :uint16_t :int16_t :uint8_t
:uint8_t_mavlink_version :int8_t :char]
:let [write-fn (type-key write-payload)
test-value (get-test-value type-key 5)]]
(is write-fn
(str "write function not defined for " type-key))
(swap! test-values assoc type-key test-value)
(write-fn buffer test-value))
(.position buffer 0)
(doseq [type-key [:uint64_t :int64_t :double :uint32_t :int32_t
:float :uint16_t :int16_t :uint8_t
:uint8_t_mavlink_version :int8_t :char]
:let [read-fn (type-key read-payload)]]
(is read-fn
(str "read function not defined for " type-key))
(is (= (type-key @test-values)
(read-fn buffer))
(str "roundtrip data write-read for " type-key " failed."))))))
(deftest simple-parser-test
(testing "Testing Simple parsing of enums."
(let [mavlink-simple (parse
{:xml-sources [{:xml-file "test-parse.xml"
:xml-source (-> "test/resources/test-parse.xml" io/input-stream)}]
:retain-fields? true
:descriptions true})]
(is (thrown-with-msg? Exception #"Enum values conflict"
(parse
{:xml-sources [{:xml-file "common.xml"
:xml-source (-> "test/resources/common.xml" io/input-stream)}
{:xml-file "test-parse.xml"
:xml-source (-> "test/resources/test-parse.xml" io/input-stream)}]
:descriptions true})))
;(is (thrown-with-msg? Exception #"Unable to translate enum"
; (encode channel-simple {:message-id :heartbeat :type :dummy-enum})))
(is (= (:enum-to-value mavlink-simple)
{:mav-autopilot-generic 0,
:mav-autopilot-reserved 1,
:mav-autopilot-slugs 2,
:mav-cmd-ack-ok 0,
:mav-cmd-ack-err-fail 1,
:mav-cmd-ack-err-access-denied 2,
:mav-cmd-ack-err-not-supported 3,
:mav-cmd-ack-err-coordinate-frame-not-supported 4,
:mav-cmd-ack-err-coordinates-out-of-range 5,
:mav-cmd-ack-err-x-lat-out-of-range 6,
:mav-cmd-ack-err-y-lon-out-of-range 7,
:mav-cmd-ack-err-z-alt-out-of-range 8,
:mav-type-generic 0,
:mav-type-fixed-wing 1,
:mav-state-uninit 0,
:mav-state-boot 1,
:mav-state-calibrating 2,
:mav-state-standby 3,
:mav-state-active 4,
:mav-state-critical 5,
:mav-state-emergency 6,
:mav-state-poweroff 7
:mav-test-five 5,
:mav-test-six 6,
:mav-test-ten 10
:mav-test-eleven 11})
"Enum-to-value test failed.")
(is (= (:enums-by-group mavlink-simple)
{:mav-test {5 :mav-test-five,
6 :mav-test-six,
10 :mav-test-ten
11 :mav-test-eleven}
:mav-autopilot {0 :mav-autopilot-generic,
1 :mav-autopilot-reserved,
2 :mav-autopilot-slugs},
:mav-cmd-ack {0 :mav-cmd-ack-ok,
1 :mav-cmd-ack-err-fail,
2 :mav-cmd-ack-err-access-denied,
3 :mav-cmd-ack-err-not-supported,
4 :mav-cmd-ack-err-coordinate-frame-not-supported,
5 :mav-cmd-ack-err-coordinates-out-of-range,
6 :mav-cmd-ack-err-x-lat-out-of-range,
7 :mav-cmd-ack-err-y-lon-out-of-range,
8 :mav-cmd-ack-err-z-alt-out-of-range},
:mav-type {0 :mav-type-generic,
1 :mav-type-fixed-wing},
:mav-state {0 :mav-state-uninit,
1 :mav-state-boot,
2 :mav-state-calibrating,
3 :mav-state-standby,
4 :mav-state-active,
5 :mav-state-critical,
6 :mav-state-emergency,
7 :mav-state-poweroff}})
"Enum-by-group test failed")
(is (= (get (:mav-autopilot (:enums-by-group mavlink-simple)) 1) :mav-autopilot-reserved)
"Fetching of enum by its value from enums-by-group failed.")
(is (= (:fld-name (get (:fields (:heartbeat (:messages-by-keyword mavlink-simple))) 3))
"base_mode")
"Fetching type of base-mode from heartbeat messages-by-keyword failed.")
(is (= (:msg-id (:gps-status (:messages-by-keyword mavlink-simple))) 25)
"Fetching id of message from messages-by-keyword failed")
(is (= (:msg-id (get (:messages-by-id mavlink-simple) 25)) 25)
"Fetching id of message from messages-by-id failed")
(is (not (nil? (:mav-autopilot (:descriptions mavlink-simple))))
"Failed to find description")
)))
(deftest mavlink-core
(testing "Testing multi file include."
(is (not (nil? (:uavionix-adsb-out-cfg (:messages-by-keyword mavlink))))
"Include from uAvionix.xml failed.")
(is (not (nil? (:heartbeat (:messages-by-keyword mavlink))))
"Include from common.xml fialed.")
(is (not (nil? (:sensor-offsets (:messages-by-keyword mavlink))))
"Include from ardupilotmega.xml failed."))
(testing "For valid message checksums."
(is (== (-> mavlink :messages-by-keyword :heartbeat :crc-seed) 50)
"Hearbeat magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :sys-status :crc-seed) 124)
"Sys Status magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :change-operator-control :crc-seed) 217)
"Change Operator Control magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :param-set :crc-seed) 168)
"Param Set magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :ping :crc-seed) 237)
"output Raw magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :servo-output-raw :crc-seed) 222)
"output Raw magic byte checksum.")))
| null | https://raw.githubusercontent.com/WickedShell/clj-mavlink/21d79d07f862e3fb6d9a75be8e65151e2ab4952b/test/mavlink/parser.clj | clojure | This file tests only the mavlink parser.
The string version produces message specific magic bytes
the other version returns the full checksum
note that compute-crc-checksum makes the magic byte for strings
(is (thrown-with-msg? Exception #"Unable to translate enum"
(encode channel-simple {:message-id :heartbeat :type :dummy-enum}))) | (ns mavlink.parser
(:require [clojure.test :refer :all]
[clojure.java.io :as io]
[mavlink.checksum :refer :all]
[mavlink.core :refer :all]
[mavlink.type :refer :all]
[mavlink.test_utilities :refer :all])
(:import [com.mavlink CRC]
[java.nio ByteBuffer ByteOrder]))
(defn compute-crc-checksum
([^String s]
(let [the-bytes (.getBytes s)
crc (new CRC)]
(doseq [b the-bytes]
(.update-checksum crc (bit-and (long b) 0xff)))
(bit-xor (.getMSB ^CRC crc) (.getLSB ^CRC crc))))
([the-bytes start-idx last-idx crc-seed]
(let [crc (new CRC)]
(doseq [idx (range start-idx last-idx)]
(.update-checksum crc
(if (.isArray (class the-bytes))
(aget ^bytes the-bytes idx)
(.get ^java.nio.ByteBuffer the-bytes (int idx)))))
(when crc-seed
(.update-checksum crc crc-seed))
(.crcValue crc))))
(def mavlink (parse {:xml-sources [{:xml-file "ardupilotmega.xml"
:xml-source (-> "test/resources/ardupilotmega.xml" io/input-stream)}
{:xml-file "common.xml"
:xml-source (-> "test/resources/common.xml" io/input-stream)}
{:xml-file "uAvionix.xml"
:xml-source (-> "test/resources/uAvionix.xml" io/input-stream)}]
:retain-fields? true}))
(deftest clj-mavlink-utilities
(testing "checksums"
(let [s "this is a string test"
byte-string "fe 19 e0 1 1 16 0 0 0 0 93 2 63 0 49 4e 49 54 49 41 4c 5f 4d 4f 44 45 0 0 0 0 2 bb 4c"
len-byte-string (count (clojure.string/split s #" "))
some-bytes (mkbytes byte-string)
buffer (ByteBuffer/wrap some-bytes)
crc-seed (byte 55)
mk-crc-seed (fn [checksum]
(bit-xor (bit-and checksum 0xFF)
(bit-and (bit-shift-right checksum 8) 0xff)))]
(.order buffer ByteOrder/LITTLE_ENDIAN)
this is to make it as much like the Java MAVlink packet as possible .
(is (== (mk-crc-seed (compute-checksum (.getBytes s)))
(compute-crc-checksum s))
"checksum string")
(is (== (compute-crc-checksum some-bytes 0 len-byte-string nil)
(compute-crc-checksum buffer 0 len-byte-string nil))
"checksum byte array with no magic byte")
(is (== (compute-crc-checksum some-bytes 0 len-byte-string crc-seed)
(compute-crc-checksum buffer 0 len-byte-string crc-seed))
"checksum byte array with magic byte")
(is (== (compute-checksum some-bytes 1 15 nil)
(compute-crc-checksum some-bytes 1 15 nil)
(compute-checksum buffer 1 15 nil)
(compute-crc-checksum buffer 1 15 nil))
"checksum byte array 15 bytes no magic byte")
(is (== (compute-checksum some-bytes 1 15 crc-seed)
(compute-crc-checksum some-bytes 1 15 crc-seed)
(compute-checksum buffer 1 15 crc-seed)
(compute-crc-checksum buffer 1 15 crc-seed))
"checksum byte array 15 bytes with magic byte")))
(testing "typed-read-write"
(let [buffer (ByteBuffer/allocate 200)
test-values (atom {})]
(.order buffer ByteOrder/LITTLE_ENDIAN)
(doseq [type-key [:uint64_t :int64_t :double :uint32_t :int32_t
:float :uint16_t :int16_t :uint8_t
:uint8_t_mavlink_version :int8_t :char]
:let [write-fn (type-key write-payload)
test-value (get-test-value type-key 5)]]
(is write-fn
(str "write function not defined for " type-key))
(swap! test-values assoc type-key test-value)
(write-fn buffer test-value))
(.position buffer 0)
(doseq [type-key [:uint64_t :int64_t :double :uint32_t :int32_t
:float :uint16_t :int16_t :uint8_t
:uint8_t_mavlink_version :int8_t :char]
:let [read-fn (type-key read-payload)]]
(is read-fn
(str "read function not defined for " type-key))
(is (= (type-key @test-values)
(read-fn buffer))
(str "roundtrip data write-read for " type-key " failed."))))))
(deftest simple-parser-test
(testing "Testing Simple parsing of enums."
(let [mavlink-simple (parse
{:xml-sources [{:xml-file "test-parse.xml"
:xml-source (-> "test/resources/test-parse.xml" io/input-stream)}]
:retain-fields? true
:descriptions true})]
(is (thrown-with-msg? Exception #"Enum values conflict"
(parse
{:xml-sources [{:xml-file "common.xml"
:xml-source (-> "test/resources/common.xml" io/input-stream)}
{:xml-file "test-parse.xml"
:xml-source (-> "test/resources/test-parse.xml" io/input-stream)}]
:descriptions true})))
(is (= (:enum-to-value mavlink-simple)
{:mav-autopilot-generic 0,
:mav-autopilot-reserved 1,
:mav-autopilot-slugs 2,
:mav-cmd-ack-ok 0,
:mav-cmd-ack-err-fail 1,
:mav-cmd-ack-err-access-denied 2,
:mav-cmd-ack-err-not-supported 3,
:mav-cmd-ack-err-coordinate-frame-not-supported 4,
:mav-cmd-ack-err-coordinates-out-of-range 5,
:mav-cmd-ack-err-x-lat-out-of-range 6,
:mav-cmd-ack-err-y-lon-out-of-range 7,
:mav-cmd-ack-err-z-alt-out-of-range 8,
:mav-type-generic 0,
:mav-type-fixed-wing 1,
:mav-state-uninit 0,
:mav-state-boot 1,
:mav-state-calibrating 2,
:mav-state-standby 3,
:mav-state-active 4,
:mav-state-critical 5,
:mav-state-emergency 6,
:mav-state-poweroff 7
:mav-test-five 5,
:mav-test-six 6,
:mav-test-ten 10
:mav-test-eleven 11})
"Enum-to-value test failed.")
(is (= (:enums-by-group mavlink-simple)
{:mav-test {5 :mav-test-five,
6 :mav-test-six,
10 :mav-test-ten
11 :mav-test-eleven}
:mav-autopilot {0 :mav-autopilot-generic,
1 :mav-autopilot-reserved,
2 :mav-autopilot-slugs},
:mav-cmd-ack {0 :mav-cmd-ack-ok,
1 :mav-cmd-ack-err-fail,
2 :mav-cmd-ack-err-access-denied,
3 :mav-cmd-ack-err-not-supported,
4 :mav-cmd-ack-err-coordinate-frame-not-supported,
5 :mav-cmd-ack-err-coordinates-out-of-range,
6 :mav-cmd-ack-err-x-lat-out-of-range,
7 :mav-cmd-ack-err-y-lon-out-of-range,
8 :mav-cmd-ack-err-z-alt-out-of-range},
:mav-type {0 :mav-type-generic,
1 :mav-type-fixed-wing},
:mav-state {0 :mav-state-uninit,
1 :mav-state-boot,
2 :mav-state-calibrating,
3 :mav-state-standby,
4 :mav-state-active,
5 :mav-state-critical,
6 :mav-state-emergency,
7 :mav-state-poweroff}})
"Enum-by-group test failed")
(is (= (get (:mav-autopilot (:enums-by-group mavlink-simple)) 1) :mav-autopilot-reserved)
"Fetching of enum by its value from enums-by-group failed.")
(is (= (:fld-name (get (:fields (:heartbeat (:messages-by-keyword mavlink-simple))) 3))
"base_mode")
"Fetching type of base-mode from heartbeat messages-by-keyword failed.")
(is (= (:msg-id (:gps-status (:messages-by-keyword mavlink-simple))) 25)
"Fetching id of message from messages-by-keyword failed")
(is (= (:msg-id (get (:messages-by-id mavlink-simple) 25)) 25)
"Fetching id of message from messages-by-id failed")
(is (not (nil? (:mav-autopilot (:descriptions mavlink-simple))))
"Failed to find description")
)))
(deftest mavlink-core
(testing "Testing multi file include."
(is (not (nil? (:uavionix-adsb-out-cfg (:messages-by-keyword mavlink))))
"Include from uAvionix.xml failed.")
(is (not (nil? (:heartbeat (:messages-by-keyword mavlink))))
"Include from common.xml fialed.")
(is (not (nil? (:sensor-offsets (:messages-by-keyword mavlink))))
"Include from ardupilotmega.xml failed."))
(testing "For valid message checksums."
(is (== (-> mavlink :messages-by-keyword :heartbeat :crc-seed) 50)
"Hearbeat magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :sys-status :crc-seed) 124)
"Sys Status magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :change-operator-control :crc-seed) 217)
"Change Operator Control magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :param-set :crc-seed) 168)
"Param Set magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :ping :crc-seed) 237)
"output Raw magic byte checksum.")
(is (== (-> mavlink :messages-by-keyword :servo-output-raw :crc-seed) 222)
"output Raw magic byte checksum.")))
|
24f5e8e738d84d57b0a6e8cdc8268a811896531a191486d751e27a63f6a42751 | mdedwards/slippery-chicken | drawing.lisp | ;;; **********************************************************************
Copyright ( C ) 2004 ( )
;;;
;;; 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.
;;;
;;; **********************************************************************
;;; $Name: rel-2_6_0 $
$ Revision : 1.8 $
$ Date : 2005/01/15 15:50:20 $
;;;
;;; Main window drawing routines
;;;
(in-package :cm)
;;;
;;; provide reasonable defaults for some internal drawing sizes. the
default for * pixels - per - increment * is 60 because that makes it
evenly divisible by many common tick values : 4 , 5 , 6 , 10 , 12 etc .
;;; label-area is the space claimed for the axis lines and
;;; labels. padding is the blank area surrounding the plotting grid on
;;; the top and right.
(defparameter *default-pixels-per-increment* 60)
(defparameter *label-area-width* 60)
(defparameter *label-area-height* 60)
(defparameter *axis-padding* 6)
(defparameter *axis-inset* 12)
(defun free-plotter (plotter)
;; destroy all Tool windows and inspectors....
;;(setq *gtk-open-toplevels*
;; (remove plotter *gtk-open-toplevels*))
(gtk-remove-toplevel plotter)
(dolist (w (plotter-tools plotter))
(if w (gtk:widget-destroy w)))
(dolist (w (plotter-inspectors plotter))
(gtk:widget-destroy w))
;; free up menubar
(slot-makunbound plotter 'menubar)
free up drawing area TODO : free its cached LAYOUT
(when (slot-boundp plotter 'drawing-area)
(let ((darea (plotter-drawing-area plotter)))
;; free up our hand-allocated rect.
(gtk:struct-free (g:object-get-data darea "user_data"))
(slot-makunbound plotter 'drawing-area)))
(slot-makunbound plotter 'x-scroller)
(slot-makunbound plotter 'y-scroller)
;; free up bitmap
(when (slot-boundp plotter 'bitmap)
(g:object-unref (plotter-bitmap plotter))
(slot-makunbound plotter 'bitmap))
TODO : Free up COLORS in colormap with gtk : struct - free
(let ((map (plotting-colormap plotter)))
(g:object-unref map))
(slot-makunbound plotter 'colors)
;; dont need to free window since its being destroyed.
(when (slot-boundp plotter 'window)
;; remove widget from hashtable
(remove-widget (plotter-window plotter))
(slot-makunbound plotter 'window))
(values))
;;; this is the destroy callback. it is triggered by closing the main
window or selecting Layer->Quit from the menubar .
(gtk:define-signal-handler destroy-plotter-window :void (window )
window
(let ((plotter (widget->object window)))
(free-plotter plotter)
;;(if (null *gtk-open-toplevels*)
( progn ( setq * gtk - main * nil )
;; (gtk:main-quit)))
(unless (gtk-open-toplevels?)
(gtk-main-stop))
(values)))
;;;
;;; focus-in-event: move selected plotter to front of open plotter
;;; stack.
(defun focus-plotter () (car *gtk-open-toplevels*))
(gtk:define-signal-handler focus-in-event :int (window event data)
window event data
(let ((plotter (widget->object window)))
(if (and (cdr *gtk-open-toplevels*)
(not (eql plotter (car *gtk-open-toplevels*))))
(rotatef (elt *gtk-open-toplevels* 0)
(elt *gtk-open-toplevels*
(position plotter *gtk-open-toplevels*)))))
gtk:+false+)
(defun erase-bitmap (bitmap gc x y w h)
(gdk:draw-rectangle bitmap gc t x y w h))
(gtk:define-signal-handler configure-event :int (widget event data)
;; widget is drawing area, data is main plotter window.
;; create a new bitmap in response to a resizing of
;; the drawing area. this could be made alot smarter!!!
widget event data
(let* ((plotter (widget->object data))
(bitmap (plotter-bitmap plotter))
(width (gtk:Widget.allocation.width widget))
(height (gtk:Widget.allocation.height widget)))
(when bitmap (g:object-unref bitmap))
(setf bitmap (gdk:pixmap-new (gtk:Widget.window widget)
width height -1))
(setf (plotter-bitmap plotter) bitmap)
(erase-bitmap bitmap (Gtk:Style.white-gc (gtk:Widget.style widget))
0 0 (gtk:Widget.allocation.width widget)
(gtk:Widget.allocation.height widget))
(setf (plotter-draw plotter) t)
gtk:+true+))
;;;
;;; expose-event is the main drawing function. its called whenever the
;;; drawing area is reconfigured or invalidated due to scrolling,
;;; zooming, calling top-level plotter functions, or whatever. If the
plotter 's draw flag is set then expose - event FIRST redraws all
;;; plots onto the offscreen bitmap before updating the visible
;;; display. Once the bitmap contains a valid display expose-event
;;; then copies it onto the drawing area at the current scroll
;;; position with axis lines and labels always maintaing their fixed
;;; positions to the left and bottom of the plotting grid.
;;;
(gtk:define-signal-handler expose-event :int (widget event data)
;; widget is drawing area, data is main window
widget event data
(let* ((plotter (widget->object data))
(selection (plotter-selection plotter))
(bitmap (plotter-bitmap plotter))
(gc (Gtk:Style.fg-gc (gtk:Widget.style widget)
(gtk:Widget.state widget)))
(wgc (Gtk:Style.white-gc (gtk:Widget.style widget)))
(win (gtk:Widget.window widget))
(xscroll (plotter-x-scroller plotter))
(yscroll (plotter-y-scroller plotter))
(xaxis (plotter-x-axis plotter))
(yaxis (plotter-y-axis plotter))
;; xlab is the height below the grid for drawing the x axis
display and ylab is the width to the left of the grid for
;; displaying the y axis and labels.
(xlab (axis-label-area xaxis))
(ylab (axis-label-area yaxis))
xpad and ypad are blank space surrounding the grid
;; this value reduces the extent of the label area.
(xpad *axis-padding*)
(ypad *axis-padding*)
;; screen left, top, width and height are current
;; scoll coordinates.
(sleft (FLOOR (Gtk:Adjustment.value xscroll)))
(stop (FLOOR (Gtk:Adjustment.value yscroll)))
(swidth (FLOOR (Gtk:Adjustment.page-size xscroll)))
(sheight (FLOOR (Gtk:Adjustment.page-size yscroll)))
;; left edge of plotting grid in scroll coords
;;(sgridleft (FLOOR (+ (gtk:adjustment.value xscroll)
;; ylab)))
bottom of plotting grid in scroll coords . takes the min of
;; the y axis-offset and the page-size since the user may
;; have resized the window to be much larger than the plot
;; itself.
(sgridbot (FLOOR (min
(axis-offset yaxis)
(+ (gtk:adjustment.value yscroll)
(gtk:adjustment.page-size yscroll)
(- xlab)))))
;; get our cached rect
(rect (g:object-get-data widget "user_data")))
;; if draw flag is set then draw the plots on the bitmap before
;; copying to drawing area
(let ((draw? (plotter-draw plotter))
(flags (plotter-flags plotter))
(layers (plotter-layers plotter)))
;; as of now draw? is just T but at some point its value will
;; convey info for controlling the layer drawing.
(when draw?
;; make sure we have a plotting gc available. this should
;; really be allocated in main plotter function but
;; (apparently) it cant be created until the drawing area
;; actually has a window :(
;;*moved to plotter-open
;;(unless (plotter-gc plotter)
( setf ( plotter - gc plotter )
( : gc - new ( gtk : Widget.window widget ) ) ) )
;; erase current drawing.
(erase-bitmap bitmap wgc 0 0
(gtk:Widget.allocation.width widget)
(gtk:Widget.allocation.height widget))
;; draw plotting grid underneath the layers if use wants it.
(when (logtest flags +show-grid+)
(draw-graduals plotter :grid))
(when layers
draw background layers first if user want them .
(let ((focus (plotter-front-layer plotter)))
(when (logtest flags +show-back-layers+)
(dolist (p layers)
(unless (eq p focus)
(draw-layer plotter p))))
(draw-layer plotter focus)))
(when selection
(draw-selection plotter selection :redraw NIL))
;; draw axis display
(draw-graduals plotter :axis))
;; clear redraw flag
(setf (plotter-draw plotter) NIL))
;; now get the visible screen area and bitblit the bitmap to the
;; drawing area. the call to begin-paint updates the screen
;; display to offscreen to avoid fickering while scrolling.
(Gdk:Rectangle.x rect sleft)
(Gdk:Rectangle.y rect stop)
(Gdk:Rectangle.width rect swidth)
(Gdk:Rectangle.height rect sheight)
(gdk:window-begin-paint-rect win rect)
Updating the visible screen area is done in three steps :
1 . fill the whole screen area with the exact same area in
;; the plotting bitmap.
2 . copy the bitmap 's axis displays into the left and bottom
;; portions of the screen area.
3 . erase the lower left corner to remove any shifted axis
;; display due to scrolling
(gdk:draw-drawable win gc bitmap sleft stop sleft stop
swidth sheight)
;; copy the Y axis area in the bitmap to the left edge of the
;; screen area
(gdk:draw-drawable win gc bitmap
0
stop
sleft
stop
(- ylab ypad) ;;***
sheight)
;; copy the X axis area that lies just below the gridline in the
bitmap to the corresponding position on the screen . add 1 to
;; avoid including the very bottom grid line in the axis area
(gdk:draw-drawable win gc bitmap
sleft
(+ (+ (axis-offset yaxis) 1) xpad) ;;***
sleft
(+ (+ sgridbot 1) xpad) ;;***
swidth
(- xlab xpad) ;;***
)
;; erase the lower left corner of the displayed area to remove any
;; X/Y axes extending left/below the grid.
(gdk:draw-rectangle win wgc t
sleft
(+ (+ sgridbot 1) xpad) ;;***
(- ylab ypad ) ;***
(- (- xlab 1) xpad) ;***
)
(gdk:window-end-paint win)
gtk:+false+))
;;; draw-graduals draws both the background grid underneath the layers
;;; as well as the axis displays on the left and underneath the
;;; layers. unfortunately, these operations cannot be accomplished in a
;;; single call because gridlines must be drawn 'behind' the layers but
;;; the axis drawing must occur AFTER the layers so that they can clip
;;; overhanging points from appearing as part of the axis displays.
for example , a point with a center at 0,0 will extend into the
axis area by half its diameter but these overhanging pixels should
;;; not appear in the axis display when it is scrolled.
(defun draw-graduals (plotter where)
;; this routine draws both the grid and the axis displays. it
;; calculates everthing in "axis" coordinates and then converts to
;; pixel position only for drawning calls.
(let* ((bitmap (plotter-bitmap plotter))
(gc (plotter-gc plotter))
(ctable (plotter-colors plotter))
(black (drawing-color "black" ctable))
(white (drawing-color "white" ctable))
(gray1 (drawing-color "dark gray" ctable))
(gray2 (drawing-color "light gray" ctable))
(x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
(ybottom (axis-offset y-axis))
(ytop (- ybottom (axis-size y-axis)))
(xleft (axis-offset x-axis))
(xright (+ xleft (axis-size x-axis)))
majc minc ;; major/minor line colors
majl majr majt majb ;; major line coords
minl minr mint minb ;; minor line coords
layout xlabel ylabel)
;; if 'where' is :axis then we are drawing the label display
(if (eq where ':axis)
(let* ((darea (plotter-drawing-area plotter))
;;(rect (g:object-get-data darea "user_data"))
;;(focus (plotter-front-layer plotter))
(inset *axis-inset*)
(lsiz 2))
(setq layout (g:object-get-data darea "layout"))
(setf xlabel (axis-labeler x-axis))
(setf ylabel (axis-labeler y-axis))
;; for axis drawing the major and minor line position are
;; different and line colors are the same
;; try to use the focus layer's color, else black.
(setf majc BLACK minc majc)
(setf majr (- xleft inset) majl (- majr 6)
minr majr minl (- majr 3))
(setf majt (+ ybottom inset) majb (+ majt 6)
mint majt minb (+ majt 3))
;; erase leftward and downward from grid lines to
;; clip overhaning point display. this should be fixed...
(gdk:gc-set-foreground gc white)
(erase-bitmap bitmap gc 0 0 (pixel (- xleft *axis-padding*))
(gtk:Widget.allocation.height darea))
(erase-bitmap bitmap gc 0 (pixel (+ ybottom *axis-padding*))
(gtk:Widget.allocation.width darea)
(gtk:Widget.allocation.height darea))
(gdk:gc-set-foreground gc black)
(gdk:gc-set-line-attributes gc lsiz 0 0 0)
;; draw x axis below
(gdk:draw-line bitmap gc (pixel xleft) (pixel (+ ybottom inset))
(pixel xright) (pixel (+ ybottom inset)))
;; y axis to left
(gdk:draw-line bitmap gc (pixel (- xleft inset)) (pixel ybottom)
(pixel (- xleft inset)) (pixel ytop))
(gdk:gc-set-line-attributes gc 1 0 0 0))
(progn
;; ...else we are drawing the grid itself in which case the
;; major and minor line positions are the same but their
;; colors are different
(setf majc gray1 minc gray2)
(setf majl xleft majr xright majt ytop majb ybottom
minl xleft minr xright mint ytop minb ybottom)))
(gdk:gc-set-foreground gc majc)
dray y axis grid or labeldisplay
(draw-dimension bitmap gc y-axis ylabel majc minc layout
majl majb majr majt
minl minb minr mint)
;; draw x axis grid or label display
(draw-dimension bitmap gc x-axis xlabel majc minc layout
majl majb majr majt
minl minb minr mint)
(gdk:gc-set-foreground gc black)
(values)))
(defun draw-dimension (bitmap gc axis labeler majc minc layout
majl majb majr majt
minl minb minr mint)
;; called to draw the grid or the axis display for each axis the
majl ... are in pixels and represent ' constant ' values
;; from the other axis dimension as this axis is being drawn.
(let* ((vert (eq (axis-orientation axis) ':vertical))
(amin (axis-minimum axis))
(amax (axis-maximum axis))
(arng (- amax amin))
(atpi (axis-ticks-per-increment axis))
(aval amin)
(i 0)
apix)
(unless (axis-draw-labels? axis)
(setq labeler nil))
;; if labeling, right justify vertical and center horizontal
(when labeler
(pango:layout-set-alignment layout
(if vert pango:align-right
pango:align-center)))
(loop do (setq aval (axis-value-at-increment axis i 0))
while (<= aval amax)
do
(setq apix (pixel (axis-pixel aval axis vert NIL)))
(when labeler
(draw-label bitmap gc
(if vert MAJL apix)
(if vert apix MAJB)
layout
(/ (- aval amin) arng)
labeler aval vert))
(gdk:draw-line bitmap gc
(if vert (pixel MAJL) apix)
(if vert apix (pixel MAJB))
(if vert (pixel MAJR) apix)
(if vert apix (pixel MAJT)))
draw light lines or small ticks if more than 1 tick
(when (> atpi 1)
(gdk:gc-set-foreground gc MINC)
(loop for j from 1 below atpi
do (setq aval (axis-value-at-increment axis i j))
while (< aval amax) ; stop if on max line
do
(setq apix (pixel (axis-pixel aval axis vert NIL)))
(gdk:draw-line bitmap gc
(if vert (pixel MINL) apix)
(if vert apix (pixel MINB))
(if vert (pixel MINR) apix)
(if vert apix (pixel MINT))))
(gdk:gc-set-foreground gc majc))
(incf i)
)))
(defun draw-label (bitmap gc x y layout pct labeler value vert)
if vert is true then label is being drawn on y axis . moves
from zero to 1 over the course of the axis drawing and is used to
;; adjust label positions so they remain within the non-clipped
;; regions of the axis displays.
(let ((text (if (stringp labeler)
(format nil labeler value)
(funcall labeler value)))
width height void)
void
(pango:layout-set-text layout text -1)
(multiple-value-setq (void width height)
(pango:layout-get-pixel-size layout 0 0))
(gdk:draw-layout bitmap gc
(if vert (pixel (- x width 4) )
(pixel (- x (* width pct))))
(if vert (pixel (- y (* height (- 1 pct))))
(pixel (+ y 4)))
layout)
(values)))
;;;
;;;
;;;
(defun draw-layer (plotter layer &key (points-filled t) (pen-mode gdk:copy)
points color points-only (dx 0) (dy 0) gc)
(let* ((data (or points (layer-data layer)))
(x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
(x-slots (axis-plotting-slots-for-layer x-axis layer))
(y-slots (axis-plotting-slots-for-layer y-axis layer)))
(if (and data x-slots y-slots)
(let* ((bitmap (plotter-bitmap plotter))
(area (plotter-drawing-area plotter))
(gstyle (plotter-style plotter))
(pstyle (layer-style layer))
(zoomp? (plotter-property plotter :zoom-points))
(zooml? (plotter-property plotter :zoom-lines))
(point-w (floor (* (styling-point-width pstyle gstyle)
(if zoomp? (axis-zoom x-axis)
1))))
(point-h (floor (* (styling-point-height pstyle gstyle)
(if zoomp? (axis-zoom y-axis)
1))))
(linew (floor (* (styling-line-width pstyle gstyle)
(if zooml? (axis-zoom x-axis) 1))))
(view (styling-view pstyle gstyle)))
(declare (ignore area))
(unless gc
(setf gc (plotter-gc plotter)))
(unless color
(setq color (drawing-color (styling-color pstyle gstyle)
(plotter-colors plotter))))
;; set up layers color and line-size
(gdk:gc-set-foreground gc color)
(gdk:gc-set-line-attributes gc linew 0 0 0)
(gdk:gc-set-function gc pen-mode)
( IF ( EQ PEN - MODE : XOR )
( SETQ BITMAP ( GTKWIDGET.WINDOW ( PLOTTER - DRAWING - AREA PLOTTER ) ) ) )
(case view
((:line-and-point :line :point :bar :bar-and-point)
(when points-only (setf view ':point))
(draw-line-and-point bitmap gc x-axis y-axis x-slots y-slots
data point-w point-h linew
points-filled view dx dy))
((:box :bubble)
(draw-box-and-bubble bitmap gc x-axis y-axis x-slots y-slots
data point-w point-h linew
points-filled view dx dy))
(t nil))
(gdk:gc-set-function gc gdk:copy)
))
(values)))
;;;
% 360 is definition of full circle in gtk , where degrees are
measured in increments of 1/64 degree .
;;;
(defconstant %360 (* 360 64))
(defun draw-line-and-point (bitmap gc x-axis y-axis x-slots y-slots
points point-w point-h line-w
filled? view dx dy)
dx dy
(let ((x-slot (car x-slots)) ; ignore width or height slots
(y-slot (car y-slots))
(half-w (floor point-w 2)) ; offset for centering point
(half-h (floor point-h 2))
x1 y1 x2 y2)
(ecase view
(:line-and-point
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx) (- y1 half-h dy)
point-w point-h 0 %360)
(if x2 (gdk:draw-line bitmap gc x2 y2 x1 y1))
(setq x2 x1 y2 y1)))
(:point
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx) (- y1 half-h dy)
point-w point-h 0 %360)))
(:line
(setq x2 (xpixel (car points) x-slot x-axis))
(setq y2 (ypixel (car points) y-slot y-axis))
(dolist (p (cdr points))
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-line bitmap gc x2 y2 x1 y1)
(setq x2 x1 y2 y1)))
((:bar :bar-and-point)
(let* ((min (axis-minimum y-axis))
(max (axis-maximum y-axis))
use zero as origin if at all possible .
(mid (FLOOR (if (or (= min 0) (= max 0)
(< min 0 max)) 0
(/ (- min max) 2))))
;; center bar line too.
(half-l (floor line-w 2)))
(setq y2 (ROUND (axis-pixel mid y-axis t)))
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(if (eq view ':bar-and-point)
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx)
(- y1 half-h dy)
point-w point-h 0 %360))
(gdk:draw-line bitmap gc (- x1 half-l) y1 (- x1 half-l) y2)))))
(values)))
(defun draw-box-and-bubble (bitmap gc x-axis y-axis x-slots y-slots
points point-w point-h line-w
filled? view dx dy)
(declare (ignore line-w ))
(let ((x-slot (car x-slots))
(y-slot (car y-slots))
(w-slot (cadr x-slots))
(h-slot (cadr y-slots))
(half-w (floor point-w 2))
(half-h (floor point-h 2))
(w point-w)
(h point-h)
x y)
(if w-slot
(if h-slot
x , y , w , h
(if (eql view ':bubble)
(dolist (p points)
(setq w (xpixel p w-slot x-axis t))
(setq h (ypixel p h-slot y-axis t))
;; center x and y
(setq x (- (xpixel p x-slot x-axis)
(floor w 2)
dx))
(setq y (- (ypixel p y-slot y-axis)
(floor h 2)
dy))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq h (ypixel p h-slot y-axis t))
(setq y (+ (ypixel p y-slot y-axis)
h))
(setq w (xpixel p w-slot x-axis t))
(gdk:draw-rectangle bitmap gc filled? x y w h)))
;; x,y,w
(if (eql view ':bubble)
(dolist (p points)
(setq w (xpixel p w-slot x-axis t))
(setq h w) ;; hmm, axes better be same!
(setq half-w (floor w 2))
;; center x and y
(setq x (- (xpixel p x-slot x-axis)
dx half-w))
(setq y (- (ypixel p y-slot y-axis)
dy half-h))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq y (ypixel p y-slot y-axis))
(setq w (xpixel p w-slot x-axis t))
(gdk:draw-rectangle bitmap gc filled? (- x dx)
(- y half-h dy)
w h))))
(if h-slot
;; x,y,h
(if (eql view ':bubble)
(dolist (p points)
(setq h (ypixel p h-slot y-axis t))
(setq w h) ;; hmm, axes better be same!
(setq half-h (floor h 2))
;; center x and y
(setq x (- (xpixel p x-slot x-axis)
half-h
dx))
(setq y (- (ypixel p y-slot y-axis)
half-h
dy))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq h (ypixel p h-slot y-axis t)) ;***
(setq y (+ (ypixel p y-slot y-axis)
h))
(gdk:draw-rectangle bitmap gc filled? (- x dx)
(- y dy)
(- w half-w) h)))
nil))))
;;;
;;; main plotter window...
;;;
(defun drawing-color (name colortable)
;; returns a color from the color table given a valid colorname
;; (rgb.text) If the color does not yet exist then allocate it in
;; the colormap.
(or (gethash name colortable)
(let ((colormap (gethash ':colormap colortable)))
(if (stringp name)
(let ((cptr (gtk:struct-alloc :<G>dk<C>olor)))
(if (eql gtk:+false+ (gdk:color-parse name cptr))
(error "Can't parse color ~S." name))
(gdk:colormap-alloc-color colormap cptr t t)
(setf (gethash name colortable) cptr)
cptr)
(error "~S is not a defined color in rgb.text"
name)))))
; (Gtk:Style.font-desc (gtk:Widget.style widget))
; (pango:font-description-to-string fd)
(defun plotting-colormap (plotter)
(gethash ':colormap (plotter-colors plotter)))
(defun allocate-plotting-data (plotter)
;; insure global styling properties, including the color hashtable for
;; fast lookup and the private colormam from which gdk colors are
;; "allocated". insure all layer styles as well.
(let* ((gstyle (plotter-style plotter))
(colormap (gdk:colormap-new (gdk:visual-get-system) t))
(ctable (make-hash-table :test #'equal)))
(setf (plotter-colors plotter) ctable)
store in the table under a special hashkey
(setf (gethash ':colormap ctable) colormap)
;; now allocate colors that plotter itself uses.
(dolist (c '("white" "black" "light gray"
"gray" "dark gray"))
(drawing-color c ctable))
;; allocate the global color if any
(when (%style-color (plotter-style plotter))
(drawing-color (%style-color (plotter-style plotter))
ctable))
;; allocate individual layer colors too.
(dolist (p (plotter-layers plotter))
(when (%style-color (layer-style p))
(drawing-color (%style-color (layer-style p))
ctable)))
;; set the font of the cached label layout to global font.
(let ((layout (g:object-get-data
(plotter-drawing-area plotter)
"layout")))
(pango:layout-set-font-description
layout
(pango:font-description-from-string
(%style-font gstyle))))
(values)))
(defun insure-drawing-sizes (area x-axis y-axis)
(unless (axis-zoom x-axis) (setf (axis-zoom x-axis) 1))
(unless (axis-zoom y-axis) (setf (axis-zoom y-axis) 1))
(unless (axis-pixels-per-increment x-axis)
(setf (axis-pixels-per-increment x-axis)
*default-pixels-per-increment*))
(unless (axis-pixels-per-increment y-axis)
(setf (axis-pixels-per-increment y-axis)
*default-pixels-per-increment*))
(unless (axis-label-area x-axis)
(setf (axis-label-area x-axis) *label-area-height*))
(unless (axis-label-area y-axis)
(setf (axis-label-area y-axis) *label-area-width*))
(let* ((xoffset (axis-label-area x-axis))
(yoffset (axis-label-area y-axis))
(xpad *axis-padding*)
(ypad *axis-padding*)
;; do i still assume this round??
(xextent (ROUND (axis-size x-axis)))
(yextent (ROUND (axis-size y-axis)))
;; padding is added to the left or below the grid and
;; stolen from the label area.
(totalx (+ xoffset xextent xpad))
(totaly (+ yoffset yextent ypad)))
(setf (axis-offset x-axis) xoffset)
(setf (axis-offset y-axis) (- totaly yoffset))
(gtk:widget-set-size-request area totalx totaly)
(values)))
(defun zoom-for-page-size (axis scroller)
(let* ((offset (axis-label-area axis))
(pagesz (Gtk:Adjustment.page-size scroller))
(extent (- pagesz (+ *axis-padding* offset))))
;; extent=zoom*ppi*increments
;; zoom=extent/(ppi*increments)
(/ extent (* (axis-increments axis)
(axis-pixels-per-increment axis)))))
;;;
;;; top-level plotter functions
;;;
(defun display-plotter (plotter)
make sure gtk is inited before doing anything .
allocate gtk structures
(let ((x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
window hints mask vbox menubar scrolled drawing-area )
(setq window (gtk:window-new gtk:window-toplevel))
( gtk : widget - set - size - request window 400 400 )
;; link our plotter object to the new main window. we will pass
;; the window as user data to all the plotting callbacks so the
;; various drawing routines can quickly access any info they might
;; need.
(setf (widget->object window) plotter)
(setf (plotter-window plotter) window)
(gtk:window-set-title window (or (object-name plotter) ""))
now set some geometry in an attempt to stop a random GDK error
message about a null window from some geometry functin . this
;; error only seems to happen when menus are added.
(setq hints (gtk:struct-alloc :<G>dk<G>eometry
:min_width 400 :min_height 400
:max_width -1 :max_height -1))
(setq mask (logior gdk:hint-min-size)) ; just min for now
(gtk:window-set-geometry-hints window (g:nullptr) hints mask)
(gtk:container-set-border-width window 5)
(g:signal-connect window "destroy"
(g:callback destroy-plotter-window)
window)
create vbox to partition window into menubar , drawing area ,
and buffer ( not yet implmented )
(setq vbox (gtk:vbox-new nil 5))
(gtk:container-add window vbox)
try telling the vbox its size before menues are added .
(gtk:window-set-geometry-hints window vbox hints mask)
(gtk:widget-show vbox)
create menubar and add to top of
(setq menubar (create-menubar *menubar* window vbox))
(setf (plotter-menubar plotter) menubar)
;; create drawing area. drawing signal handlers are passed main
;; window as user data
(setq drawing-area (gtk:drawing-area-new))
(setf (plotter-drawing-area plotter) drawing-area)
(setf (plotter-bitmap plotter) nil)
;; set values in pixel slots of axes and resize the drawing area
;; to fit the plotting geometry
(insure-drawing-sizes drawing-area x-axis y-axis)
(gtk:widget-show drawing-area)
(g:signal-connect drawing-area "expose_event"
(g:callback expose-event)
window)
(g:signal-connect drawing-area "configure_event"
(g:callback configure-event)
window)
(g:signal-connect drawing-area "button_press_event"
(g:callback button-press-event) window)
(g:signal-connect drawing-area "button_release_event"
(g:callback button-release-event) window)
(g:signal-connect drawing-area "motion_notify_event"
(g:callback motion-notify-event) window)
(g:signal-connect window "key_press_event"
(g:callback key-press-event) window)
;; cache a rect for expose_event to use.
(g:object-set-data drawing-area "user_data"
(gtk:struct-alloc :<G>dk<R>ectangle))
;; create a pango layout for drawing axis labels and cache it in
;; the drawing-area.
(g:object-set-data drawing-area "layout"
(gtk:widget-create-pango-layout drawing-area ""))
(gtk:widget-set-events drawing-area
(logior gdk:exposure-mask
gdk:leave-notify-mask
gdk:button-press-mask
gdk:button-release-mask
gdk:pointer-motion-mask
gdk:pointer-motion-hint-mask
))
(gtk:widget-set-events window gdk:focus-change-mask)
(g:signal-connect window "focus_in_event"
(g:callback focus-in-event) window)
;; create scrolled window and add drawing area to it
(setq scrolled (gtk:scrolled-window-new
(g:nullptr) (g:nullptr)))
(gtk:widget-show scrolled)
(gtk:scrolled-window-add-with-viewport scrolled drawing-area)
(gtk:scrolled-window-set-policy scrolled
gtk:policy-always
gtk:policy-always)
;; cache the scrollers and set their step increment
;; to the tick size.
(let ((hscroll (gtk:scrolled-window-get-hadjustment scrolled))
(vscroll (gtk:scrolled-window-get-vadjustment scrolled)))
(setf (plotter-x-scroller plotter) hscroll
(plotter-y-scroller plotter) vscroll)
;; n.b. fix the accessors!
(Gtk:Adjustment.step-increment
hscroll (coerce (axis-tick-size x-axis)'double-float))
(gtk:adjustment-changed hscroll)
(Gtk:Adjustment.step-increment
vscroll (coerce (axis-tick-size y-axis) 'double-float))
(gtk:adjustment-changed vscroll))
add scroller to
(gtk:box-pack-start vbox scrolled t t 0)
allocate private colormap , gc , plotting colors etc .
(allocate-plotting-data plotter)
(setf (plotter-draw plotter) t)
;; ensure mode starts as :select-points
(setf (mouseinfo-mode (plotter-mouseinfo plotter)) :select-points)
(gtk:widget-show window)
;; do this here so darea has window?
(setf (plotter-gc plotter)
(gdk:gc-new (gtk:Widget.window drawing-area)))
scroll to origin on
(plotter-scroll plotter :y 1)
;; start main loop if necessary
(push plotter *gtk-open-toplevels*)
;;(unless *gtk-main*
;;(setq *gtk-main* t)
( gtk : main ) )
(gtk-main-start) ; support.lisp
(values)))
(defun plotter-zoom (plotter &key x y )
;; get/set the curren zoom values of plotter
;; if x or y are T then calculate zoom to fit
;; current scrolling page size.
(let ((x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter)))
(when x
(when (eq x t)
(setf x (zoom-for-page-size x-axis
(plotter-x-scroller plotter))))
(if (and (numberp x) (> x 0))
(setf (axis-zoom x-axis) x)
(error "Zoom scaler not a positive number: ~S."
x)))
(when y
(when (eq y t)
(setf y (zoom-for-page-size y-axis
(plotter-y-scroller plotter))))
(if (and (numberp y) (> y 0))
(setf (axis-zoom y-axis) y)
(error "Zoom scaler not a positive number: ~S."
y)))
(when (or x y)
(insure-drawing-sizes (plotter-drawing-area plotter)
x-axis y-axis))
(values (axis-zoom x-axis)
(axis-zoom y-axis))))
(defun plotter-redraw (plotter &optional (redraw t))
;; signal plotter's drawing area to redraw plots.
(when redraw
(setf (plotter-draw plotter) redraw))
(let ((area (plotter-drawing-area plotter)))
(gtk:widget-queue-draw area))
(values))
(defun plotter-close (plotter)
(gtk:widget-destroy (plotter-window plotter)))
(defun plotter-resize (plotter &key width height)
plotter width height
())
(defun plotter-title (plotter &optional title)
(let ((win (plotter-window plotter)))
(if title
(progn (gtk:window-set-title win title)
title)
(gtk:window-get-title win))))
(defun plotter-scroll (pw &key x y)
(let (h v r)
(when x
(setq h (plotter-x-scroller pw))
(setq x (max (min x 1) 0))
(setq r (- (Gtk:Adjustment.upper h)
(Gtk:Adjustment.page-size h)))
(gtk:adjustment-set-value h (* r x))
(gtk:adjustment-value-changed h))
(when y
(setq v (plotter-y-scroller pw))
(setq y (max (min y 1) 0))
(setq r (- (Gtk:Adjustment.upper v)
(Gtk:Adjustment.page-size v)))
(gtk:adjustment-set-value v (* r y))
(gtk:adjustment-value-changed v))
(values)))
| null | https://raw.githubusercontent.com/mdedwards/slippery-chicken/c1c11fadcdb40cd869d5b29091ba5e53c5270e04/src/cm-2.6.0/src/gui/drawing.lisp | lisp | **********************************************************************
This program is free software; you can redistribute it and/or
either version 2
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.
**********************************************************************
$Name: rel-2_6_0 $
Main window drawing routines
provide reasonable defaults for some internal drawing sizes. the
label-area is the space claimed for the axis lines and
labels. padding is the blank area surrounding the plotting grid on
the top and right.
destroy all Tool windows and inspectors....
(setq *gtk-open-toplevels*
(remove plotter *gtk-open-toplevels*))
free up menubar
free up our hand-allocated rect.
free up bitmap
dont need to free window since its being destroyed.
remove widget from hashtable
this is the destroy callback. it is triggered by closing the main
(if (null *gtk-open-toplevels*)
(gtk:main-quit)))
focus-in-event: move selected plotter to front of open plotter
stack.
widget is drawing area, data is main plotter window.
create a new bitmap in response to a resizing of
the drawing area. this could be made alot smarter!!!
expose-event is the main drawing function. its called whenever the
drawing area is reconfigured or invalidated due to scrolling,
zooming, calling top-level plotter functions, or whatever. If the
plots onto the offscreen bitmap before updating the visible
display. Once the bitmap contains a valid display expose-event
then copies it onto the drawing area at the current scroll
position with axis lines and labels always maintaing their fixed
positions to the left and bottom of the plotting grid.
widget is drawing area, data is main window
xlab is the height below the grid for drawing the x axis
displaying the y axis and labels.
this value reduces the extent of the label area.
screen left, top, width and height are current
scoll coordinates.
left edge of plotting grid in scroll coords
(sgridleft (FLOOR (+ (gtk:adjustment.value xscroll)
ylab)))
the y axis-offset and the page-size since the user may
have resized the window to be much larger than the plot
itself.
get our cached rect
if draw flag is set then draw the plots on the bitmap before
copying to drawing area
as of now draw? is just T but at some point its value will
convey info for controlling the layer drawing.
make sure we have a plotting gc available. this should
really be allocated in main plotter function but
(apparently) it cant be created until the drawing area
actually has a window :(
*moved to plotter-open
(unless (plotter-gc plotter)
erase current drawing.
draw plotting grid underneath the layers if use wants it.
draw axis display
clear redraw flag
now get the visible screen area and bitblit the bitmap to the
drawing area. the call to begin-paint updates the screen
display to offscreen to avoid fickering while scrolling.
the plotting bitmap.
portions of the screen area.
display due to scrolling
copy the Y axis area in the bitmap to the left edge of the
screen area
***
copy the X axis area that lies just below the gridline in the
avoid including the very bottom grid line in the axis area
***
***
***
erase the lower left corner of the displayed area to remove any
X/Y axes extending left/below the grid.
***
***
***
draw-graduals draws both the background grid underneath the layers
as well as the axis displays on the left and underneath the
layers. unfortunately, these operations cannot be accomplished in a
single call because gridlines must be drawn 'behind' the layers but
the axis drawing must occur AFTER the layers so that they can clip
overhanging points from appearing as part of the axis displays.
not appear in the axis display when it is scrolled.
this routine draws both the grid and the axis displays. it
calculates everthing in "axis" coordinates and then converts to
pixel position only for drawning calls.
major/minor line colors
major line coords
minor line coords
if 'where' is :axis then we are drawing the label display
(rect (g:object-get-data darea "user_data"))
(focus (plotter-front-layer plotter))
for axis drawing the major and minor line position are
different and line colors are the same
try to use the focus layer's color, else black.
erase leftward and downward from grid lines to
clip overhaning point display. this should be fixed...
draw x axis below
y axis to left
...else we are drawing the grid itself in which case the
major and minor line positions are the same but their
colors are different
draw x axis grid or label display
called to draw the grid or the axis display for each axis the
from the other axis dimension as this axis is being drawn.
if labeling, right justify vertical and center horizontal
stop if on max line
adjust label positions so they remain within the non-clipped
regions of the axis displays.
set up layers color and line-size
ignore width or height slots
offset for centering point
center bar line too.
center x and y
x,y,w
hmm, axes better be same!
center x and y
x,y,h
hmm, axes better be same!
center x and y
***
main plotter window...
returns a color from the color table given a valid colorname
(rgb.text) If the color does not yet exist then allocate it in
the colormap.
(Gtk:Style.font-desc (gtk:Widget.style widget))
(pango:font-description-to-string fd)
insure global styling properties, including the color hashtable for
fast lookup and the private colormam from which gdk colors are
"allocated". insure all layer styles as well.
now allocate colors that plotter itself uses.
allocate the global color if any
allocate individual layer colors too.
set the font of the cached label layout to global font.
do i still assume this round??
padding is added to the left or below the grid and
stolen from the label area.
extent=zoom*ppi*increments
zoom=extent/(ppi*increments)
top-level plotter functions
link our plotter object to the new main window. we will pass
the window as user data to all the plotting callbacks so the
various drawing routines can quickly access any info they might
need.
error only seems to happen when menus are added.
just min for now
create drawing area. drawing signal handlers are passed main
window as user data
set values in pixel slots of axes and resize the drawing area
to fit the plotting geometry
cache a rect for expose_event to use.
create a pango layout for drawing axis labels and cache it in
the drawing-area.
create scrolled window and add drawing area to it
cache the scrollers and set their step increment
to the tick size.
n.b. fix the accessors!
ensure mode starts as :select-points
do this here so darea has window?
start main loop if necessary
(unless *gtk-main*
(setq *gtk-main* t)
support.lisp
get/set the curren zoom values of plotter
if x or y are T then calculate zoom to fit
current scrolling page size.
signal plotter's drawing area to redraw plots. | Copyright ( C ) 2004 ( )
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
$ Revision : 1.8 $
$ Date : 2005/01/15 15:50:20 $
(in-package :cm)
default for * pixels - per - increment * is 60 because that makes it
evenly divisible by many common tick values : 4 , 5 , 6 , 10 , 12 etc .
(defparameter *default-pixels-per-increment* 60)
(defparameter *label-area-width* 60)
(defparameter *label-area-height* 60)
(defparameter *axis-padding* 6)
(defparameter *axis-inset* 12)
(defun free-plotter (plotter)
(gtk-remove-toplevel plotter)
(dolist (w (plotter-tools plotter))
(if w (gtk:widget-destroy w)))
(dolist (w (plotter-inspectors plotter))
(gtk:widget-destroy w))
(slot-makunbound plotter 'menubar)
free up drawing area TODO : free its cached LAYOUT
(when (slot-boundp plotter 'drawing-area)
(let ((darea (plotter-drawing-area plotter)))
(gtk:struct-free (g:object-get-data darea "user_data"))
(slot-makunbound plotter 'drawing-area)))
(slot-makunbound plotter 'x-scroller)
(slot-makunbound plotter 'y-scroller)
(when (slot-boundp plotter 'bitmap)
(g:object-unref (plotter-bitmap plotter))
(slot-makunbound plotter 'bitmap))
TODO : Free up COLORS in colormap with gtk : struct - free
(let ((map (plotting-colormap plotter)))
(g:object-unref map))
(slot-makunbound plotter 'colors)
(when (slot-boundp plotter 'window)
(remove-widget (plotter-window plotter))
(slot-makunbound plotter 'window))
(values))
window or selecting Layer->Quit from the menubar .
(gtk:define-signal-handler destroy-plotter-window :void (window )
window
(let ((plotter (widget->object window)))
(free-plotter plotter)
( progn ( setq * gtk - main * nil )
(unless (gtk-open-toplevels?)
(gtk-main-stop))
(values)))
(defun focus-plotter () (car *gtk-open-toplevels*))
(gtk:define-signal-handler focus-in-event :int (window event data)
window event data
(let ((plotter (widget->object window)))
(if (and (cdr *gtk-open-toplevels*)
(not (eql plotter (car *gtk-open-toplevels*))))
(rotatef (elt *gtk-open-toplevels* 0)
(elt *gtk-open-toplevels*
(position plotter *gtk-open-toplevels*)))))
gtk:+false+)
(defun erase-bitmap (bitmap gc x y w h)
(gdk:draw-rectangle bitmap gc t x y w h))
(gtk:define-signal-handler configure-event :int (widget event data)
widget event data
(let* ((plotter (widget->object data))
(bitmap (plotter-bitmap plotter))
(width (gtk:Widget.allocation.width widget))
(height (gtk:Widget.allocation.height widget)))
(when bitmap (g:object-unref bitmap))
(setf bitmap (gdk:pixmap-new (gtk:Widget.window widget)
width height -1))
(setf (plotter-bitmap plotter) bitmap)
(erase-bitmap bitmap (Gtk:Style.white-gc (gtk:Widget.style widget))
0 0 (gtk:Widget.allocation.width widget)
(gtk:Widget.allocation.height widget))
(setf (plotter-draw plotter) t)
gtk:+true+))
plotter 's draw flag is set then expose - event FIRST redraws all
(gtk:define-signal-handler expose-event :int (widget event data)
widget event data
(let* ((plotter (widget->object data))
(selection (plotter-selection plotter))
(bitmap (plotter-bitmap plotter))
(gc (Gtk:Style.fg-gc (gtk:Widget.style widget)
(gtk:Widget.state widget)))
(wgc (Gtk:Style.white-gc (gtk:Widget.style widget)))
(win (gtk:Widget.window widget))
(xscroll (plotter-x-scroller plotter))
(yscroll (plotter-y-scroller plotter))
(xaxis (plotter-x-axis plotter))
(yaxis (plotter-y-axis plotter))
display and ylab is the width to the left of the grid for
(xlab (axis-label-area xaxis))
(ylab (axis-label-area yaxis))
xpad and ypad are blank space surrounding the grid
(xpad *axis-padding*)
(ypad *axis-padding*)
(sleft (FLOOR (Gtk:Adjustment.value xscroll)))
(stop (FLOOR (Gtk:Adjustment.value yscroll)))
(swidth (FLOOR (Gtk:Adjustment.page-size xscroll)))
(sheight (FLOOR (Gtk:Adjustment.page-size yscroll)))
bottom of plotting grid in scroll coords . takes the min of
(sgridbot (FLOOR (min
(axis-offset yaxis)
(+ (gtk:adjustment.value yscroll)
(gtk:adjustment.page-size yscroll)
(- xlab)))))
(rect (g:object-get-data widget "user_data")))
(let ((draw? (plotter-draw plotter))
(flags (plotter-flags plotter))
(layers (plotter-layers plotter)))
(when draw?
( setf ( plotter - gc plotter )
( : gc - new ( gtk : Widget.window widget ) ) ) )
(erase-bitmap bitmap wgc 0 0
(gtk:Widget.allocation.width widget)
(gtk:Widget.allocation.height widget))
(when (logtest flags +show-grid+)
(draw-graduals plotter :grid))
(when layers
draw background layers first if user want them .
(let ((focus (plotter-front-layer plotter)))
(when (logtest flags +show-back-layers+)
(dolist (p layers)
(unless (eq p focus)
(draw-layer plotter p))))
(draw-layer plotter focus)))
(when selection
(draw-selection plotter selection :redraw NIL))
(draw-graduals plotter :axis))
(setf (plotter-draw plotter) NIL))
(Gdk:Rectangle.x rect sleft)
(Gdk:Rectangle.y rect stop)
(Gdk:Rectangle.width rect swidth)
(Gdk:Rectangle.height rect sheight)
(gdk:window-begin-paint-rect win rect)
Updating the visible screen area is done in three steps :
1 . fill the whole screen area with the exact same area in
2 . copy the bitmap 's axis displays into the left and bottom
3 . erase the lower left corner to remove any shifted axis
(gdk:draw-drawable win gc bitmap sleft stop sleft stop
swidth sheight)
(gdk:draw-drawable win gc bitmap
0
stop
sleft
stop
sheight)
bitmap to the corresponding position on the screen . add 1 to
(gdk:draw-drawable win gc bitmap
sleft
sleft
swidth
)
(gdk:draw-rectangle win wgc t
sleft
)
(gdk:window-end-paint win)
gtk:+false+))
for example , a point with a center at 0,0 will extend into the
axis area by half its diameter but these overhanging pixels should
(defun draw-graduals (plotter where)
(let* ((bitmap (plotter-bitmap plotter))
(gc (plotter-gc plotter))
(ctable (plotter-colors plotter))
(black (drawing-color "black" ctable))
(white (drawing-color "white" ctable))
(gray1 (drawing-color "dark gray" ctable))
(gray2 (drawing-color "light gray" ctable))
(x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
(ybottom (axis-offset y-axis))
(ytop (- ybottom (axis-size y-axis)))
(xleft (axis-offset x-axis))
(xright (+ xleft (axis-size x-axis)))
layout xlabel ylabel)
(if (eq where ':axis)
(let* ((darea (plotter-drawing-area plotter))
(inset *axis-inset*)
(lsiz 2))
(setq layout (g:object-get-data darea "layout"))
(setf xlabel (axis-labeler x-axis))
(setf ylabel (axis-labeler y-axis))
(setf majc BLACK minc majc)
(setf majr (- xleft inset) majl (- majr 6)
minr majr minl (- majr 3))
(setf majt (+ ybottom inset) majb (+ majt 6)
mint majt minb (+ majt 3))
(gdk:gc-set-foreground gc white)
(erase-bitmap bitmap gc 0 0 (pixel (- xleft *axis-padding*))
(gtk:Widget.allocation.height darea))
(erase-bitmap bitmap gc 0 (pixel (+ ybottom *axis-padding*))
(gtk:Widget.allocation.width darea)
(gtk:Widget.allocation.height darea))
(gdk:gc-set-foreground gc black)
(gdk:gc-set-line-attributes gc lsiz 0 0 0)
(gdk:draw-line bitmap gc (pixel xleft) (pixel (+ ybottom inset))
(pixel xright) (pixel (+ ybottom inset)))
(gdk:draw-line bitmap gc (pixel (- xleft inset)) (pixel ybottom)
(pixel (- xleft inset)) (pixel ytop))
(gdk:gc-set-line-attributes gc 1 0 0 0))
(progn
(setf majc gray1 minc gray2)
(setf majl xleft majr xright majt ytop majb ybottom
minl xleft minr xright mint ytop minb ybottom)))
(gdk:gc-set-foreground gc majc)
dray y axis grid or labeldisplay
(draw-dimension bitmap gc y-axis ylabel majc minc layout
majl majb majr majt
minl minb minr mint)
(draw-dimension bitmap gc x-axis xlabel majc minc layout
majl majb majr majt
minl minb minr mint)
(gdk:gc-set-foreground gc black)
(values)))
(defun draw-dimension (bitmap gc axis labeler majc minc layout
majl majb majr majt
minl minb minr mint)
majl ... are in pixels and represent ' constant ' values
(let* ((vert (eq (axis-orientation axis) ':vertical))
(amin (axis-minimum axis))
(amax (axis-maximum axis))
(arng (- amax amin))
(atpi (axis-ticks-per-increment axis))
(aval amin)
(i 0)
apix)
(unless (axis-draw-labels? axis)
(setq labeler nil))
(when labeler
(pango:layout-set-alignment layout
(if vert pango:align-right
pango:align-center)))
(loop do (setq aval (axis-value-at-increment axis i 0))
while (<= aval amax)
do
(setq apix (pixel (axis-pixel aval axis vert NIL)))
(when labeler
(draw-label bitmap gc
(if vert MAJL apix)
(if vert apix MAJB)
layout
(/ (- aval amin) arng)
labeler aval vert))
(gdk:draw-line bitmap gc
(if vert (pixel MAJL) apix)
(if vert apix (pixel MAJB))
(if vert (pixel MAJR) apix)
(if vert apix (pixel MAJT)))
draw light lines or small ticks if more than 1 tick
(when (> atpi 1)
(gdk:gc-set-foreground gc MINC)
(loop for j from 1 below atpi
do (setq aval (axis-value-at-increment axis i j))
do
(setq apix (pixel (axis-pixel aval axis vert NIL)))
(gdk:draw-line bitmap gc
(if vert (pixel MINL) apix)
(if vert apix (pixel MINB))
(if vert (pixel MINR) apix)
(if vert apix (pixel MINT))))
(gdk:gc-set-foreground gc majc))
(incf i)
)))
(defun draw-label (bitmap gc x y layout pct labeler value vert)
if vert is true then label is being drawn on y axis . moves
from zero to 1 over the course of the axis drawing and is used to
(let ((text (if (stringp labeler)
(format nil labeler value)
(funcall labeler value)))
width height void)
void
(pango:layout-set-text layout text -1)
(multiple-value-setq (void width height)
(pango:layout-get-pixel-size layout 0 0))
(gdk:draw-layout bitmap gc
(if vert (pixel (- x width 4) )
(pixel (- x (* width pct))))
(if vert (pixel (- y (* height (- 1 pct))))
(pixel (+ y 4)))
layout)
(values)))
(defun draw-layer (plotter layer &key (points-filled t) (pen-mode gdk:copy)
points color points-only (dx 0) (dy 0) gc)
(let* ((data (or points (layer-data layer)))
(x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
(x-slots (axis-plotting-slots-for-layer x-axis layer))
(y-slots (axis-plotting-slots-for-layer y-axis layer)))
(if (and data x-slots y-slots)
(let* ((bitmap (plotter-bitmap plotter))
(area (plotter-drawing-area plotter))
(gstyle (plotter-style plotter))
(pstyle (layer-style layer))
(zoomp? (plotter-property plotter :zoom-points))
(zooml? (plotter-property plotter :zoom-lines))
(point-w (floor (* (styling-point-width pstyle gstyle)
(if zoomp? (axis-zoom x-axis)
1))))
(point-h (floor (* (styling-point-height pstyle gstyle)
(if zoomp? (axis-zoom y-axis)
1))))
(linew (floor (* (styling-line-width pstyle gstyle)
(if zooml? (axis-zoom x-axis) 1))))
(view (styling-view pstyle gstyle)))
(declare (ignore area))
(unless gc
(setf gc (plotter-gc plotter)))
(unless color
(setq color (drawing-color (styling-color pstyle gstyle)
(plotter-colors plotter))))
(gdk:gc-set-foreground gc color)
(gdk:gc-set-line-attributes gc linew 0 0 0)
(gdk:gc-set-function gc pen-mode)
( IF ( EQ PEN - MODE : XOR )
( SETQ BITMAP ( GTKWIDGET.WINDOW ( PLOTTER - DRAWING - AREA PLOTTER ) ) ) )
(case view
((:line-and-point :line :point :bar :bar-and-point)
(when points-only (setf view ':point))
(draw-line-and-point bitmap gc x-axis y-axis x-slots y-slots
data point-w point-h linew
points-filled view dx dy))
((:box :bubble)
(draw-box-and-bubble bitmap gc x-axis y-axis x-slots y-slots
data point-w point-h linew
points-filled view dx dy))
(t nil))
(gdk:gc-set-function gc gdk:copy)
))
(values)))
% 360 is definition of full circle in gtk , where degrees are
measured in increments of 1/64 degree .
(defconstant %360 (* 360 64))
(defun draw-line-and-point (bitmap gc x-axis y-axis x-slots y-slots
points point-w point-h line-w
filled? view dx dy)
dx dy
(y-slot (car y-slots))
(half-h (floor point-h 2))
x1 y1 x2 y2)
(ecase view
(:line-and-point
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx) (- y1 half-h dy)
point-w point-h 0 %360)
(if x2 (gdk:draw-line bitmap gc x2 y2 x1 y1))
(setq x2 x1 y2 y1)))
(:point
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx) (- y1 half-h dy)
point-w point-h 0 %360)))
(:line
(setq x2 (xpixel (car points) x-slot x-axis))
(setq y2 (ypixel (car points) y-slot y-axis))
(dolist (p (cdr points))
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(gdk:draw-line bitmap gc x2 y2 x1 y1)
(setq x2 x1 y2 y1)))
((:bar :bar-and-point)
(let* ((min (axis-minimum y-axis))
(max (axis-maximum y-axis))
use zero as origin if at all possible .
(mid (FLOOR (if (or (= min 0) (= max 0)
(< min 0 max)) 0
(/ (- min max) 2))))
(half-l (floor line-w 2)))
(setq y2 (ROUND (axis-pixel mid y-axis t)))
(dolist (p points)
(setq x1 (xpixel p x-slot x-axis))
(setq y1 (ypixel p y-slot y-axis))
(if (eq view ':bar-and-point)
(gdk:draw-arc bitmap gc filled? (- x1 half-w dx)
(- y1 half-h dy)
point-w point-h 0 %360))
(gdk:draw-line bitmap gc (- x1 half-l) y1 (- x1 half-l) y2)))))
(values)))
(defun draw-box-and-bubble (bitmap gc x-axis y-axis x-slots y-slots
points point-w point-h line-w
filled? view dx dy)
(declare (ignore line-w ))
(let ((x-slot (car x-slots))
(y-slot (car y-slots))
(w-slot (cadr x-slots))
(h-slot (cadr y-slots))
(half-w (floor point-w 2))
(half-h (floor point-h 2))
(w point-w)
(h point-h)
x y)
(if w-slot
(if h-slot
x , y , w , h
(if (eql view ':bubble)
(dolist (p points)
(setq w (xpixel p w-slot x-axis t))
(setq h (ypixel p h-slot y-axis t))
(setq x (- (xpixel p x-slot x-axis)
(floor w 2)
dx))
(setq y (- (ypixel p y-slot y-axis)
(floor h 2)
dy))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq h (ypixel p h-slot y-axis t))
(setq y (+ (ypixel p y-slot y-axis)
h))
(setq w (xpixel p w-slot x-axis t))
(gdk:draw-rectangle bitmap gc filled? x y w h)))
(if (eql view ':bubble)
(dolist (p points)
(setq w (xpixel p w-slot x-axis t))
(setq half-w (floor w 2))
(setq x (- (xpixel p x-slot x-axis)
dx half-w))
(setq y (- (ypixel p y-slot y-axis)
dy half-h))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq y (ypixel p y-slot y-axis))
(setq w (xpixel p w-slot x-axis t))
(gdk:draw-rectangle bitmap gc filled? (- x dx)
(- y half-h dy)
w h))))
(if h-slot
(if (eql view ':bubble)
(dolist (p points)
(setq h (ypixel p h-slot y-axis t))
(setq half-h (floor h 2))
(setq x (- (xpixel p x-slot x-axis)
half-h
dx))
(setq y (- (ypixel p y-slot y-axis)
half-h
dy))
(gdk:draw-arc bitmap gc filled? x y w h 0 %360))
(dolist (p points)
(setq x (xpixel p x-slot x-axis))
(setq y (+ (ypixel p y-slot y-axis)
h))
(gdk:draw-rectangle bitmap gc filled? (- x dx)
(- y dy)
(- w half-w) h)))
nil))))
(defun drawing-color (name colortable)
(or (gethash name colortable)
(let ((colormap (gethash ':colormap colortable)))
(if (stringp name)
(let ((cptr (gtk:struct-alloc :<G>dk<C>olor)))
(if (eql gtk:+false+ (gdk:color-parse name cptr))
(error "Can't parse color ~S." name))
(gdk:colormap-alloc-color colormap cptr t t)
(setf (gethash name colortable) cptr)
cptr)
(error "~S is not a defined color in rgb.text"
name)))))
(defun plotting-colormap (plotter)
(gethash ':colormap (plotter-colors plotter)))
(defun allocate-plotting-data (plotter)
(let* ((gstyle (plotter-style plotter))
(colormap (gdk:colormap-new (gdk:visual-get-system) t))
(ctable (make-hash-table :test #'equal)))
(setf (plotter-colors plotter) ctable)
store in the table under a special hashkey
(setf (gethash ':colormap ctable) colormap)
(dolist (c '("white" "black" "light gray"
"gray" "dark gray"))
(drawing-color c ctable))
(when (%style-color (plotter-style plotter))
(drawing-color (%style-color (plotter-style plotter))
ctable))
(dolist (p (plotter-layers plotter))
(when (%style-color (layer-style p))
(drawing-color (%style-color (layer-style p))
ctable)))
(let ((layout (g:object-get-data
(plotter-drawing-area plotter)
"layout")))
(pango:layout-set-font-description
layout
(pango:font-description-from-string
(%style-font gstyle))))
(values)))
(defun insure-drawing-sizes (area x-axis y-axis)
(unless (axis-zoom x-axis) (setf (axis-zoom x-axis) 1))
(unless (axis-zoom y-axis) (setf (axis-zoom y-axis) 1))
(unless (axis-pixels-per-increment x-axis)
(setf (axis-pixels-per-increment x-axis)
*default-pixels-per-increment*))
(unless (axis-pixels-per-increment y-axis)
(setf (axis-pixels-per-increment y-axis)
*default-pixels-per-increment*))
(unless (axis-label-area x-axis)
(setf (axis-label-area x-axis) *label-area-height*))
(unless (axis-label-area y-axis)
(setf (axis-label-area y-axis) *label-area-width*))
(let* ((xoffset (axis-label-area x-axis))
(yoffset (axis-label-area y-axis))
(xpad *axis-padding*)
(ypad *axis-padding*)
(xextent (ROUND (axis-size x-axis)))
(yextent (ROUND (axis-size y-axis)))
(totalx (+ xoffset xextent xpad))
(totaly (+ yoffset yextent ypad)))
(setf (axis-offset x-axis) xoffset)
(setf (axis-offset y-axis) (- totaly yoffset))
(gtk:widget-set-size-request area totalx totaly)
(values)))
(defun zoom-for-page-size (axis scroller)
(let* ((offset (axis-label-area axis))
(pagesz (Gtk:Adjustment.page-size scroller))
(extent (- pagesz (+ *axis-padding* offset))))
(/ extent (* (axis-increments axis)
(axis-pixels-per-increment axis)))))
(defun display-plotter (plotter)
make sure gtk is inited before doing anything .
allocate gtk structures
(let ((x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter))
window hints mask vbox menubar scrolled drawing-area )
(setq window (gtk:window-new gtk:window-toplevel))
( gtk : widget - set - size - request window 400 400 )
(setf (widget->object window) plotter)
(setf (plotter-window plotter) window)
(gtk:window-set-title window (or (object-name plotter) ""))
now set some geometry in an attempt to stop a random GDK error
message about a null window from some geometry functin . this
(setq hints (gtk:struct-alloc :<G>dk<G>eometry
:min_width 400 :min_height 400
:max_width -1 :max_height -1))
(gtk:window-set-geometry-hints window (g:nullptr) hints mask)
(gtk:container-set-border-width window 5)
(g:signal-connect window "destroy"
(g:callback destroy-plotter-window)
window)
create vbox to partition window into menubar , drawing area ,
and buffer ( not yet implmented )
(setq vbox (gtk:vbox-new nil 5))
(gtk:container-add window vbox)
try telling the vbox its size before menues are added .
(gtk:window-set-geometry-hints window vbox hints mask)
(gtk:widget-show vbox)
create menubar and add to top of
(setq menubar (create-menubar *menubar* window vbox))
(setf (plotter-menubar plotter) menubar)
(setq drawing-area (gtk:drawing-area-new))
(setf (plotter-drawing-area plotter) drawing-area)
(setf (plotter-bitmap plotter) nil)
(insure-drawing-sizes drawing-area x-axis y-axis)
(gtk:widget-show drawing-area)
(g:signal-connect drawing-area "expose_event"
(g:callback expose-event)
window)
(g:signal-connect drawing-area "configure_event"
(g:callback configure-event)
window)
(g:signal-connect drawing-area "button_press_event"
(g:callback button-press-event) window)
(g:signal-connect drawing-area "button_release_event"
(g:callback button-release-event) window)
(g:signal-connect drawing-area "motion_notify_event"
(g:callback motion-notify-event) window)
(g:signal-connect window "key_press_event"
(g:callback key-press-event) window)
(g:object-set-data drawing-area "user_data"
(gtk:struct-alloc :<G>dk<R>ectangle))
(g:object-set-data drawing-area "layout"
(gtk:widget-create-pango-layout drawing-area ""))
(gtk:widget-set-events drawing-area
(logior gdk:exposure-mask
gdk:leave-notify-mask
gdk:button-press-mask
gdk:button-release-mask
gdk:pointer-motion-mask
gdk:pointer-motion-hint-mask
))
(gtk:widget-set-events window gdk:focus-change-mask)
(g:signal-connect window "focus_in_event"
(g:callback focus-in-event) window)
(setq scrolled (gtk:scrolled-window-new
(g:nullptr) (g:nullptr)))
(gtk:widget-show scrolled)
(gtk:scrolled-window-add-with-viewport scrolled drawing-area)
(gtk:scrolled-window-set-policy scrolled
gtk:policy-always
gtk:policy-always)
(let ((hscroll (gtk:scrolled-window-get-hadjustment scrolled))
(vscroll (gtk:scrolled-window-get-vadjustment scrolled)))
(setf (plotter-x-scroller plotter) hscroll
(plotter-y-scroller plotter) vscroll)
(Gtk:Adjustment.step-increment
hscroll (coerce (axis-tick-size x-axis)'double-float))
(gtk:adjustment-changed hscroll)
(Gtk:Adjustment.step-increment
vscroll (coerce (axis-tick-size y-axis) 'double-float))
(gtk:adjustment-changed vscroll))
add scroller to
(gtk:box-pack-start vbox scrolled t t 0)
allocate private colormap , gc , plotting colors etc .
(allocate-plotting-data plotter)
(setf (plotter-draw plotter) t)
(setf (mouseinfo-mode (plotter-mouseinfo plotter)) :select-points)
(gtk:widget-show window)
(setf (plotter-gc plotter)
(gdk:gc-new (gtk:Widget.window drawing-area)))
scroll to origin on
(plotter-scroll plotter :y 1)
(push plotter *gtk-open-toplevels*)
( gtk : main ) )
(values)))
(defun plotter-zoom (plotter &key x y )
(let ((x-axis (plotter-x-axis plotter))
(y-axis (plotter-y-axis plotter)))
(when x
(when (eq x t)
(setf x (zoom-for-page-size x-axis
(plotter-x-scroller plotter))))
(if (and (numberp x) (> x 0))
(setf (axis-zoom x-axis) x)
(error "Zoom scaler not a positive number: ~S."
x)))
(when y
(when (eq y t)
(setf y (zoom-for-page-size y-axis
(plotter-y-scroller plotter))))
(if (and (numberp y) (> y 0))
(setf (axis-zoom y-axis) y)
(error "Zoom scaler not a positive number: ~S."
y)))
(when (or x y)
(insure-drawing-sizes (plotter-drawing-area plotter)
x-axis y-axis))
(values (axis-zoom x-axis)
(axis-zoom y-axis))))
(defun plotter-redraw (plotter &optional (redraw t))
(when redraw
(setf (plotter-draw plotter) redraw))
(let ((area (plotter-drawing-area plotter)))
(gtk:widget-queue-draw area))
(values))
(defun plotter-close (plotter)
(gtk:widget-destroy (plotter-window plotter)))
(defun plotter-resize (plotter &key width height)
plotter width height
())
(defun plotter-title (plotter &optional title)
(let ((win (plotter-window plotter)))
(if title
(progn (gtk:window-set-title win title)
title)
(gtk:window-get-title win))))
(defun plotter-scroll (pw &key x y)
(let (h v r)
(when x
(setq h (plotter-x-scroller pw))
(setq x (max (min x 1) 0))
(setq r (- (Gtk:Adjustment.upper h)
(Gtk:Adjustment.page-size h)))
(gtk:adjustment-set-value h (* r x))
(gtk:adjustment-value-changed h))
(when y
(setq v (plotter-y-scroller pw))
(setq y (max (min y 1) 0))
(setq r (- (Gtk:Adjustment.upper v)
(Gtk:Adjustment.page-size v)))
(gtk:adjustment-set-value v (* r y))
(gtk:adjustment-value-changed v))
(values)))
|
3f36045b06a3d2d58852b02d2beda25da8c4c1ad5030ba42924302d3f2a0004e | jumarko/clojure-experiments | 0420_uniques.clj | (ns clojure-experiments.purely-functional.puzzles.0420-uniques
"-tv-newsletter-420-say-what-you-mean/")
(defn uniques
"Removes elements that appear twice in the collection."
[coll]
(let [freqs (frequencies coll)]
(remove #(= 2 (get freqs %))
coll)))
(uniques [])
;;=> ()
(uniques [1 2 3])
= > ( 1 2 3 )
(uniques [1 1 2 3])
= > ( 2 3 )
(uniques [1 2 3 1 2 3])
;;=> ()
(uniques [1 2 3 2])
= > ( 1 3 )
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/purely_functional/puzzles/0420_uniques.clj | clojure | => ()
=> () | (ns clojure-experiments.purely-functional.puzzles.0420-uniques
"-tv-newsletter-420-say-what-you-mean/")
(defn uniques
"Removes elements that appear twice in the collection."
[coll]
(let [freqs (frequencies coll)]
(remove #(= 2 (get freqs %))
coll)))
(uniques [])
(uniques [1 2 3])
= > ( 1 2 3 )
(uniques [1 1 2 3])
= > ( 2 3 )
(uniques [1 2 3 1 2 3])
(uniques [1 2 3 2])
= > ( 1 3 )
|
f3493fdfdeb915b955aa5433879f4344fa32b1c1f01b0bebc131ab7ca0c6231e | Verites/verigraph | ModelCheckerSpec.hs | module Logic.Ctl.ModelCheckerSpec where
import qualified Data.Char as Char
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import Test.Hspec
import Test.HUnit hiding (State, Test)
import Logic.Ctl
import Logic.Model
spec :: Spec
spec = do
context "with boolean expressions" $ do
let
model =
assembleModel
[ ["1 []"]
, ["2 [p]"]
, ["3 [q]"]
, ["4 [p q]"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'true' properly" $
"true" `shouldHoldOn` [1, 2, 3, 4]
it "should handle 'false' properly" $
"false" `shouldHoldOn` []
it "should handle 'p' properly" $
"p" `shouldHoldOn` [2, 4]
it "should handle 'q' properly" $
"q" `shouldHoldOn` [3, 4]
it "should handle '~p' properly" $
"~p" `shouldHoldOn` [1, 3]
it "should handle 'p && q' properly" $
"p && q" `shouldHoldOn` [4]
it "should handle 'p || q' properly" $
"p || q" `shouldHoldOn` [2, 3, 4]
it "should handle 'p -> q' properly" $
"p -> q" `shouldHoldOn` [1, 3, 4]
it "should handle 'p <-> q' properly" $
"p <-> q" `shouldHoldOn` [1, 4]
it "should handle '~(p <-> q)' properly" $
"~(p <-> q)" `shouldHoldOn` [2, 3]
describe "{E|A}X" $ do
let
model =
assembleModel
[ ["1 []", "2 []", "3 [p]", "4 [p]"]
, ["3 [p]", "2 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EX p' properly" $
"EX p" `shouldHoldOn` [2, 3]
it "should handle 'AX p' properly" $
"AX p" `shouldHoldOn` [2, 4]
it "should handle '~(EX p || AX p)' properly" $
"~(EX p || AX p)" `shouldHoldOn` [1]
describe "{E|A}F" $ do
let
model =
assembleModel
[ ["1 []", "2 []", "3 []", "4 [p]", "5 []"]
, ["1 []", "1 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EF p' properly" $
"EF p" `shouldHoldOn` [1, 2, 3, 4]
it "should handle 'AF p' properly" $
"AF p" `shouldHoldOn` [2, 3, 4]
it "should handle '~(EF p || AF p)' properly" $
"~(EF p || AF p)" `shouldHoldOn` [5]
describe "{E|A}G" $ do
let
model =
assembleModel
[ ["1 []", "2 [p]", "3 [p]", "4 [p]"]
, ["2 []", "2 []", "5 []"]
, ["3 [p]", "3 [p]"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EG p' properly" $
"EG p" `shouldHoldOn` [2, 3, 4]
it "should handle 'AG p' properly" $
"AG p" `shouldHoldOn` [3, 4]
it "should handle '~(EG p || AG p)' properly" $
"~(EG p || AG p)" `shouldHoldOn` [1, 5]
describe "{E|A}U" $ do
let
model =
assembleModel
[ ["1 []", "2 [p]", "3 [p]", "4 [q]", "5 [p]", "5 [p]"]
, ["5 [p]", "3 [p]"]
, ["3 [p]", "6 [p q]", "1 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'E[p U q]' properly" $
"E[p U q]" `shouldHoldOn` [2, 3, 4, 5, 6]
it "should handle 'A[p U q]' properly" $
"A[p U q]" `shouldHoldOn` [2, 3, 4, 6]
it "should handle '~(E[p U q] || A[p U q])' properly" $
"~(E[p U q] || A[p U q])" `shouldHoldOn` [1]
statesThatSatisfy :: String -> KripkeStructure String -> [Int]
statesThatSatisfy exprText model =
case parseExpr "" exprText of
Left err ->
error ("Error parsing '"++ exprText ++"':\n"++ show err)
Right expr ->
List.sort (satisfyExpr' model expr)
assembleModel :: [[String]] -> KripkeStructure String
assembleModel description =
let
(states, transitions') =
parseLines description (IntMap.empty, Set.empty)
(transitions, _) =
Set.foldr addTransition ([], 0) transitions'
addTransition (src, tgt) (ts, uid) =
(Transition uid src tgt [] : ts, uid + 1)
in
KripkeStructure (IntMap.elems states) transitions
type PartialModel =
(IntMap (State String), Set (Int, Int))
parseLines :: [[String]] -> PartialModel -> PartialModel
parseLines lines model =
foldr parseLine model lines
parseLine :: [String] -> PartialModel -> PartialModel
parseLine stateTexts =
addStates (map parseState stateTexts)
addStates :: [(Int, [String])] -> PartialModel -> PartialModel
addStates [] model =
model
addStates [n1] (states, transitions) =
(addState n1 states, transitions)
addStates (n1:n2:rest) (states, transitions) =
let
states' =
addState n1 states
transitions' =
Set.insert (fst n1, fst n2) transitions
in
addStates (n2:rest) (states', transitions')
addState :: (Int, [String]) -> IntMap (State String) -> IntMap (State String)
addState (stateId, props) states =
let
addProps Nothing =
State stateId props
addProps (Just (State _ props')) =
State stateId (props `List.union` props')
in
IntMap.alter (Just . addProps) stateId states
parseState :: String -> (Int, [String])
parseState text =
let
(stateId, text') =
List.break Char.isSpace text
('[' : atomsText) =
List.takeWhile (/= ']') $ List.dropWhile (/= '[') text'
atoms =
split Char.isSpace atomsText
in
(read stateId, atoms)
split :: (a -> Bool) -> [a] -> [[a]]
split _ [] =
[[]]
split prop xs =
let
(first, rest') =
List.break prop xs
rest =
List.dropWhile prop rest'
in
if List.null rest then
[first, rest]
else
first : split prop rest
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/tests/Logic/Ctl/ModelCheckerSpec.hs | haskell | module Logic.Ctl.ModelCheckerSpec where
import qualified Data.Char as Char
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import Test.Hspec
import Test.HUnit hiding (State, Test)
import Logic.Ctl
import Logic.Model
spec :: Spec
spec = do
context "with boolean expressions" $ do
let
model =
assembleModel
[ ["1 []"]
, ["2 [p]"]
, ["3 [q]"]
, ["4 [p q]"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'true' properly" $
"true" `shouldHoldOn` [1, 2, 3, 4]
it "should handle 'false' properly" $
"false" `shouldHoldOn` []
it "should handle 'p' properly" $
"p" `shouldHoldOn` [2, 4]
it "should handle 'q' properly" $
"q" `shouldHoldOn` [3, 4]
it "should handle '~p' properly" $
"~p" `shouldHoldOn` [1, 3]
it "should handle 'p && q' properly" $
"p && q" `shouldHoldOn` [4]
it "should handle 'p || q' properly" $
"p || q" `shouldHoldOn` [2, 3, 4]
it "should handle 'p -> q' properly" $
"p -> q" `shouldHoldOn` [1, 3, 4]
it "should handle 'p <-> q' properly" $
"p <-> q" `shouldHoldOn` [1, 4]
it "should handle '~(p <-> q)' properly" $
"~(p <-> q)" `shouldHoldOn` [2, 3]
describe "{E|A}X" $ do
let
model =
assembleModel
[ ["1 []", "2 []", "3 [p]", "4 [p]"]
, ["3 [p]", "2 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EX p' properly" $
"EX p" `shouldHoldOn` [2, 3]
it "should handle 'AX p' properly" $
"AX p" `shouldHoldOn` [2, 4]
it "should handle '~(EX p || AX p)' properly" $
"~(EX p || AX p)" `shouldHoldOn` [1]
describe "{E|A}F" $ do
let
model =
assembleModel
[ ["1 []", "2 []", "3 []", "4 [p]", "5 []"]
, ["1 []", "1 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EF p' properly" $
"EF p" `shouldHoldOn` [1, 2, 3, 4]
it "should handle 'AF p' properly" $
"AF p" `shouldHoldOn` [2, 3, 4]
it "should handle '~(EF p || AF p)' properly" $
"~(EF p || AF p)" `shouldHoldOn` [5]
describe "{E|A}G" $ do
let
model =
assembleModel
[ ["1 []", "2 [p]", "3 [p]", "4 [p]"]
, ["2 []", "2 []", "5 []"]
, ["3 [p]", "3 [p]"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'EG p' properly" $
"EG p" `shouldHoldOn` [2, 3, 4]
it "should handle 'AG p' properly" $
"AG p" `shouldHoldOn` [3, 4]
it "should handle '~(EG p || AG p)' properly" $
"~(EG p || AG p)" `shouldHoldOn` [1, 5]
describe "{E|A}U" $ do
let
model =
assembleModel
[ ["1 []", "2 [p]", "3 [p]", "4 [q]", "5 [p]", "5 [p]"]
, ["5 [p]", "3 [p]"]
, ["3 [p]", "6 [p q]", "1 []"]
]
expr `shouldHoldOn` expectedStates =
statesThatSatisfy expr model `shouldBe` List.sort expectedStates
it "should handle 'E[p U q]' properly" $
"E[p U q]" `shouldHoldOn` [2, 3, 4, 5, 6]
it "should handle 'A[p U q]' properly" $
"A[p U q]" `shouldHoldOn` [2, 3, 4, 6]
it "should handle '~(E[p U q] || A[p U q])' properly" $
"~(E[p U q] || A[p U q])" `shouldHoldOn` [1]
statesThatSatisfy :: String -> KripkeStructure String -> [Int]
statesThatSatisfy exprText model =
case parseExpr "" exprText of
Left err ->
error ("Error parsing '"++ exprText ++"':\n"++ show err)
Right expr ->
List.sort (satisfyExpr' model expr)
assembleModel :: [[String]] -> KripkeStructure String
assembleModel description =
let
(states, transitions') =
parseLines description (IntMap.empty, Set.empty)
(transitions, _) =
Set.foldr addTransition ([], 0) transitions'
addTransition (src, tgt) (ts, uid) =
(Transition uid src tgt [] : ts, uid + 1)
in
KripkeStructure (IntMap.elems states) transitions
type PartialModel =
(IntMap (State String), Set (Int, Int))
parseLines :: [[String]] -> PartialModel -> PartialModel
parseLines lines model =
foldr parseLine model lines
parseLine :: [String] -> PartialModel -> PartialModel
parseLine stateTexts =
addStates (map parseState stateTexts)
addStates :: [(Int, [String])] -> PartialModel -> PartialModel
addStates [] model =
model
addStates [n1] (states, transitions) =
(addState n1 states, transitions)
addStates (n1:n2:rest) (states, transitions) =
let
states' =
addState n1 states
transitions' =
Set.insert (fst n1, fst n2) transitions
in
addStates (n2:rest) (states', transitions')
addState :: (Int, [String]) -> IntMap (State String) -> IntMap (State String)
addState (stateId, props) states =
let
addProps Nothing =
State stateId props
addProps (Just (State _ props')) =
State stateId (props `List.union` props')
in
IntMap.alter (Just . addProps) stateId states
parseState :: String -> (Int, [String])
parseState text =
let
(stateId, text') =
List.break Char.isSpace text
('[' : atomsText) =
List.takeWhile (/= ']') $ List.dropWhile (/= '[') text'
atoms =
split Char.isSpace atomsText
in
(read stateId, atoms)
split :: (a -> Bool) -> [a] -> [[a]]
split _ [] =
[[]]
split prop xs =
let
(first, rest') =
List.break prop xs
rest =
List.dropWhile prop rest'
in
if List.null rest then
[first, rest]
else
first : split prop rest
| |
112823dbb26f3cf364d23f6ae20c6683b58c516de8a56b72b37d1721152677cf | mishadoff/project-euler | problem045.clj | (ns project-euler)
(defn is-triangle? [n]
(let [t (/ (dec (Math/sqrt (inc (* 8 n)))) 2)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn is-pentagonal? [n]
(let [t (/ (inc (Math/sqrt (inc (* 24 n)))) 6)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn is-hexagonal? [n]
(let [t (/ (inc (Math/sqrt (inc (* 8 n)))) 2)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn triangle-number [n]
(* n (/ (+ n 1) 2)))
(defn pentagonal-number [n]
(* n (/ (- (* 3 n) 1) 2)))
(defn hexagonal-number [n]
(* n (- (* 2 n) 1)))
(def triangles (map triangle-number (iterate inc 1)))
(def pentagonals (map pentagonal-number (iterate inc 1)))
(def hexagonals (map hexagonal-number (iterate inc 1)))
Elapsed time : 82.55289 msecs
(defn euler-045 []
(first (drop-while #(not (and (is-triangle? %) (is-pentagonal? %)))
(drop-while #(< % (inc 40755)) hexagonals))))
| null | https://raw.githubusercontent.com/mishadoff/project-euler/45642adf29626d3752227c5a342886b33c70b337/src/project_euler/problem045.clj | clojure | (ns project-euler)
(defn is-triangle? [n]
(let [t (/ (dec (Math/sqrt (inc (* 8 n)))) 2)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn is-pentagonal? [n]
(let [t (/ (inc (Math/sqrt (inc (* 24 n)))) 6)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn is-hexagonal? [n]
(let [t (/ (inc (Math/sqrt (inc (* 8 n)))) 2)]
(if (and (pos? n) (= t (quot t 1))) true false)))
(defn triangle-number [n]
(* n (/ (+ n 1) 2)))
(defn pentagonal-number [n]
(* n (/ (- (* 3 n) 1) 2)))
(defn hexagonal-number [n]
(* n (- (* 2 n) 1)))
(def triangles (map triangle-number (iterate inc 1)))
(def pentagonals (map pentagonal-number (iterate inc 1)))
(def hexagonals (map hexagonal-number (iterate inc 1)))
Elapsed time : 82.55289 msecs
(defn euler-045 []
(first (drop-while #(not (and (is-triangle? %) (is-pentagonal? %)))
(drop-while #(< % (inc 40755)) hexagonals))))
| |
87425781a283e946bba017b2269e5f59b047af0c7fa1ba3625c1145cb0121a23 | jeopard/haskell-checking-account | Operation.hs | module Models.Operation (
Operation (..),
OperationType (..),
amountWithSign,
calculateBalance
) where
import Data.Scientific
import Data.Time.Calendar
import Data.UUID
-- represents credit and debit operations performed in a bank account
data Operation = Operation { operationId :: UUID
, accountId :: UUID
, operationType :: OperationType
, date :: Day
, amount :: Scientific
, description :: String
} deriving (Show)
data OperationType = Credit | Debit deriving (Show)
instance Eq Operation where
x == y = operationId x == operationId y
implementing this instance so that we can use Operations inside Sets
instance Ord Operation where
compare x y = compare (operationId x) (operationId y)
-- return a negative amount if the operation was debit
amountWithSign :: Operation -> Scientific
amountWithSign op = let a = amount op
in case (operationType op) of Credit -> a
Debit -> -a
-- calculate the sum of the amounts of a list of operations
calculateBalance :: [Operation] -> Scientific
calculateBalance ops = let startingValue = (scientific 0 0)
sumFunction = (\op acc -> acc + (amountWithSign op))
in foldr sumFunction startingValue ops
| null | https://raw.githubusercontent.com/jeopard/haskell-checking-account/27a889e507ad830ccb476a9663a5ab62aba8baa7/src/Models/Operation.hs | haskell | represents credit and debit operations performed in a bank account
return a negative amount if the operation was debit
calculate the sum of the amounts of a list of operations | module Models.Operation (
Operation (..),
OperationType (..),
amountWithSign,
calculateBalance
) where
import Data.Scientific
import Data.Time.Calendar
import Data.UUID
data Operation = Operation { operationId :: UUID
, accountId :: UUID
, operationType :: OperationType
, date :: Day
, amount :: Scientific
, description :: String
} deriving (Show)
data OperationType = Credit | Debit deriving (Show)
instance Eq Operation where
x == y = operationId x == operationId y
implementing this instance so that we can use Operations inside Sets
instance Ord Operation where
compare x y = compare (operationId x) (operationId y)
amountWithSign :: Operation -> Scientific
amountWithSign op = let a = amount op
in case (operationType op) of Credit -> a
Debit -> -a
calculateBalance :: [Operation] -> Scientific
calculateBalance ops = let startingValue = (scientific 0 0)
sumFunction = (\op acc -> acc + (amountWithSign op))
in foldr sumFunction startingValue ops
|
dc85419170afa1ba8e44f595193b484db2adc6c73c26b3762750ab47218259fb | bevuta/pox | cli.scm | #!/usr/bin/csi -ns
(use http-client intarweb uri-common ports matchable getopt-long data-structures tcp)
(require-library regex)
(import irregex)
(tcp-buffer-size 1024)
(define (print-usage command #!optional options)
(print "usage: " (program-name) " " command)
(when options
(newline)
(print "Options:")
(print options)))
(define base-uri (uri-reference ":7040/"))
(define (make-pox-uri path query)
(update-uri base-uri
path: path
query: query))
(define (make-pox-request uri #!key (method 'GET))
(make-request uri: uri
method: method
headers: (headers '((accept text/x-downtime)
(content-type text/x-downtime)))))
(define (port-pipe #!key (from (current-input-port)) (to (current-output-port)) (read read-char) (write write-char))
(with-output-to-port to
(lambda ()
(with-input-from-port from
(lambda ()
(port-for-each write read))))))
(define (get-tasks user options)
(with-input-from-request (make-pox-request (make-pox-uri `(/ "users" ,user "tasks") options))
#f
(cut port-pipe read: read-line write: print)))
(define get-tasks-options-grammar
'((omit-origin "omit the @origin declaration"
(required #f)
(single-char #\o)
(value #f))
(include-done "include tasks marked as done"
(required #f)
(single-char #\d)
(value #f))))
(define (get-tasks-options options)
(cdr (getopt-long options get-tasks-options-grammar)))
(define (post-tasks options)
(let* ((file (alist-ref 'file options))
(port (if file (open-input-file file) (current-input-port))))
(and-let* ((origin (read-line port))
(origin (irregex-match '(seq "@origin" (+ space) (submatch (+ any))) origin))
(origin (irregex-match-substring origin 1))
(origin (string-trim origin)))
(with-input-from-request (make-pox-request (uri-reference origin) method: 'POST)
(read-string #f port)
(cut port-pipe)))
(when file (close-input-port port))))
(define post-tasks-options-grammar
'((file "read tasks from FILE instead of standard input"
(required? #f)
(single-char #\f)
(value (required FILE)))))
(define (post-tasks-options options)
(cdr (getopt-long options post-tasks-options-grammar)))
(match (command-line-arguments)
(("get" user . options)
(get-tasks user (get-tasks-options options)))
(("get" . ...) (print-usage "get USER" (usage get-tasks-options-grammar)))
(("post" . options) (post-tasks (post-tasks-options options)))
(else (print-usage "COMMAND [OPTION ...]")
(newline)
(print "Available commands:")
(print " get Get tasks for a given user")
(print " post Post a task list back to the server")
(newline))) | null | https://raw.githubusercontent.com/bevuta/pox/9684d4037573b6c55acf24867c1d50aa8f4ea57e/cli.scm | scheme | #!/usr/bin/csi -ns
(use http-client intarweb uri-common ports matchable getopt-long data-structures tcp)
(require-library regex)
(import irregex)
(tcp-buffer-size 1024)
(define (print-usage command #!optional options)
(print "usage: " (program-name) " " command)
(when options
(newline)
(print "Options:")
(print options)))
(define base-uri (uri-reference ":7040/"))
(define (make-pox-uri path query)
(update-uri base-uri
path: path
query: query))
(define (make-pox-request uri #!key (method 'GET))
(make-request uri: uri
method: method
headers: (headers '((accept text/x-downtime)
(content-type text/x-downtime)))))
(define (port-pipe #!key (from (current-input-port)) (to (current-output-port)) (read read-char) (write write-char))
(with-output-to-port to
(lambda ()
(with-input-from-port from
(lambda ()
(port-for-each write read))))))
(define (get-tasks user options)
(with-input-from-request (make-pox-request (make-pox-uri `(/ "users" ,user "tasks") options))
#f
(cut port-pipe read: read-line write: print)))
(define get-tasks-options-grammar
'((omit-origin "omit the @origin declaration"
(required #f)
(single-char #\o)
(value #f))
(include-done "include tasks marked as done"
(required #f)
(single-char #\d)
(value #f))))
(define (get-tasks-options options)
(cdr (getopt-long options get-tasks-options-grammar)))
(define (post-tasks options)
(let* ((file (alist-ref 'file options))
(port (if file (open-input-file file) (current-input-port))))
(and-let* ((origin (read-line port))
(origin (irregex-match '(seq "@origin" (+ space) (submatch (+ any))) origin))
(origin (irregex-match-substring origin 1))
(origin (string-trim origin)))
(with-input-from-request (make-pox-request (uri-reference origin) method: 'POST)
(read-string #f port)
(cut port-pipe)))
(when file (close-input-port port))))
(define post-tasks-options-grammar
'((file "read tasks from FILE instead of standard input"
(required? #f)
(single-char #\f)
(value (required FILE)))))
(define (post-tasks-options options)
(cdr (getopt-long options post-tasks-options-grammar)))
(match (command-line-arguments)
(("get" user . options)
(get-tasks user (get-tasks-options options)))
(("get" . ...) (print-usage "get USER" (usage get-tasks-options-grammar)))
(("post" . options) (post-tasks (post-tasks-options options)))
(else (print-usage "COMMAND [OPTION ...]")
(newline)
(print "Available commands:")
(print " get Get tasks for a given user")
(print " post Post a task list back to the server")
(newline))) | |
4f4c403249ffe3880ccdfc1c9e15e06ddd69fad54592a4722e6a47cd3d4dd172 | samoht/docker-extension-ocaml | ui.ml | open Brr
let dd = Dd.v ()
let get_id id =
match Document.find_el_by_id G.document (Jstr.v id) with
| None ->
Console.(debug [ str (Printf.sprintf "element %S not found" id) ]);
raise Not_found
| Some elt -> elt
let call_hello k =
let vm = Dd.vm_service dd in
let response = Dd.get vm "/hello" in
Fut.await response k
let main () =
(* Set-up the page structure *)
let root = get_id "root" in
let button = El.button [ El.txt' "Call backend" ] in
El.set_children root [ button ];
(* Add onClick events *)
Ev.listen Ev.click (fun _ -> call_hello (Dd.success dd)) (El.as_target button)
let () = main ()
| null | https://raw.githubusercontent.com/samoht/docker-extension-ocaml/1a5f1d76df0797d500e56dd26ae5faac366f3ad9/ui/ui.ml | ocaml | Set-up the page structure
Add onClick events | open Brr
let dd = Dd.v ()
let get_id id =
match Document.find_el_by_id G.document (Jstr.v id) with
| None ->
Console.(debug [ str (Printf.sprintf "element %S not found" id) ]);
raise Not_found
| Some elt -> elt
let call_hello k =
let vm = Dd.vm_service dd in
let response = Dd.get vm "/hello" in
Fut.await response k
let main () =
let root = get_id "root" in
let button = El.button [ El.txt' "Call backend" ] in
El.set_children root [ button ];
Ev.listen Ev.click (fun _ -> call_hello (Dd.success dd)) (El.as_target button)
let () = main ()
|
1ea83034aa168296cc4e0a19b9eb0644984a8c7f057da76f9dcf84f29f018f0a | brownplt/pyret-docs | plot.js.rkt | #lang scribble/base
@(require "../../scribble-api.rkt" "../abbrevs.rkt")
@(require (only-in scribble/core delayed-block))
@(define (in-link T) (a-id T (xref "plot" T)))
@(define Color (a-id "Color" (xref "color" "Color")))
@(define Image (a-id "Image" (xref "image" "Image")))
@(define (t-field name ty) (a-field (tt name) ty))
@(define (t-record . rest)
(apply a-record (map tt (filter (lambda (x) (not (string=? x "\n"))) rest))))
@(append-gen-docs
`(module "plot"
(path "src/arr/trove/plot.arr")
(fun-spec (name "histogram") (arity 3))
(fun-spec (name "pie-chart") (arity 2))
(fun-spec (name "bar-chart") (arity 3))
(fun-spec (name "grouped-bar-chart") (arity 3))
(fun-spec (name "display-function") (arity 2))
(fun-spec (name "display-scatter") (arity 2))
(fun-spec (name "display-line") (arity 2))
(fun-spec (name "display-multi-plot") (arity 2))
(type-spec (name "PlotOptions"))
(type-spec (name "PlotWindowOptions"))
(data-spec
(name "Plot")
(variants ("line-plot" "scatter-plot" "function-plot")))
(constr-spec (name "line-plot"))
(constr-spec (name "scatter-plot"))
(constr-spec (name "function-plot"))
))
@docmodule["plot"]{
@margin-note{Note that the plot library has been completely rewritten as the @secref["chart"]
library to use Google Charts, which would allow us to support more features and more
types of charts easily. The current plot library will still be here for a period of time for those who
still use it, but we will not support it further.}
The Pyret Plot library. It consists of plot, chart, and data visualization tools.
The visualization will appear in a separate dialog window, and/or be returned
as an @pyret-id["Image" "image"].
@itemlist[
@item{To close the dialog, click the close button on the title bar or press @tt{esc}}
@item{To save a snapshot of the visualization, click the save button on the
title bar and choose a location to save the image}
]
Every function in this library is available on the @tt{plot} module object.
For example, if you used @pyret{import plot as P}, you would write
@pyret{P.display-function} to access @pyret{display-function} below. If you used
@pyret{include}, then you can refer to identifiers without needing to prefix
with @pyret{P.}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{The Plot Type}
(If you do not wish to customize the plotting, feel free to skip this section.
There will be a link referring back to this section when necessary)
@data-spec2["Plot" (list) (list
@constructor-spec["Plot" "function-plot" `(("f" ("type" "normal") ("contract" ,(a-arrow N N)))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))]
@constructor-spec["Plot" "line-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))]
@constructor-spec["Plot" "scatter-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))])]
@nested[#:style 'inset]{
@constructor-doc["Plot" "function-plot" (list `("f" ("type" "normal") ("contract" ,(a-arrow N N)))
`("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A graph of a function of one variable.
@member-spec["f" #:type "normal" #:contract (a-arrow N N)]{
A function to be graphed. The function doesn't need to be total:
it can yield an error for some @pyret{x} (such as division by zero
or resulting in an imaginary number).
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
@constructor-doc["Plot" "line-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A line plot or line chart, used to display "information as a series of data points called `markers'
connected by straight line segments." (see @url[""])
@member-spec["points" #:type "normal" #:contract TA]{
A table of two columns: @t-field["x" N] and @t-field["y" N]
Because two consecutive data points will be connected by a line segment as they are,
the rows of the table should have been sorted by the x-value.
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
@constructor-doc["Plot" "scatter-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A scatter plot or scatter chart, used "to display values for two variables for a set of data."
(see @url[""])
@member-spec["points" #:type "normal" #:contract TA]{
A table of two columns: @t-field["x" N] and @t-field["y" N].
The order of rows in this table does not matter.
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
}
@examples{
my-plot = function-plot(lam(x): num-sqrt(x + 1) end, default-options)
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{Plot Functions}
All plot functions will populate a dialog with controllers (textboxes and buttons)
on the right which can be used to change the window boundaries and number of sample points.
To zoom in at a specific region, you can click and drag on the plotting
region. To zoom out, press @tt{shift} and click on the plotting region.
To reset to the initial window boundaries, simply click on the plotting
region.
All changes by the controllers will not take an effect until the redraw button
is pressed.
The window boundaries could be any kind of real number (e.g., fraction, roughnum).
However, when processing, it will be converted to a decimal number.
For example, @pyret{1/3} will be converted to @pyret{0.3333...33} which
is actually @pyret{3333...33/10000...00}. This incurs the numerical imprecision,
but allows us to read the number easily.
For function plot, we make a deliberate decision to show points (the tendency of the function)
instead of connecting lines between them. This is to avoid the problem of inaccurate plotting
causing from, for example, discontinuity of the function, or a function which oscillates infinitely.
@function["display-multi-plot"
#:contract (a-arrow (L-of (in-link "Plot"))
(in-link "PlotWindowOptions")
Image)
#:args '(("lst" #f) ("options" #f))
#:return Image
]{
Display all @pyret-id{Plot}s in @pyret{lst} on a window with the configuration
from @pyret{options}.
@examples{
import color as C
p1 = function-plot(lam(x): x * x end, _.{color: C.red})
p2 = line-plot(table: x :: Number, y :: Number
row: 1, 1
row: 2, 4
row: 3, 9
row: 4, 16
end, _.{color: C.green})
display-multi-plot(
[list: p1, p2],
_.{
title: 'quadratic function and a scatter plot',
x-min: 0,
x-max: 20,
y-min: 0,
y-max: 20
})
}
The above example will plot a function @tt{y = x^2} using red color, and show
a line chart connecting points in the table using green color. The left, right,
top, bottom window boundary are 0, 20, 0, 20 respectively.
}
@function["display-function"
#:contract (a-arrow S (a-arrow N N) Image)
#:args '(("title" #f) ("f" #f))
#:return Image
]{
A shorthand to construct an @in-link{function-plot} with default options and then
display it. See @in-link{function-plot} for more information.
@examples{
NUM_E = ~2.71828
display-function('converge to 1', lam(x): 1 - num-expt(NUM_E, 0 - x) end)
}
}
@function["display-line"
#:contract (a-arrow S TA Image)
#:args '(("title" #f) ("tab" #f))
#:return Image
]{
A shorthand to construct a @in-link{line-plot} with default options and then
display it. See @in-link{line-plot} for more information.
@examples{
display-line('My line', table: x, y
row: 1, 2
row: 2, 10
row: 2.1, 3
row: 2.4, 5
row: 5, 1
end)
}
}
@function["display-scatter"
#:contract (a-arrow S TA Image)
#:args '(("title" #f) ("tab" #f))
#:return Image
]{
A shorthand to construct a @in-link{scatter-plot} with default options and then
display it. See @in-link{scatter-plot} for more information.
@examples{
display-scatter('My scatter plot', table: x, y
row: 1, 2
row: 1, 3.1
row: 4, 1
row: 7, 3
row: 4, 6
row: 2, 5
end)
}
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{Visualization Functions}
@function["histogram"
#:contract (a-arrow TA N (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("n" #f) ("options" #f))
#:return Image
]{
Display a histogram with @pyret{n} bins using data from @pyret{tab}
which is a table with one column: @t-field["value" N].
The range of the histogram is automatically inferred from the data.
@examples{
histogram(table: value :: Number
row: 1
row: 1.2
row: 2
row: 3
row: 10
row: 3
row: 6
row: -1
end, 4, _.{title: "A histogram with 4 bins"})
}
}
@function["pie-chart"
#:contract (a-arrow TA (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("options" #f))
#:return Image
]{
Display a pie chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["value" N].
@examples{
pie-chart(table: label, value
row: 'EU', 10.12
row: 'Asia', 93.1
row: 'America', 56.33
row: 'Africa', 101.1
end, _.{title: "A pie chart"})
}
}
@function["bar-chart"
#:contract (a-arrow TA (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("options" #f))
#:return Image
]{
Display a bar chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["value" N].
@examples{
bar-chart(
table: label, value
row: 'A', 11
row: 'B', 1
row: 'C', 3
row: 'D', 4
row: 'E', 9
row: 'F', 3
end, _.{title: 'Frequency of letters'})
}
}
@function["grouped-bar-chart"
#:contract (a-arrow TA (L-of S) (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("legends" #f) ("options" #f))
#:return Image
]{
Display a bar chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["values" (L-of N)]. @pyret{legends} indicates the legends
of the data where the first value of the table column @pyret{values} corresponds to the first legend
in @pyret{legends}, and so on.
}
@examples{
grouped-bar-chart(
table: label, values
row: 'CA', [list: 2704659, 4499890, 2159981, 3853788, 10604510, 8819342, 4114496]
row: 'TX', [list: 2027307, 3277946, 1420518, 2454721, 7017731, 5656528, 2472223]
row: 'NY', [list: 1208495, 2141490, 1058031, 1999120, 5355235, 5120254, 2607672]
row: 'FL', [list: 1140516, 1938695, 925060, 1607297, 4782119, 4746856, 3187797]
row: 'IL', [list: 894368, 1558919, 725973, 1311479, 3596343, 3239173, 1575308]
row: 'PA', [list: 737462, 1345341, 679201, 1203944, 3157759, 3414001, 1910571]
end, [list:
'Under 5 Years',
'5 to 13 Years',
'14 to 17 Years',
'18 to 24 Years',
'25 to 44 Years',
'45 to 64 Years',
'65 Years and Over'],
_.{title: 'Populations of different states by age group'})
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{The Options Types and Default Values}
The @pyret{PlotOptions} and @pyret{PlotWindowOptions} type is actually a function type
which consumes a default config and produces a desired config.
To use a default config, you could construct
@pyret-block{lam(default-configs): default-configs end}
which consumes a default config and merely returns it. We provide a value
@pyret{default-options} which is the polymorphic identity function for convenience, which has both type @pyret{PlotOptions} and @pyret{PlotWindowOptions}
A new Options can be constructed by the using @secref["s:extend-expr"] on
the default config.
@pyret-block{
new-options = lam(default-configs): default-configs.{val1: ..., val2: ...} end
}
Combining the @secref["s:extend-expr"] with the @secref["s:curried-apply-expr"],
the above can be rewritten as:
@pyret-block{
new-options = _.{val1: ..., val2: ...}
}
@type-spec["PlotOptions" '()]{
A config associated with @pyret-id{PlotOptions} consists of the following fields:
@a-record[(t-field "color" Color)]
The default config is @t-record{color: blue}
@examples{
import color as C
my-plot-options-1 = _.{color: C.red}
my-plot-options-2 = default-options
}
}
@type-spec["PlotWindowOptions" '()]{
A config associated with @pyret-id{PlotWindowOptions} consists of the following fields:
@a-record[(t-field "x-min" N)
(t-field "x-max" N)
(t-field "y-min" N)
(t-field "y-max" N)
(t-field "num-samples" N)
(t-field "infer-bounds" B)
(t-field "interact" B)
(t-field "title" S)]
The default config is
@t-record{x-min: -10
x-max: 10
y-min: -10
y-max: 10
num-samples: 1000
infer-bounds: false
interact: true
title: ""
}
If @pyret{infer-bounds} is true,
@pyret{x-min}, @pyret{x-max}, @pyret{y-min}, @pyret{y-max} will be inferred,
and old values will be overwritten.
@pyret{num-samples} is to control the number of sample points for
@in-link{function-plot}s.
@pyret{title} is displayed at the top of the plot window.
@pyret{interact}, when @pyret{true} (the default) shows a separate window
containing the plot. When @pyret{false}, the window does not appear; this is
useful for simply getting an @pyret-id["Image" "image"] from the plot.
}
}
| null | https://raw.githubusercontent.com/brownplt/pyret-docs/a7aad4c6432e6863b3a3a7a6adb4aedfc6c7ca0d/src/trove/plot.js.rkt | racket | this is | #lang scribble/base
@(require "../../scribble-api.rkt" "../abbrevs.rkt")
@(require (only-in scribble/core delayed-block))
@(define (in-link T) (a-id T (xref "plot" T)))
@(define Color (a-id "Color" (xref "color" "Color")))
@(define Image (a-id "Image" (xref "image" "Image")))
@(define (t-field name ty) (a-field (tt name) ty))
@(define (t-record . rest)
(apply a-record (map tt (filter (lambda (x) (not (string=? x "\n"))) rest))))
@(append-gen-docs
`(module "plot"
(path "src/arr/trove/plot.arr")
(fun-spec (name "histogram") (arity 3))
(fun-spec (name "pie-chart") (arity 2))
(fun-spec (name "bar-chart") (arity 3))
(fun-spec (name "grouped-bar-chart") (arity 3))
(fun-spec (name "display-function") (arity 2))
(fun-spec (name "display-scatter") (arity 2))
(fun-spec (name "display-line") (arity 2))
(fun-spec (name "display-multi-plot") (arity 2))
(type-spec (name "PlotOptions"))
(type-spec (name "PlotWindowOptions"))
(data-spec
(name "Plot")
(variants ("line-plot" "scatter-plot" "function-plot")))
(constr-spec (name "line-plot"))
(constr-spec (name "scatter-plot"))
(constr-spec (name "function-plot"))
))
@docmodule["plot"]{
@margin-note{Note that the plot library has been completely rewritten as the @secref["chart"]
library to use Google Charts, which would allow us to support more features and more
types of charts easily. The current plot library will still be here for a period of time for those who
still use it, but we will not support it further.}
The Pyret Plot library. It consists of plot, chart, and data visualization tools.
The visualization will appear in a separate dialog window, and/or be returned
as an @pyret-id["Image" "image"].
@itemlist[
@item{To close the dialog, click the close button on the title bar or press @tt{esc}}
@item{To save a snapshot of the visualization, click the save button on the
title bar and choose a location to save the image}
]
Every function in this library is available on the @tt{plot} module object.
For example, if you used @pyret{import plot as P}, you would write
@pyret{P.display-function} to access @pyret{display-function} below. If you used
@pyret{include}, then you can refer to identifiers without needing to prefix
with @pyret{P.}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{The Plot Type}
(If you do not wish to customize the plotting, feel free to skip this section.
There will be a link referring back to this section when necessary)
@data-spec2["Plot" (list) (list
@constructor-spec["Plot" "function-plot" `(("f" ("type" "normal") ("contract" ,(a-arrow N N)))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))]
@constructor-spec["Plot" "line-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))]
@constructor-spec["Plot" "scatter-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions"))))])]
@nested[#:style 'inset]{
@constructor-doc["Plot" "function-plot" (list `("f" ("type" "normal") ("contract" ,(a-arrow N N)))
`("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A graph of a function of one variable.
@member-spec["f" #:type "normal" #:contract (a-arrow N N)]{
A function to be graphed. The function doesn't need to be total:
it can yield an error for some @pyret{x} (such as division by zero
or resulting in an imaginary number).
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
@constructor-doc["Plot" "line-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A line plot or line chart, used to display "information as a series of data points called `markers'
connected by straight line segments." (see @url[""])
@member-spec["points" #:type "normal" #:contract TA]{
A table of two columns: @t-field["x" N] and @t-field["y" N]
Because two consecutive data points will be connected by a line segment as they are,
the rows of the table should have been sorted by the x-value.
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
@constructor-doc["Plot" "scatter-plot" `(("points" ("type" "normal") ("contract" ,TA))
("options" ("type" "normal") ("contract" ,(in-link "PlotOptions")))) (in-link "Plot")]{
A scatter plot or scatter chart, used "to display values for two variables for a set of data."
(see @url[""])
@member-spec["points" #:type "normal" #:contract TA]{
A table of two columns: @t-field["x" N] and @t-field["y" N].
The order of rows in this table does not matter.
}
@member-spec["options" #:type "normal" #:contract (in-link "PlotOptions")]
}
}
@examples{
my-plot = function-plot(lam(x): num-sqrt(x + 1) end, default-options)
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{Plot Functions}
All plot functions will populate a dialog with controllers (textboxes and buttons)
on the right which can be used to change the window boundaries and number of sample points.
To zoom in at a specific region, you can click and drag on the plotting
region. To zoom out, press @tt{shift} and click on the plotting region.
To reset to the initial window boundaries, simply click on the plotting
region.
All changes by the controllers will not take an effect until the redraw button
is pressed.
The window boundaries could be any kind of real number (e.g., fraction, roughnum).
However, when processing, it will be converted to a decimal number.
For example, @pyret{1/3} will be converted to @pyret{0.3333...33} which
is actually @pyret{3333...33/10000...00}. This incurs the numerical imprecision,
but allows us to read the number easily.
For function plot, we make a deliberate decision to show points (the tendency of the function)
instead of connecting lines between them. This is to avoid the problem of inaccurate plotting
causing from, for example, discontinuity of the function, or a function which oscillates infinitely.
@function["display-multi-plot"
#:contract (a-arrow (L-of (in-link "Plot"))
(in-link "PlotWindowOptions")
Image)
#:args '(("lst" #f) ("options" #f))
#:return Image
]{
Display all @pyret-id{Plot}s in @pyret{lst} on a window with the configuration
from @pyret{options}.
@examples{
import color as C
p1 = function-plot(lam(x): x * x end, _.{color: C.red})
p2 = line-plot(table: x :: Number, y :: Number
row: 1, 1
row: 2, 4
row: 3, 9
row: 4, 16
end, _.{color: C.green})
display-multi-plot(
[list: p1, p2],
_.{
title: 'quadratic function and a scatter plot',
x-min: 0,
x-max: 20,
y-min: 0,
y-max: 20
})
}
The above example will plot a function @tt{y = x^2} using red color, and show
a line chart connecting points in the table using green color. The left, right,
top, bottom window boundary are 0, 20, 0, 20 respectively.
}
@function["display-function"
#:contract (a-arrow S (a-arrow N N) Image)
#:args '(("title" #f) ("f" #f))
#:return Image
]{
A shorthand to construct an @in-link{function-plot} with default options and then
display it. See @in-link{function-plot} for more information.
@examples{
NUM_E = ~2.71828
display-function('converge to 1', lam(x): 1 - num-expt(NUM_E, 0 - x) end)
}
}
@function["display-line"
#:contract (a-arrow S TA Image)
#:args '(("title" #f) ("tab" #f))
#:return Image
]{
A shorthand to construct a @in-link{line-plot} with default options and then
display it. See @in-link{line-plot} for more information.
@examples{
display-line('My line', table: x, y
row: 1, 2
row: 2, 10
row: 2.1, 3
row: 2.4, 5
row: 5, 1
end)
}
}
@function["display-scatter"
#:contract (a-arrow S TA Image)
#:args '(("title" #f) ("tab" #f))
#:return Image
]{
A shorthand to construct a @in-link{scatter-plot} with default options and then
display it. See @in-link{scatter-plot} for more information.
@examples{
display-scatter('My scatter plot', table: x, y
row: 1, 2
row: 1, 3.1
row: 4, 1
row: 7, 3
row: 4, 6
row: 2, 5
end)
}
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{Visualization Functions}
@function["histogram"
#:contract (a-arrow TA N (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("n" #f) ("options" #f))
#:return Image
]{
Display a histogram with @pyret{n} bins using data from @pyret{tab}
which is a table with one column: @t-field["value" N].
The range of the histogram is automatically inferred from the data.
@examples{
histogram(table: value :: Number
row: 1
row: 1.2
row: 2
row: 3
row: 10
row: 3
row: 6
row: -1
end, 4, _.{title: "A histogram with 4 bins"})
}
}
@function["pie-chart"
#:contract (a-arrow TA (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("options" #f))
#:return Image
]{
Display a pie chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["value" N].
@examples{
pie-chart(table: label, value
row: 'EU', 10.12
row: 'Asia', 93.1
row: 'America', 56.33
row: 'Africa', 101.1
end, _.{title: "A pie chart"})
}
}
@function["bar-chart"
#:contract (a-arrow TA (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("options" #f))
#:return Image
]{
Display a bar chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["value" N].
@examples{
bar-chart(
table: label, value
row: 'A', 11
row: 'B', 1
row: 'C', 3
row: 'D', 4
row: 'E', 9
row: 'F', 3
end, _.{title: 'Frequency of letters'})
}
}
@function["grouped-bar-chart"
#:contract (a-arrow TA (L-of S) (in-link "PlotWindowOptions") Image)
#:args '(("tab" #f) ("legends" #f) ("options" #f))
#:return Image
]{
Display a bar chart using data from @pyret{tab} which is a table with two columns:
@t-field["label" S] and @t-field["values" (L-of N)]. @pyret{legends} indicates the legends
of the data where the first value of the table column @pyret{values} corresponds to the first legend
in @pyret{legends}, and so on.
}
@examples{
grouped-bar-chart(
table: label, values
row: 'CA', [list: 2704659, 4499890, 2159981, 3853788, 10604510, 8819342, 4114496]
row: 'TX', [list: 2027307, 3277946, 1420518, 2454721, 7017731, 5656528, 2472223]
row: 'NY', [list: 1208495, 2141490, 1058031, 1999120, 5355235, 5120254, 2607672]
row: 'FL', [list: 1140516, 1938695, 925060, 1607297, 4782119, 4746856, 3187797]
row: 'IL', [list: 894368, 1558919, 725973, 1311479, 3596343, 3239173, 1575308]
row: 'PA', [list: 737462, 1345341, 679201, 1203944, 3157759, 3414001, 1910571]
end, [list:
'Under 5 Years',
'5 to 13 Years',
'14 to 17 Years',
'18 to 24 Years',
'25 to 44 Years',
'45 to 64 Years',
'65 Years and Over'],
_.{title: 'Populations of different states by age group'})
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@section{The Options Types and Default Values}
The @pyret{PlotOptions} and @pyret{PlotWindowOptions} type is actually a function type
which consumes a default config and produces a desired config.
To use a default config, you could construct
@pyret-block{lam(default-configs): default-configs end}
which consumes a default config and merely returns it. We provide a value
@pyret{default-options} which is the polymorphic identity function for convenience, which has both type @pyret{PlotOptions} and @pyret{PlotWindowOptions}
A new Options can be constructed by the using @secref["s:extend-expr"] on
the default config.
@pyret-block{
new-options = lam(default-configs): default-configs.{val1: ..., val2: ...} end
}
Combining the @secref["s:extend-expr"] with the @secref["s:curried-apply-expr"],
the above can be rewritten as:
@pyret-block{
new-options = _.{val1: ..., val2: ...}
}
@type-spec["PlotOptions" '()]{
A config associated with @pyret-id{PlotOptions} consists of the following fields:
@a-record[(t-field "color" Color)]
The default config is @t-record{color: blue}
@examples{
import color as C
my-plot-options-1 = _.{color: C.red}
my-plot-options-2 = default-options
}
}
@type-spec["PlotWindowOptions" '()]{
A config associated with @pyret-id{PlotWindowOptions} consists of the following fields:
@a-record[(t-field "x-min" N)
(t-field "x-max" N)
(t-field "y-min" N)
(t-field "y-max" N)
(t-field "num-samples" N)
(t-field "infer-bounds" B)
(t-field "interact" B)
(t-field "title" S)]
The default config is
@t-record{x-min: -10
x-max: 10
y-min: -10
y-max: 10
num-samples: 1000
infer-bounds: false
interact: true
title: ""
}
If @pyret{infer-bounds} is true,
@pyret{x-min}, @pyret{x-max}, @pyret{y-min}, @pyret{y-max} will be inferred,
and old values will be overwritten.
@pyret{num-samples} is to control the number of sample points for
@in-link{function-plot}s.
@pyret{title} is displayed at the top of the plot window.
@pyret{interact}, when @pyret{true} (the default) shows a separate window
useful for simply getting an @pyret-id["Image" "image"] from the plot.
}
}
|
f4fb614c2d36c792bb5df34d1cb5e9d753d0e8dcd13322fd38aedd0216a68a93 | soulomoon/SICP | Exercise3.25.scm | Exercise 3.25 : Generalizing one- and two - dimensional tables , show how to implement a table in which values are stored under an arbitrary number of keys and different values may be stored under different numbers of keys . The lookup and insert ! procedures should take as input a list of keys used to access the table .
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-list)
(define (iter key-list table)
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(cdr subtable)
(iter remain-key-list subtable))
false)))
(iter key-list local-table))
(define (insert! key-list value)
(define (iter key-list table)
(if (pair? (cdr table))
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(set-cdr! subtable value)
(iter remain-key-list subtable))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(cons newtable
(cdr table)))
(iter key-list table)))))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(list newtable))
(iter key-list table))))
'ok)
(iter key-list local-table)
'ok local-table)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation:
TABLE" m))))
dispatch))
(define operation-table (make-table))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
(display (put (list 'b) 0))(newline )
(display (put (list 'a) 0))(newline )
(display (put (list 'a 'b) 1))(newline )
(display (put (list 'a 'b 'c) 2))(newline )
(display (put (list 'a 'b 'd) 3))(newline )
(display (get (list 'a 'b)))(newline )
(display (get (list 'a 'b 'c)))(newline )
(display (get (list 'a 'b 'd)))(newline )
Welcome to , version 6.7 [ 3 m ] .
Language : SICP ( PLaneT 1.18 ) ; memory limit : 128 MB .
; (*table* (b . 0))
; (*table* (a . 0) (b . 0))
( * table * ( a ( b . 1 ) ) ( b . 0 ) )
( * table * ( a ( b ( c . 2 ) ) ) ( b . 0 ) )
( * table * ( a ( b ( d . 3 ) ( c . 2 ) ) ) ( b . 0 ) )
( ( d . 3 ) ( c . 2 ) )
2
3
; > | null | https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter3/Exercise3.25.scm | scheme | memory limit : 128 MB .
(*table* (b . 0))
(*table* (a . 0) (b . 0))
> | Exercise 3.25 : Generalizing one- and two - dimensional tables , show how to implement a table in which values are stored under an arbitrary number of keys and different values may be stored under different numbers of keys . The lookup and insert ! procedures should take as input a list of keys used to access the table .
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-list)
(define (iter key-list table)
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(cdr subtable)
(iter remain-key-list subtable))
false)))
(iter key-list local-table))
(define (insert! key-list value)
(define (iter key-list table)
(if (pair? (cdr table))
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(set-cdr! subtable value)
(iter remain-key-list subtable))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(cons newtable
(cdr table)))
(iter key-list table)))))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(list newtable))
(iter key-list table))))
'ok)
(iter key-list local-table)
'ok local-table)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation:
TABLE" m))))
dispatch))
(define operation-table (make-table))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
(display (put (list 'b) 0))(newline )
(display (put (list 'a) 0))(newline )
(display (put (list 'a 'b) 1))(newline )
(display (put (list 'a 'b 'c) 2))(newline )
(display (put (list 'a 'b 'd) 3))(newline )
(display (get (list 'a 'b)))(newline )
(display (get (list 'a 'b 'c)))(newline )
(display (get (list 'a 'b 'd)))(newline )
Welcome to , version 6.7 [ 3 m ] .
( * table * ( a ( b . 1 ) ) ( b . 0 ) )
( * table * ( a ( b ( c . 2 ) ) ) ( b . 0 ) )
( * table * ( a ( b ( d . 3 ) ( c . 2 ) ) ) ( b . 0 ) )
( ( d . 3 ) ( c . 2 ) )
2
3 |
c99d7f6e74c2ba976dda45504419b082af3afe632421f0e3812a686294b7a2ec | mnieper/unsyntax | repl.scm | Copyright © ( 2020 ) .
;; This file is part of unsyntax.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation files
( the " Software " ) , to deal in the Software without restriction ,
;; including without limitation the rights to use, copy, modify, merge,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
;; subject to the following conditions:
;; The above copyright notice and this permission notice (including the
;; next paragraph) shall be included in all copies or substantial
portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define *interaction-environment*
(delay
(let
((env
(mutable-environment
'(only (unsyntax) import)
'(only (scheme base)
...
=>
_
and
begin
case
cond
cond-expand
define
define-record-type
define-syntax
define-values
do
else
guard
if
include
include-ci
lambda
let
let*
let*-values
let-values
let-syntax
letrec
letrec*
letrec-syntax
or
parameterize
quasiquote
quote
set!
syntax-error
syntax-rules
unless
unquote
unquote-splicing
when))))
(let-syntax ((define* (syntax-rules ()
((_ i ...)
(begin
(environment-define! env 'i i) ...)))))
(define*
*
+
-
/
<
<=
=
>
>=
abs
append
apply
assoc
assq
assv
binary-port?
boolean=?
boolean?
bytevector
bytevector-append
bytevector-copy
bytevector-copy!
bytevector-length
bytevector-u8-ref
bytevector-u8-set!
bytevector?
caar
cadr
call-with-current-continuation
call-with-port
call-with-values
call/cc
car
cdar
cddr
cdr
ceiling
char->integer
char-ready?
char<=?
char<?
char=?
char>=?
char>?
char?
close-input-port
close-output-port
close-port
complex?
cons
current-error-port
current-input-port
current-output-port
denominator
dynamic-wind
eof-object
eof-object?
eq?
equal?
eqv?
error
error-object-irritants
error-object-message
error-object?
even?
exact
exact-integer-sqrt
exact-integer?
exact?
expt
features
file-error?
floor
floor-quotient
floor-remainder
floor/
flush-output-port
for-each
gcd
get-output-bytevector
get-output-string
inexact
inexact?
input-port-open?
input-port?
integer->char
integer?
lcm
length
list
list->string
list->vector
list-copy
list-ref
list-set!
list-tail
list?
make-bytevector
make-list
make-parameter
make-string
make-vector
map
max
member
memq
memv
min
modulo
negative?
newline
not
null?
number->string
number?
numerator
odd?
open-input-bytevector
open-input-string
open-output-bytevector
open-output-string
output-port-open?
output-port?
pair?
peek-char
peek-u8
port?
positive?
procedure?
quotient
raise
raise-continuable
rational?
rationalize
read-bytevector
read-bytevector!
read-char
read-error?
read-line
read-string
read-u8
real?
remainder
reverse
round
set-car!
set-cdr!
square
string
string->list
string->number
string->symbol
string->utf8
string->vector
string-append
string-copy
string-copy!
string-fill!
string-for-each
string-length
string-map
string-ref
string-set!
string<=?
string<?
string=?
string>=?
string>?
string?
substring
symbol->string
symbol=?
symbol?
textual-port?
truncate
truncate-quotient
u8-ready?
utf8->string
values
vector
vector->list
vector->string
vector-append
vector-copy
vector-copy!
vector-fill!
vector-for-each
vector-length
vector-map
vector-ref
vector-set!
vector?
with-exception-handler
write-bytevector
write-char
write-string
write-u8
zero?)
env))))
(define (interaction-environment) (force *interaction-environment*))
| null | https://raw.githubusercontent.com/mnieper/unsyntax/cd12891805a93229255ff0f2c46cf0e2b5316c7c/src/scheme/repl.scm | scheme | This file is part of unsyntax.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
including without limitation the rights to use, copy, modify, merge,
subject to the following conditions:
The above copyright notice and this permission notice (including the
next paragraph) shall be included in all copies or substantial
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | Copyright © ( 2020 ) .
( the " Software " ) , to deal in the Software without restriction ,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(define *interaction-environment*
(delay
(let
((env
(mutable-environment
'(only (unsyntax) import)
'(only (scheme base)
...
=>
_
and
begin
case
cond
cond-expand
define
define-record-type
define-syntax
define-values
do
else
guard
if
include
include-ci
lambda
let
let*
let*-values
let-values
let-syntax
letrec
letrec*
letrec-syntax
or
parameterize
quasiquote
quote
set!
syntax-error
syntax-rules
unless
unquote
unquote-splicing
when))))
(let-syntax ((define* (syntax-rules ()
((_ i ...)
(begin
(environment-define! env 'i i) ...)))))
(define*
*
+
-
/
<
<=
=
>
>=
abs
append
apply
assoc
assq
assv
binary-port?
boolean=?
boolean?
bytevector
bytevector-append
bytevector-copy
bytevector-copy!
bytevector-length
bytevector-u8-ref
bytevector-u8-set!
bytevector?
caar
cadr
call-with-current-continuation
call-with-port
call-with-values
call/cc
car
cdar
cddr
cdr
ceiling
char->integer
char-ready?
char<=?
char<?
char=?
char>=?
char>?
char?
close-input-port
close-output-port
close-port
complex?
cons
current-error-port
current-input-port
current-output-port
denominator
dynamic-wind
eof-object
eof-object?
eq?
equal?
eqv?
error
error-object-irritants
error-object-message
error-object?
even?
exact
exact-integer-sqrt
exact-integer?
exact?
expt
features
file-error?
floor
floor-quotient
floor-remainder
floor/
flush-output-port
for-each
gcd
get-output-bytevector
get-output-string
inexact
inexact?
input-port-open?
input-port?
integer->char
integer?
lcm
length
list
list->string
list->vector
list-copy
list-ref
list-set!
list-tail
list?
make-bytevector
make-list
make-parameter
make-string
make-vector
map
max
member
memq
memv
min
modulo
negative?
newline
not
null?
number->string
number?
numerator
odd?
open-input-bytevector
open-input-string
open-output-bytevector
open-output-string
output-port-open?
output-port?
pair?
peek-char
peek-u8
port?
positive?
procedure?
quotient
raise
raise-continuable
rational?
rationalize
read-bytevector
read-bytevector!
read-char
read-error?
read-line
read-string
read-u8
real?
remainder
reverse
round
set-car!
set-cdr!
square
string
string->list
string->number
string->symbol
string->utf8
string->vector
string-append
string-copy
string-copy!
string-fill!
string-for-each
string-length
string-map
string-ref
string-set!
string<=?
string<?
string=?
string>=?
string>?
string?
substring
symbol->string
symbol=?
symbol?
textual-port?
truncate
truncate-quotient
u8-ready?
utf8->string
values
vector
vector->list
vector->string
vector-append
vector-copy
vector-copy!
vector-fill!
vector-for-each
vector-length
vector-map
vector-ref
vector-set!
vector?
with-exception-handler
write-bytevector
write-char
write-string
write-u8
zero?)
env))))
(define (interaction-environment) (force *interaction-environment*))
|
7a468e8fcd1659e63bb6b0be922291fa6dbb2b940789a041bce1c00fb1712aac | jacobhilton/backgammon | player.ml | type t =
| Forwards
| Backwards
[@@deriving sexp]
let equal t1 t2 =
match t1, t2 with
| Forwards, Forwards | Backwards, Backwards -> true
| Forwards, Backwards | Backwards, Forwards -> false
let flip = function
| Forwards -> Backwards
| Backwards -> Forwards
let char = function
| Forwards -> 'O'
| Backwards -> 'X'
| null | https://raw.githubusercontent.com/jacobhilton/backgammon/9b5330efa4c8314b8fb7cb6b9b2a428a23d29719/player.ml | ocaml | type t =
| Forwards
| Backwards
[@@deriving sexp]
let equal t1 t2 =
match t1, t2 with
| Forwards, Forwards | Backwards, Backwards -> true
| Forwards, Backwards | Backwards, Forwards -> false
let flip = function
| Forwards -> Backwards
| Backwards -> Forwards
let char = function
| Forwards -> 'O'
| Backwards -> 'X'
| |
d7308e6951a5df0b286116863e0cf0870c734a712dbdb33027f46b76ad652926 | RefactoringTools/HaRe | Utils.hs | module Layout.Utils where
foo :: IO ()
foo = do
let parsed = 3
let expr = 2
return ()
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/Renaming/Utils.hs | haskell | module Layout.Utils where
foo :: IO ()
foo = do
let parsed = 3
let expr = 2
return ()
| |
0b6200af65de16a19e44a568559a8246c040029231d87e99a965b834f1bdfab3 | reasonml-old/bs-node | nodeBuffer.ml | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
*
* 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 , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
open Js.Typed_array
type t
external fromString : Js.String.t -> t = "Buffer.from" [@@bs.val]
external fromStringWithEncoding : Js.String.t -> encoding:Js.String.t -> t =
"Buffer.from" [@@bs.val]
external fromArray : int array -> t = "Buffer.from" [@@bs.val]
external fromArrayBuffer : ArrayBuffer.t -> t = "Buffer.from" [@@bs.val]
external fromArrayBufferOffset: ArrayBuffer.t -> offset:int -> t =
"Buffer.from" [@@bs.val]
external fromArrayBufferRange: ArrayBuffer.t -> offset:int ->
length:int -> t = "Buffer.from" [@@bs.val]
external fromBuffer: t -> t = "Buffer.from" [@@bs.val]
external alloc: int -> t = "Buffer.alloc" [@@bs.val]
external allocFillInt: int -> fill:int -> t = "Buffer.alloc" [@@bs.val]
external allocFillString: int -> fill:Js.String.t -> t = "Buffer.alloc" [@@bs.val]
external allocFillStringWithEncoding: int -> fill:Js.String.t ->
encoding:Js.String.t -> t = "Buffer.alloc" [@@bs.val]
external allocFillBuffer: int -> fill:t -> t = "Buffer.alloc" [@@bs.val]
external allocUnsafe: int -> t = "Buffer.allocUnsafe" [@@bs.val]
external allocUnsafeSlow: int -> t = "Buffer.allocUnsafeSlow" [@@bs.val]
external unsafeGet : t -> int -> int = "" [@@bs.get_index]
external unsafeSet : t -> int -> int -> unit = "" [@@bs.set_index]
external byteLengthString : Js.String.t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthStringWithEncoding : Js.String.t -> encoding:Js.String.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthBuffer : t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthInt8Array : Int8Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint8Array : Uint8Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthInt16Array : Int16Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint16Array : Uint16Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthInt32Array : Int32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint32Array : Uint32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthFloat32Array : Float32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthFloat64Array : Float64Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthDataView : DataView.t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthArrayBuffer : ArrayBuffer.t -> int = "Buffer.byteLength" [@@bs.val]
external compare : t -> t -> int = "Buffer.compare" [@@bs.val]
external concat : t array -> t = "Buffer.concat" [@@bs.val]
external concatLength : t array -> length:int -> t = "Buffer.concat" [@@bs.val]
external isEncoding : Js.String.t -> bool = "Buffer.isEncoding" [@@bs.val]
type buffer
external buffer : buffer = "Buffer" [@@bs.val]
external poolSize : int = "Buffer.poolSize" [@@bs.val]
external setPoolSize : buffer -> int -> int = "poolSize" [@@bs.set]
let setPoolSize n = setPoolSize buffer n
external copy : t -> t -> int = "" [@@bs.send]
external copyOffset : t -> t -> targetStart:int -> int = "copy" [@@bs.send]
external copyOffsetFromOffset : t -> t -> targetStart:int -> sourceStart:int ->
int = "copy" [@@bs.send]
external copyOffsetFromRange : t -> t -> targetStart:int -> sourceStart:int ->
sourceEnd:int -> int = "copy" [@@bs.send]
external copyToUint8Array : t -> Uint8Array.t -> int = "copy" [@@bs.send]
external copyToUint8ArrayOffset : t -> Uint8Array.t -> targetStart:int ->
int = "copy" [@@bs.send]
external copyToUint8ArrayFrom: t -> Uint8Array.t -> targetStart:int ->
sourceStart:int -> int = "copy" [@@bs.send]
external copyToUint8ArrayFromRange : t -> Uint8Array.t -> targetStart:int ->
sourceStart:int -> sourceEnd:int -> int = "copy" [@@bs.send]
FIXME after iterators support
(* external entries : t -> Iterator = "" [@@bs.get] *)
external equals : t -> t -> bool = "" [@@bs.send]
external fillString : t -> Js.String.t -> t = "fill" [@@bs.send]
external fillStringOffset : t -> value:Js.String.t -> offset:int -> t =
"fill" [@@bs.send]
external fillStringRange : t -> value:Js.String.t -> offset:int ->
end_:int -> t = "fill" [@@bs.send]
external fillStringRangeWithEncoding : t -> value:Js.String.t -> offset:int ->
end_:int -> encoding:Js.String.t -> t = "fill" [@@bs.send]
external fillBuffer : t -> t -> t = "fill" [@@bs.send]
external fillBufferOffset : t -> value:t -> offset:int -> t = "fill" [@@bs.send]
external fillBufferRange : t -> value:t -> offset:int -> end_:int -> t =
"fill" [@@bs.send]
external fillInt : t -> int -> t = "fill" [@@bs.send]
external fillIntOffset : t -> value:int -> offset:int -> t = "fill" [@@bs.send]
external fillIntRange : t -> value:int -> offset:int -> end_:int -> t =
"fill" [@@bs.send]
external includesString : t -> Js.String.t -> bool = "includes" [@@bs.send]
external includesStringFrom : t -> value:Js.String.t -> offset:int -> bool =
"includes" [@@bs.send]
external includesStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> bool ="includes" [@@bs.send]
external includesBuffer : t -> t -> bool = "includes" [@@bs.send]
external includesBufferFrom : t -> value:t -> offset:int -> bool =
"includes" [@@bs.send]
external includesInt : t -> int -> bool = "includes" [@@bs.send]
external includesIntFrom : t -> value:int -> offset:int -> bool =
"includes" [@@bs.send]
external indexOfString : t -> Js.String.t -> int = "indexOf" [@@bs.send]
external indexOfStringFrom : t -> value:Js.String.t -> offset:int -> int =
"indexOf" [@@bs.send]
external indexOfStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> int ="indexOf" [@@bs.send]
external indexOfBuffer : t -> t -> int = "indexOf" [@@bs.send]
external indexOfBufferFrom : t -> value:t -> offset:int -> int =
"indexOf" [@@bs.send]
external indexOfInt : t -> int -> int = "indexOf" [@@bs.send]
external indexOfIntFrom : t -> value:int -> offset:int -> int =
"indexOf" [@@bs.send]
FIXME after iterators support
(* external keys : t -> Iterator = "" [@@bs.send] *)
external lastIndexOfString : t -> Js.String.t -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfStringFrom : t -> value:Js.String.t -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external lastIndexOfStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> int ="lastIndexOf" [@@bs.send]
external lastIndexOfBuffer : t -> t -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfBufferFrom : t -> value:t -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external lastIndexOfInt : t -> int -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfIntFrom : t -> value:int -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external length : t -> int = "" [@@bs.get]
external readDoubleBigEndian : t -> offset:int -> float = "" [@@bs.send]
external readDoubleBigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readDoubleBE" [@@bs.send]
external readDoubleLittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readDoubleLittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readDoubleLE" [@@bs.send]
external readFloatBigEndian : t -> offset:int -> float = "" [@@bs.send]
external readFloatBigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readFloatBE" [@@bs.send]
external readFloatLittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readFloatLittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readFloatLE" [@@bs.send]
external readInt8 : t -> offset:int -> float = "" [@@bs.send]
external readInt8NoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt8" [@@bs.send]
external readInt16BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt16BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt16BE" [@@bs.send]
external readInt16LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt16LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt16LE" [@@bs.send]
external readInt32BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt32BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt32BE" [@@bs.send]
external readInt32LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt32LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt32LE" [@@bs.send]
external readIntBigEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readIntBigEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readIntBE" [@@bs.send]
external readIntLittleEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readIntLittleEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readIntLE" [@@bs.send]
external readUint8 : t -> offset:int -> float = "" [@@bs.send]
external readUint8NoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint8" [@@bs.send]
external readUint16BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint16BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint16BE" [@@bs.send]
external readUint16LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint16LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint16LE" [@@bs.send]
external readUint32BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint32BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint32BE" [@@bs.send]
external readUint32LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint32LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint32LE" [@@bs.send]
external readUintBigEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readUintBigEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readUintBE" [@@bs.send]
external readUintLittleEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readUintLittleEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readUintLE" [@@bs.send]
external slice : t -> t = "" [@@bs.send]
external sliceOffset : t -> start:int -> t = "slice" [@@bs.send]
external sliceRange : t -> start:int -> end_:int -> t = "slice" [@@bs.send]
external swap16 : t -> t = "" [@@bs.send]
external swap32 : t -> t = "" [@@bs.send]
external swap64 : t -> t = "" [@@bs.send]
external toJSON : t -> < .. > Js.t = "" [@@bs.send]
external toString: t -> Js.String.t = "" [@@bs.send]
external toStringWithEncoding: t -> encoding:Js.String.t -> Js.String.t =
"toString" [@@bs.send]
external toStringWithEncodingOffset: t -> encoding:Js.String.t -> start:int
-> Js.String.t = "toString" [@@bs.send]
external toStringWithEncodingRange: t -> encoding:Js.String.t -> start:int
-> end_:int -> Js.String.t = "toString" [@@bs.send]
FIXME after iterators support
(* external values : t -> Iterator = "" [@@bs.get] *)
external write : t -> Js.String.t -> int = "" [@@bs.send]
external writeOffset : t -> value:Js.String.t -> offset:int -> int =
"write" [@@bs.send]
external writeRange : t -> value:Js.String.t -> offset:int -> length:int -> int =
"write" [@@bs.send]
external writeRangeWithEncoding : t -> value:Js.String.t -> offset:int ->
length:int -> encoding:Js.String.t -> int = "write" [@@bs.send]
external writeDoubleBigEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeDoubleBigEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeDoubleBE" [@@bs.send]
external writeDoubleLittleEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeDoubleLittleEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeDoubleLE" [@@bs.send]
external writeFloatBigEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeFloatBigEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeFloatBE" [@@bs.send]
external writeFloatLittleEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeFloatLittleEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeFloatLE" [@@bs.send]
external writeInt8 : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt8NoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt8" [@@bs.send]
external writeInt16BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt16BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt16BE" [@@bs.send]
external writeInt16LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt16LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt16LE" [@@bs.send]
external writeInt32BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt32BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt32BE" [@@bs.send]
external writeInt32LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt32LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt32LE" [@@bs.send]
external writeIntBigEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeIntBigEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeIntBE" [@@bs.send]
external writeIntLittleEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeIntLittleEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeIntLE" [@@bs.send]
external writeUint8 : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint8NoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint8" [@@bs.send]
external writeUint16BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint16BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint16BE" [@@bs.send]
external writeUint16LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint16LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint16LE" [@@bs.send]
external writeUint32BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint32BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint32BE" [@@bs.send]
external writeUint32LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint32LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint32LE" [@@bs.send]
external writeUintBigEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeUintBigEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeUintBE" [@@bs.send]
external writeUintLittleEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeUintLittleEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeUintLE" [@@bs.send]
external _INSPECT_MAX_BYTES : t -> int = "INSPECT_MAX_BYTES" [@@bs.get]
external kMaxLength : t -> int = "" [@@bs.get]
external transcode : t -> source:t -> from:Js.String.t -> to_:Js.String.t ->
t = "" [@@bs.send]
| null | https://raw.githubusercontent.com/reasonml-old/bs-node/d1fd002b0391c6e4b153d90c38fe60e0ac800487/src/nodeBuffer.ml | ocaml | external entries : t -> Iterator = "" [@@bs.get]
external keys : t -> Iterator = "" [@@bs.send]
external values : t -> Iterator = "" [@@bs.get] | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
*
* 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 , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
open Js.Typed_array
type t
external fromString : Js.String.t -> t = "Buffer.from" [@@bs.val]
external fromStringWithEncoding : Js.String.t -> encoding:Js.String.t -> t =
"Buffer.from" [@@bs.val]
external fromArray : int array -> t = "Buffer.from" [@@bs.val]
external fromArrayBuffer : ArrayBuffer.t -> t = "Buffer.from" [@@bs.val]
external fromArrayBufferOffset: ArrayBuffer.t -> offset:int -> t =
"Buffer.from" [@@bs.val]
external fromArrayBufferRange: ArrayBuffer.t -> offset:int ->
length:int -> t = "Buffer.from" [@@bs.val]
external fromBuffer: t -> t = "Buffer.from" [@@bs.val]
external alloc: int -> t = "Buffer.alloc" [@@bs.val]
external allocFillInt: int -> fill:int -> t = "Buffer.alloc" [@@bs.val]
external allocFillString: int -> fill:Js.String.t -> t = "Buffer.alloc" [@@bs.val]
external allocFillStringWithEncoding: int -> fill:Js.String.t ->
encoding:Js.String.t -> t = "Buffer.alloc" [@@bs.val]
external allocFillBuffer: int -> fill:t -> t = "Buffer.alloc" [@@bs.val]
external allocUnsafe: int -> t = "Buffer.allocUnsafe" [@@bs.val]
external allocUnsafeSlow: int -> t = "Buffer.allocUnsafeSlow" [@@bs.val]
external unsafeGet : t -> int -> int = "" [@@bs.get_index]
external unsafeSet : t -> int -> int -> unit = "" [@@bs.set_index]
external byteLengthString : Js.String.t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthStringWithEncoding : Js.String.t -> encoding:Js.String.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthBuffer : t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthInt8Array : Int8Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint8Array : Uint8Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthInt16Array : Int16Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint16Array : Uint16Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthInt32Array : Int32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthUint32Array : Uint32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthFloat32Array : Float32Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthFloat64Array : Float64Array.t -> int =
"Buffer.byteLength" [@@bs.val]
external byteLengthDataView : DataView.t -> int = "Buffer.byteLength" [@@bs.val]
external byteLengthArrayBuffer : ArrayBuffer.t -> int = "Buffer.byteLength" [@@bs.val]
external compare : t -> t -> int = "Buffer.compare" [@@bs.val]
external concat : t array -> t = "Buffer.concat" [@@bs.val]
external concatLength : t array -> length:int -> t = "Buffer.concat" [@@bs.val]
external isEncoding : Js.String.t -> bool = "Buffer.isEncoding" [@@bs.val]
type buffer
external buffer : buffer = "Buffer" [@@bs.val]
external poolSize : int = "Buffer.poolSize" [@@bs.val]
external setPoolSize : buffer -> int -> int = "poolSize" [@@bs.set]
let setPoolSize n = setPoolSize buffer n
external copy : t -> t -> int = "" [@@bs.send]
external copyOffset : t -> t -> targetStart:int -> int = "copy" [@@bs.send]
external copyOffsetFromOffset : t -> t -> targetStart:int -> sourceStart:int ->
int = "copy" [@@bs.send]
external copyOffsetFromRange : t -> t -> targetStart:int -> sourceStart:int ->
sourceEnd:int -> int = "copy" [@@bs.send]
external copyToUint8Array : t -> Uint8Array.t -> int = "copy" [@@bs.send]
external copyToUint8ArrayOffset : t -> Uint8Array.t -> targetStart:int ->
int = "copy" [@@bs.send]
external copyToUint8ArrayFrom: t -> Uint8Array.t -> targetStart:int ->
sourceStart:int -> int = "copy" [@@bs.send]
external copyToUint8ArrayFromRange : t -> Uint8Array.t -> targetStart:int ->
sourceStart:int -> sourceEnd:int -> int = "copy" [@@bs.send]
FIXME after iterators support
external equals : t -> t -> bool = "" [@@bs.send]
external fillString : t -> Js.String.t -> t = "fill" [@@bs.send]
external fillStringOffset : t -> value:Js.String.t -> offset:int -> t =
"fill" [@@bs.send]
external fillStringRange : t -> value:Js.String.t -> offset:int ->
end_:int -> t = "fill" [@@bs.send]
external fillStringRangeWithEncoding : t -> value:Js.String.t -> offset:int ->
end_:int -> encoding:Js.String.t -> t = "fill" [@@bs.send]
external fillBuffer : t -> t -> t = "fill" [@@bs.send]
external fillBufferOffset : t -> value:t -> offset:int -> t = "fill" [@@bs.send]
external fillBufferRange : t -> value:t -> offset:int -> end_:int -> t =
"fill" [@@bs.send]
external fillInt : t -> int -> t = "fill" [@@bs.send]
external fillIntOffset : t -> value:int -> offset:int -> t = "fill" [@@bs.send]
external fillIntRange : t -> value:int -> offset:int -> end_:int -> t =
"fill" [@@bs.send]
external includesString : t -> Js.String.t -> bool = "includes" [@@bs.send]
external includesStringFrom : t -> value:Js.String.t -> offset:int -> bool =
"includes" [@@bs.send]
external includesStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> bool ="includes" [@@bs.send]
external includesBuffer : t -> t -> bool = "includes" [@@bs.send]
external includesBufferFrom : t -> value:t -> offset:int -> bool =
"includes" [@@bs.send]
external includesInt : t -> int -> bool = "includes" [@@bs.send]
external includesIntFrom : t -> value:int -> offset:int -> bool =
"includes" [@@bs.send]
external indexOfString : t -> Js.String.t -> int = "indexOf" [@@bs.send]
external indexOfStringFrom : t -> value:Js.String.t -> offset:int -> int =
"indexOf" [@@bs.send]
external indexOfStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> int ="indexOf" [@@bs.send]
external indexOfBuffer : t -> t -> int = "indexOf" [@@bs.send]
external indexOfBufferFrom : t -> value:t -> offset:int -> int =
"indexOf" [@@bs.send]
external indexOfInt : t -> int -> int = "indexOf" [@@bs.send]
external indexOfIntFrom : t -> value:int -> offset:int -> int =
"indexOf" [@@bs.send]
FIXME after iterators support
external lastIndexOfString : t -> Js.String.t -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfStringFrom : t -> value:Js.String.t -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external lastIndexOfStringWithEncodingFrom : t -> value:Js.String.t -> offset:int ->
encoding:Js.String.t -> int ="lastIndexOf" [@@bs.send]
external lastIndexOfBuffer : t -> t -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfBufferFrom : t -> value:t -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external lastIndexOfInt : t -> int -> int = "lastIndexOf" [@@bs.send]
external lastIndexOfIntFrom : t -> value:int -> offset:int -> int =
"lastIndexOf" [@@bs.send]
external length : t -> int = "" [@@bs.get]
external readDoubleBigEndian : t -> offset:int -> float = "" [@@bs.send]
external readDoubleBigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readDoubleBE" [@@bs.send]
external readDoubleLittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readDoubleLittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readDoubleLE" [@@bs.send]
external readFloatBigEndian : t -> offset:int -> float = "" [@@bs.send]
external readFloatBigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readFloatBE" [@@bs.send]
external readFloatLittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readFloatLittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readFloatLE" [@@bs.send]
external readInt8 : t -> offset:int -> float = "" [@@bs.send]
external readInt8NoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt8" [@@bs.send]
external readInt16BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt16BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt16BE" [@@bs.send]
external readInt16LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt16LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt16LE" [@@bs.send]
external readInt32BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt32BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt32BE" [@@bs.send]
external readInt32LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readInt32LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readInt32LE" [@@bs.send]
external readIntBigEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readIntBigEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readIntBE" [@@bs.send]
external readIntLittleEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readIntLittleEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readIntLE" [@@bs.send]
external readUint8 : t -> offset:int -> float = "" [@@bs.send]
external readUint8NoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint8" [@@bs.send]
external readUint16BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint16BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint16BE" [@@bs.send]
external readUint16LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint16LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint16LE" [@@bs.send]
external readUint32BigEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint32BigEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint32BE" [@@bs.send]
external readUint32LittleEndian : t -> offset:int -> float = "" [@@bs.send]
external readUint32LittleEndianNoAssert : t -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"readUint32LE" [@@bs.send]
external readUintBigEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readUintBigEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readUintBE" [@@bs.send]
external readUintLittleEndian : t -> offset:int -> length:int -> float = "" [@@bs.send]
external readUintLittleEndianNoAssert : t -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "readUintLE" [@@bs.send]
external slice : t -> t = "" [@@bs.send]
external sliceOffset : t -> start:int -> t = "slice" [@@bs.send]
external sliceRange : t -> start:int -> end_:int -> t = "slice" [@@bs.send]
external swap16 : t -> t = "" [@@bs.send]
external swap32 : t -> t = "" [@@bs.send]
external swap64 : t -> t = "" [@@bs.send]
external toJSON : t -> < .. > Js.t = "" [@@bs.send]
external toString: t -> Js.String.t = "" [@@bs.send]
external toStringWithEncoding: t -> encoding:Js.String.t -> Js.String.t =
"toString" [@@bs.send]
external toStringWithEncodingOffset: t -> encoding:Js.String.t -> start:int
-> Js.String.t = "toString" [@@bs.send]
external toStringWithEncodingRange: t -> encoding:Js.String.t -> start:int
-> end_:int -> Js.String.t = "toString" [@@bs.send]
FIXME after iterators support
external write : t -> Js.String.t -> int = "" [@@bs.send]
external writeOffset : t -> value:Js.String.t -> offset:int -> int =
"write" [@@bs.send]
external writeRange : t -> value:Js.String.t -> offset:int -> length:int -> int =
"write" [@@bs.send]
external writeRangeWithEncoding : t -> value:Js.String.t -> offset:int ->
length:int -> encoding:Js.String.t -> int = "write" [@@bs.send]
external writeDoubleBigEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeDoubleBigEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeDoubleBE" [@@bs.send]
external writeDoubleLittleEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeDoubleLittleEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeDoubleLE" [@@bs.send]
external writeFloatBigEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeFloatBigEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeFloatBE" [@@bs.send]
external writeFloatLittleEndian : t -> value:float -> offset:int -> float = "" [@@bs.send]
external writeFloatLittleEndianNoAssert : t -> value:float -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeFloatLE" [@@bs.send]
external writeInt8 : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt8NoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt8" [@@bs.send]
external writeInt16BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt16BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt16BE" [@@bs.send]
external writeInt16LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt16LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt16LE" [@@bs.send]
external writeInt32BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt32BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt32BE" [@@bs.send]
external writeInt32LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeInt32LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeInt32LE" [@@bs.send]
external writeIntBigEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeIntBigEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeIntBE" [@@bs.send]
external writeIntLittleEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeIntLittleEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeIntLE" [@@bs.send]
external writeUint8 : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint8NoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint8" [@@bs.send]
external writeUint16BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint16BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint16BE" [@@bs.send]
external writeUint16LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint16LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint16LE" [@@bs.send]
external writeUint32BigEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint32BigEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint32BE" [@@bs.send]
external writeUint32LittleEndian : t -> value:int -> offset:int -> float = "" [@@bs.send]
external writeUint32LittleEndianNoAssert : t -> value:int -> offset:int -> (_ [@bs.as {json|true|json}]) -> float =
"writeUint32LE" [@@bs.send]
external writeUintBigEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeUintBigEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeUintBE" [@@bs.send]
external writeUintLittleEndian : t -> value:int -> offset:int -> length:int -> float = "" [@@bs.send]
external writeUintLittleEndianNoAssert : t -> value:int -> offset:int -> length:int -> (_ [@bs.as {json|true|json}]) ->
float = "writeUintLE" [@@bs.send]
external _INSPECT_MAX_BYTES : t -> int = "INSPECT_MAX_BYTES" [@@bs.get]
external kMaxLength : t -> int = "" [@@bs.get]
external transcode : t -> source:t -> from:Js.String.t -> to_:Js.String.t ->
t = "" [@@bs.send]
|
8cb72443583d07a33474a54c7d1fb84c847f29c26a0f416dcf146c4107e1f109 | qfpl/reflex-tutorial | Attach.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Util.Attach (
attachId
, attachId_
) where
import qualified Data.Text as T
import Reflex.Dom.Core
import GHCJS.DOM
import GHCJS.DOM.NonElementParentNode
import Language.Javascript.JSaddle.Monad (MonadJSM, liftJSM)
attachId ::
MonadJSM m =>
T.Text ->
(forall x. Widget x a) ->
m (Maybe a)
attachId eid w =
withJSContextSingleton $ \jsSing -> do
doc <- currentDocumentUnchecked
root <- getElementById doc eid
case root of
Nothing ->
return Nothing
Just docRoot -> do
x <- liftJSM $ attachWidget docRoot jsSing w
pure $ Just x
attachId_ ::
MonadJSM m =>
T.Text ->
(forall x. Widget x a) ->
m ()
attachId_ eid w = do
_ <- attachId eid w
pure ()
| null | https://raw.githubusercontent.com/qfpl/reflex-tutorial/07c1e6fab387cbeedd031630ba6a5cd946cc612e/code/common/src/Util/Attach.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes # | module Util.Attach (
attachId
, attachId_
) where
import qualified Data.Text as T
import Reflex.Dom.Core
import GHCJS.DOM
import GHCJS.DOM.NonElementParentNode
import Language.Javascript.JSaddle.Monad (MonadJSM, liftJSM)
attachId ::
MonadJSM m =>
T.Text ->
(forall x. Widget x a) ->
m (Maybe a)
attachId eid w =
withJSContextSingleton $ \jsSing -> do
doc <- currentDocumentUnchecked
root <- getElementById doc eid
case root of
Nothing ->
return Nothing
Just docRoot -> do
x <- liftJSM $ attachWidget docRoot jsSing w
pure $ Just x
attachId_ ::
MonadJSM m =>
T.Text ->
(forall x. Widget x a) ->
m ()
attachId_ eid w = do
_ <- attachId eid w
pure ()
|
e1b2a6aea8912bd7792f4fbe8f627031994677f23bfa3f365eb3ef39574c5ef4 | realworldocaml/book | odoc.mli | (** Odoc rules *)
open Import
val setup_library_odoc_rules :
Compilation_context.t -> Lib.Local.t -> unit Memo.t
val gen_project_rules : Super_context.t -> Dune_project.t -> unit Memo.t
val setup_private_library_doc_alias :
Super_context.t
-> scope:Scope.t
-> dir:Stdune.Path.Build.t
-> Dune_file.Library.t
-> unit Memo.t
val gen_rules :
Super_context.t
-> dir:Path.Build.t
-> string list
-> Build_config.gen_rules_result Memo.t
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/odoc.mli | ocaml | * Odoc rules |
open Import
val setup_library_odoc_rules :
Compilation_context.t -> Lib.Local.t -> unit Memo.t
val gen_project_rules : Super_context.t -> Dune_project.t -> unit Memo.t
val setup_private_library_doc_alias :
Super_context.t
-> scope:Scope.t
-> dir:Stdune.Path.Build.t
-> Dune_file.Library.t
-> unit Memo.t
val gen_rules :
Super_context.t
-> dir:Path.Build.t
-> string list
-> Build_config.gen_rules_result Memo.t
|
1e09567e6e355a05fddab90cdd55e06f56177cb1e48674c07329a1193f1eaa57 | Leystryku/mpbomberman_racket | cl_render_game.rkt | #lang racket
;; imports
(require 2htdp/image)
(require lang/posn)
(require "cl_helper.rkt")
(require "sh_config.rkt")
(require "sh_helper.rkt")
(require "sh_structs.rkt")
(require "sh_config_textures.rkt")
;; exports
(provide (all-defined-out))
[ renderHandleAnimFrameAdvanceLoop ] Advances a animation frame . If at frame end , reset to first frame ( loop )
(define (renderHandleAnimFrameAdvanceLoop tickCount anim newTextureNum)
(and
(set-animatedTexture-ticksWhenNextAnim! anim (+ tickCount (animatedTexture-frameAdvanceTicks anim)) )
(if (> newTextureNum (length (animatedTexture-textures anim)))
(set-animatedTexture-currentTextureNum! anim 1)
(set-animatedTexture-currentTextureNum! anim newTextureNum)
)
anim
)
)
;; [renderHandleAnimFrameAdvanceNoLoop] Advances a animation frame. If at frame end, do not change anything (no loop)
(define (renderHandleAnimFrameAdvanceNoLoop tickCount anim newTextureNum)
(and
(set-animatedTexture-ticksWhenNextAnim! anim (+ tickCount (animatedTexture-frameAdvanceTicks anim)) )
(if (> newTextureNum (length (animatedTexture-textures anim)))
anim
(set-animatedTexture-currentTextureNum! anim newTextureNum)
)
)
)
;; [renderHandleAnimFrameAdvance] Calls the fitting function to advance the animation frame depending on the loop settings and incrments the current textureNumber
(define (renderHandleAnimFrameAdvance tickCount anim)
(let ([newTextureNum (+ 1 (animatedTexture-currentTextureNum anim))])
(if (animatedTexture-shouldLoop anim)
(renderHandleAnimFrameAdvanceLoop tickCount anim newTextureNum)
(renderHandleAnimFrameAdvanceNoLoop tickCount anim newTextureNum)
)
)
)
;; [renderHandleAnimFrameAdvance] Checks if frame should be advanced. If yes, call [renderHandleAnimFrameAdvance] to advance it
(define (renderHandleAnimFrameAdvanceIfShould tickCount anim)
(if (or (animatedTexture-isPaused anim) (> (animatedTexture-ticksWhenNextAnim anim) tickCount))
anim
(renderHandleAnimFrameAdvance tickCount anim)
)
)
;; [renderHandleAnimFrame] Renders a frame of a animatedTexture
(define (renderHandleAnimFrame tickCount anim)
(define textures (animatedTexture-textures anim))
(define currentTextureNum (animatedTexture-currentTextureNum anim))
(list-ref textures (- currentTextureNum 1))
)
;; [renderGameElementG] Renders a game element using [renderHandleAnimFrame] and does the advancement handling by calling [renderHandleAnimFrameAdvanceIfShould]
(define (renderGameElementG tickCount elem anim extraData)
(and
(renderHandleAnimFrameAdvanceIfShould tickCount anim)
(renderHandleAnimFrame tickCount anim)
)
)
;; [renderGameElement] Calls [renderGameElementG] for valid elements. If a elementName is unknown, draws a error
(define (renderGameElement tickCount elem anim extraData)
(define elementName (fieldElement-elementName elem))
(case elementName
['unbreakableTile (renderGameElementG tickCount elem anim extraData) ]
['breakableTile (renderGameElementG tickCount elem anim extraData) ]
['breakingTile (renderGameElementG tickCount elem anim extraData) ]
['bomb (renderGameElementG tickCount elem anim extraData) ]
['explosion (renderGameElementG tickCount elem anim extraData) ]
[else (text (string-append (symbol->string elementName) "IS NOT A VALID ELEMENT") 18 "red")]
)
)
;; [renderGameElementCollisions] Draws collision bounds for 'breakableTile and 'unbreakableTile, for other elements calls [renderGameElement]
(define (renderGameElementCollisions tickCount elem anim extraData)
(cond
[(equal? (fieldElement-elementName elem) 'unbreakableTile) (rectangle (tileToCoord (fieldElement-wtiles elem)) (tileToCoord (fieldElement-ytiles elem)) "solid" "blue") ]
[(equal? (fieldElement-elementName elem) 'breakableTile) (rectangle (tileToCoord (fieldElement-wtiles elem)) (tileToCoord (fieldElement-ytiles elem)) "solid" "white") ]
[else (renderGameElement tickCount elem anim extraData)]
)
)
;; [renderGameElementsEWithCollisions] Renders game elements with drawing collision bounds
(define (renderGameElementsEWithCollisions tickCount elements)
(for/list ([element elements])
(renderGameElementCollisions tickCount element (fieldElement-animatedTexture element) (fieldElement-extraData element))
)
)
;; [renderGameElementsEWithoutCollisions] Renders game elements without drawing collision bounds
(define (renderGameElementsEWithoutCollisions tickCount elements)
(for/list ([element elements])
(renderGameElement tickCount element (fieldElement-animatedTexture element) (fieldElement-extraData element))
)
)
;; [renderGameElementsE] Calls the right render function depending on whether game should render collisionBounds
(define (renderGameElementsE world tickCount elements)
(if gameRenderCollisionBounds
(renderGameElementsEWithCollisions tickCount elements)
(renderGameElementsEWithoutCollisions tickCount (filter (lambda (elem) (not (equal? (fieldElement-elementName elem) 'unbreakableTile))) elements) )
)
)
;; [renderGameElementsP] Calculates the posn for every game Element
(define (renderGameElementsP elements)
(for/list ([element elements])
(make-posn (tileToCoord (fieldElement-xtiles element)) (tileToCoordY (fieldElement-ytiles element)))
)
)
;; [renderPlayer] Gets the current active texture of the player, calls funcs to render it and advance if needed
(define (renderPlayer tickCount player)
(let* (
[facingDir (player-facingDir player)]
[facingSince (player-facingSince player)]
[animtextures (player-animatedTextures player)]
[anim (assoc facingDir animtextures)])
(if anim
(if (> (+ 100 facingSince) (current-inexact-milliseconds) )
(and (renderHandleAnimFrameAdvanceIfShould tickCount (second anim)) (renderHandleAnimFrame tickCount (second anim)))
(renderHandleAnimFrame tickCount (second anim))
)
(rectangle
gameTileSize
gameTileSize
"solid"
"grey"
)
)
)
)
;; [renderPlayersE] Renders all the players
(define (renderPlayersE tickCount currentWorld)
(define players (clientsideWorld-players currentWorld))
(for/list ([player players])
(renderPlayer tickCount player)
)
)
;; [renderPlayersP] Calcuates the posn for every player
(define (renderPlayersP currentWorld)
(define players (clientsideWorld-players currentWorld))
(for/list ([player players])
(make-posn (player-x player) (+ (player-y player) gameScoreHeight))
)
)
;; [renderGameScore] Renders our current score
(define (renderGameScore currentWorld localPlayer)
(place-images/align
(list
(text
(string-append " TIME " (string-append (number->string (clientsideWorld-timeLeft currentWorld)) " ") "CURSCORE " (number->string (player-score localPlayer)) " LIVES " (number->string (player-lives localPlayer)))
24
"white"
)
)
(list
(make-posn 0 (* gameScoreHeight 0.4))
)
"left"
"top"
(rectangle
gameWidth
gameScoreHeight
"solid"
"grey"
)
)
)
;; [renderRespawnText] Renders the respawn text
(define (renderRespawnText currentWorld localPlayer)
(if (player-alive localPlayer)
(text "" 1 "white")
(text "HIT SPACE TO RESPAWN" 18 "red")
)
)
[ renderGameOver ] Renders
(define (renderGameOver currentWorld localPlayer)
(place-images/align
(list
(text
(string-append " TIME 0 CURSCORE 0 GAME OVER ")
24
"red"
)
)
(list
(make-posn 0 (* gameScoreHeight 0.4))
)
"left"
"top"
(rectangle
gameWidth
gameScoreHeight
"solid"
"black"
)
)
)
[ renderGameR ] Renders the HUD
(define (renderHUD currentWorld localPlayer)
(if (and (not (player-alive localPlayer)) (= 0 (player-lives localPlayer)))
(list
(renderGameOver currentWorld localPlayer)
(text "" 1 "white")
)
(list
(renderRespawnText currentWorld localPlayer)
(renderGameScore currentWorld localPlayer)
)
)
)
;; [renderGameR] Renders the current game
(define (renderGameR currentWorld elements)
(define localPlayer (getLocalPlayer currentWorld))
(place-images/align
(append
(renderHUD currentWorld localPlayer)
(renderGameElementsE currentWorld (clientsideWorld-tickCount currentWorld) elements)
(renderPlayersE (clientsideWorld-tickCount currentWorld) currentWorld)
)
(append
(list (make-posn 0 0) (make-posn 0 0) )
(renderGameElementsP elements)
(renderPlayersP currentWorld)
)
"left"
"top"
gameBackgroundTexture
)
)
;; [renderGame] Calls functions to render the game and if collision bounds should not be drawn, removes 'unbreakableTile from element list (since we don't need to draw them extra)
(define (renderGame currentWorld)
(if gameRenderCollisionBounds
(renderGameR currentWorld (clientsideWorld-gameField currentWorld))
(renderGameR currentWorld (filter (lambda (elem) (not (equal? (fieldElement-elementName elem) 'unbreakableTile)) ) (clientsideWorld-gameField currentWorld)))
)
) | null | https://raw.githubusercontent.com/Leystryku/mpbomberman_racket/059d95040cfad2e27237f8dd41fc32a4fc698afe/game/cl_render_game.rkt | racket | imports
exports
[renderHandleAnimFrameAdvanceNoLoop] Advances a animation frame. If at frame end, do not change anything (no loop)
[renderHandleAnimFrameAdvance] Calls the fitting function to advance the animation frame depending on the loop settings and incrments the current textureNumber
[renderHandleAnimFrameAdvance] Checks if frame should be advanced. If yes, call [renderHandleAnimFrameAdvance] to advance it
[renderHandleAnimFrame] Renders a frame of a animatedTexture
[renderGameElementG] Renders a game element using [renderHandleAnimFrame] and does the advancement handling by calling [renderHandleAnimFrameAdvanceIfShould]
[renderGameElement] Calls [renderGameElementG] for valid elements. If a elementName is unknown, draws a error
[renderGameElementCollisions] Draws collision bounds for 'breakableTile and 'unbreakableTile, for other elements calls [renderGameElement]
[renderGameElementsEWithCollisions] Renders game elements with drawing collision bounds
[renderGameElementsEWithoutCollisions] Renders game elements without drawing collision bounds
[renderGameElementsE] Calls the right render function depending on whether game should render collisionBounds
[renderGameElementsP] Calculates the posn for every game Element
[renderPlayer] Gets the current active texture of the player, calls funcs to render it and advance if needed
[renderPlayersE] Renders all the players
[renderPlayersP] Calcuates the posn for every player
[renderGameScore] Renders our current score
[renderRespawnText] Renders the respawn text
[renderGameR] Renders the current game
[renderGame] Calls functions to render the game and if collision bounds should not be drawn, removes 'unbreakableTile from element list (since we don't need to draw them extra) | #lang racket
(require 2htdp/image)
(require lang/posn)
(require "cl_helper.rkt")
(require "sh_config.rkt")
(require "sh_helper.rkt")
(require "sh_structs.rkt")
(require "sh_config_textures.rkt")
(provide (all-defined-out))
[ renderHandleAnimFrameAdvanceLoop ] Advances a animation frame . If at frame end , reset to first frame ( loop )
(define (renderHandleAnimFrameAdvanceLoop tickCount anim newTextureNum)
(and
(set-animatedTexture-ticksWhenNextAnim! anim (+ tickCount (animatedTexture-frameAdvanceTicks anim)) )
(if (> newTextureNum (length (animatedTexture-textures anim)))
(set-animatedTexture-currentTextureNum! anim 1)
(set-animatedTexture-currentTextureNum! anim newTextureNum)
)
anim
)
)
(define (renderHandleAnimFrameAdvanceNoLoop tickCount anim newTextureNum)
(and
(set-animatedTexture-ticksWhenNextAnim! anim (+ tickCount (animatedTexture-frameAdvanceTicks anim)) )
(if (> newTextureNum (length (animatedTexture-textures anim)))
anim
(set-animatedTexture-currentTextureNum! anim newTextureNum)
)
)
)
(define (renderHandleAnimFrameAdvance tickCount anim)
(let ([newTextureNum (+ 1 (animatedTexture-currentTextureNum anim))])
(if (animatedTexture-shouldLoop anim)
(renderHandleAnimFrameAdvanceLoop tickCount anim newTextureNum)
(renderHandleAnimFrameAdvanceNoLoop tickCount anim newTextureNum)
)
)
)
(define (renderHandleAnimFrameAdvanceIfShould tickCount anim)
(if (or (animatedTexture-isPaused anim) (> (animatedTexture-ticksWhenNextAnim anim) tickCount))
anim
(renderHandleAnimFrameAdvance tickCount anim)
)
)
(define (renderHandleAnimFrame tickCount anim)
(define textures (animatedTexture-textures anim))
(define currentTextureNum (animatedTexture-currentTextureNum anim))
(list-ref textures (- currentTextureNum 1))
)
(define (renderGameElementG tickCount elem anim extraData)
(and
(renderHandleAnimFrameAdvanceIfShould tickCount anim)
(renderHandleAnimFrame tickCount anim)
)
)
(define (renderGameElement tickCount elem anim extraData)
(define elementName (fieldElement-elementName elem))
(case elementName
['unbreakableTile (renderGameElementG tickCount elem anim extraData) ]
['breakableTile (renderGameElementG tickCount elem anim extraData) ]
['breakingTile (renderGameElementG tickCount elem anim extraData) ]
['bomb (renderGameElementG tickCount elem anim extraData) ]
['explosion (renderGameElementG tickCount elem anim extraData) ]
[else (text (string-append (symbol->string elementName) "IS NOT A VALID ELEMENT") 18 "red")]
)
)
(define (renderGameElementCollisions tickCount elem anim extraData)
(cond
[(equal? (fieldElement-elementName elem) 'unbreakableTile) (rectangle (tileToCoord (fieldElement-wtiles elem)) (tileToCoord (fieldElement-ytiles elem)) "solid" "blue") ]
[(equal? (fieldElement-elementName elem) 'breakableTile) (rectangle (tileToCoord (fieldElement-wtiles elem)) (tileToCoord (fieldElement-ytiles elem)) "solid" "white") ]
[else (renderGameElement tickCount elem anim extraData)]
)
)
(define (renderGameElementsEWithCollisions tickCount elements)
(for/list ([element elements])
(renderGameElementCollisions tickCount element (fieldElement-animatedTexture element) (fieldElement-extraData element))
)
)
(define (renderGameElementsEWithoutCollisions tickCount elements)
(for/list ([element elements])
(renderGameElement tickCount element (fieldElement-animatedTexture element) (fieldElement-extraData element))
)
)
(define (renderGameElementsE world tickCount elements)
(if gameRenderCollisionBounds
(renderGameElementsEWithCollisions tickCount elements)
(renderGameElementsEWithoutCollisions tickCount (filter (lambda (elem) (not (equal? (fieldElement-elementName elem) 'unbreakableTile))) elements) )
)
)
(define (renderGameElementsP elements)
(for/list ([element elements])
(make-posn (tileToCoord (fieldElement-xtiles element)) (tileToCoordY (fieldElement-ytiles element)))
)
)
(define (renderPlayer tickCount player)
(let* (
[facingDir (player-facingDir player)]
[facingSince (player-facingSince player)]
[animtextures (player-animatedTextures player)]
[anim (assoc facingDir animtextures)])
(if anim
(if (> (+ 100 facingSince) (current-inexact-milliseconds) )
(and (renderHandleAnimFrameAdvanceIfShould tickCount (second anim)) (renderHandleAnimFrame tickCount (second anim)))
(renderHandleAnimFrame tickCount (second anim))
)
(rectangle
gameTileSize
gameTileSize
"solid"
"grey"
)
)
)
)
(define (renderPlayersE tickCount currentWorld)
(define players (clientsideWorld-players currentWorld))
(for/list ([player players])
(renderPlayer tickCount player)
)
)
(define (renderPlayersP currentWorld)
(define players (clientsideWorld-players currentWorld))
(for/list ([player players])
(make-posn (player-x player) (+ (player-y player) gameScoreHeight))
)
)
(define (renderGameScore currentWorld localPlayer)
(place-images/align
(list
(text
(string-append " TIME " (string-append (number->string (clientsideWorld-timeLeft currentWorld)) " ") "CURSCORE " (number->string (player-score localPlayer)) " LIVES " (number->string (player-lives localPlayer)))
24
"white"
)
)
(list
(make-posn 0 (* gameScoreHeight 0.4))
)
"left"
"top"
(rectangle
gameWidth
gameScoreHeight
"solid"
"grey"
)
)
)
(define (renderRespawnText currentWorld localPlayer)
(if (player-alive localPlayer)
(text "" 1 "white")
(text "HIT SPACE TO RESPAWN" 18 "red")
)
)
[ renderGameOver ] Renders
(define (renderGameOver currentWorld localPlayer)
(place-images/align
(list
(text
(string-append " TIME 0 CURSCORE 0 GAME OVER ")
24
"red"
)
)
(list
(make-posn 0 (* gameScoreHeight 0.4))
)
"left"
"top"
(rectangle
gameWidth
gameScoreHeight
"solid"
"black"
)
)
)
[ renderGameR ] Renders the HUD
(define (renderHUD currentWorld localPlayer)
(if (and (not (player-alive localPlayer)) (= 0 (player-lives localPlayer)))
(list
(renderGameOver currentWorld localPlayer)
(text "" 1 "white")
)
(list
(renderRespawnText currentWorld localPlayer)
(renderGameScore currentWorld localPlayer)
)
)
)
(define (renderGameR currentWorld elements)
(define localPlayer (getLocalPlayer currentWorld))
(place-images/align
(append
(renderHUD currentWorld localPlayer)
(renderGameElementsE currentWorld (clientsideWorld-tickCount currentWorld) elements)
(renderPlayersE (clientsideWorld-tickCount currentWorld) currentWorld)
)
(append
(list (make-posn 0 0) (make-posn 0 0) )
(renderGameElementsP elements)
(renderPlayersP currentWorld)
)
"left"
"top"
gameBackgroundTexture
)
)
(define (renderGame currentWorld)
(if gameRenderCollisionBounds
(renderGameR currentWorld (clientsideWorld-gameField currentWorld))
(renderGameR currentWorld (filter (lambda (elem) (not (equal? (fieldElement-elementName elem) 'unbreakableTile)) ) (clientsideWorld-gameField currentWorld)))
)
) |
a2fe112c73f0672b426eb334c2f28fca9355be189f807788cd8b1d38ad1588f6 | msgpack/msgpack-haskell | Aeson.hs | {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
| Aeson bridge for MessagePack
module Data.MessagePack.Aeson (
-- * Conversion functions
toAeson, fromAeson,
unsafeViaToJSON, viaFromJSON,
-- * Wrapper instances
AsMessagePack(..),
AsAeson(..),
MessagePackAesonError(..),
-- * Utility functions
packAeson, unpackAeson,
decodeMessagePack, encodeMessagePack,
) where
import Control.Applicative
import Control.Arrow
import Control.DeepSeq
import Control.Exception
import Data.Aeson as A
import qualified Data.ByteString.Lazy as L (ByteString)
import Data.Data
import qualified Data.HashMap.Strict as HM
import Data.Int
import Data.Maybe
import Data.MessagePack as MP
import Data.MessagePack.Integer
import Data.Scientific
import qualified Data.Text.Encoding as T
import Data.Traversable (traverse)
import qualified Data.Vector as V
import Data.Word
-- | Convert 'MP.Object' to JSON 'Value'
toAeson :: MP.Object -> A.Result Value
toAeson = \case
ObjectNil -> pure Null
ObjectBool b -> pure (Bool b)
ObjectInt n -> pure $! Number $! fromIntegral n
ObjectFloat f -> pure $! Number $! realToFrac f
ObjectDouble d -> pure $! Number $! realToFrac d
ObjectStr t -> pure (String t)
ObjectBin b -> fail $ "ObjectBin is not supported by JSON"
ObjectArray v -> Array <$> V.mapM toAeson v
ObjectMap m ->
A.Object . HM.fromList . V.toList
<$> V.mapM (\(k, v) -> (,) <$> from k <*> toAeson v) m
where from = mpResult fail pure . MP.fromObject
ObjectExt _ _ -> fail "ObjectExt is not supported by JSON"
-- | Convert JSON 'Value' to 'MP.Object'
fromAeson :: Value -> MP.Result MP.Object
fromAeson = \case
Null -> pure ObjectNil
Bool b -> pure $ ObjectBool b
Number s ->
NOTE floatingOrInteger can OOM on untrusted input
case floatingOrInteger s of
Left n -> pure $ ObjectDouble n
Right (fromIntegerTry -> Right n) -> pure $ ObjectInt n
Right _ -> fail "number out of bounds"
String t -> pure $ ObjectStr t
Array v -> ObjectArray <$> traverse fromAeson v
A.Object o -> (ObjectMap . V.fromList) <$> traverse fromEntry (HM.toList o)
where
fromEntry (k, v) = (\a -> (ObjectStr k, a)) <$> fromAeson v
Helpers to piggyback off a JSON encoder / decoder when creating a MessagePack
-- instance.
--
-- Not as efficient as a direct encoder.
viaFromJSON :: FromJSON a => MP.Object -> MP.Result a
viaFromJSON o = case toAeson o >>= fromJSON of
A.Success a -> MP.Success a
A.Error e -> MP.Error e
WARNING : not total for JSON numbers outside the 64 bit range
unsafeViaToJSON :: ToJSON a => a -> MP.Object
unsafeViaToJSON a = case fromAeson $ toJSON a of
MP.Error e -> throw $ MessagePackAesonError e
MP.Success a -> a
data MessagePackAesonError = MessagePackAesonError String
deriving (Eq, Show, Typeable)
instance Exception MessagePackAesonError
| Wrapper for using values as MessagePack value .
newtype AsMessagePack a = AsMessagePack { getAsMessagePack :: a }
deriving (Eq, Ord, Show, Read, Functor, Data, Typeable, NFData)
instance (FromJSON a, ToJSON a) => MessagePack (AsMessagePack a) where
fromObject o = AsMessagePack <$> (aResult fail pure (fromJSON =<< toAeson o))
toObject = unsafeViaToJSON . getAsMessagePack
| Wrapper for using MessagePack values as value .
newtype AsAeson a = AsAeson { getAsAeson :: a }
deriving (Eq, Ord, Show, Read, Functor, Data, Typeable, NFData)
instance MessagePack a => ToJSON (AsAeson a) where
toJSON = aResult (const Null) id . toAeson . toObject . getAsAeson
instance MessagePack a => FromJSON (AsAeson a) where
parseJSON j = case fromAeson j of
MP.Error e -> fail e
MP.Success a -> mpResult fail (pure . AsAeson) $ fromObject a
| Encode to MessagePack via " Data . Aeson " 's ' ToJSON ' instances
packAeson :: ToJSON a => a -> MP.Result L.ByteString
packAeson a = pack <$> (fromAeson $ toJSON a)
| Decode from MessagePack via " Data . Aeson " 's ' FromJSON ' instances
unpackAeson :: FromJSON a => L.ByteString -> A.Result a
unpackAeson b = fromJSON =<< toAeson =<< either fail pure (unpack b)
-- | Encode MessagePack value to JSON document
encodeMessagePack :: MessagePack a => a -> L.ByteString
encodeMessagePack = encode . toJSON . AsAeson
-- | Decode MessagePack value from JSON document
decodeMessagePack :: MessagePack a => L.ByteString -> A.Result a
decodeMessagePack b = getAsAeson <$> (fromJSON =<< either A.Error A.Success (eitherDecode b))
aResult f s = \case
A.Success a -> s a
A.Error e -> f e
mpResult f s = \case
MP.Success a -> s a
MP.Error e -> f e
| null | https://raw.githubusercontent.com/msgpack/msgpack-haskell/f52a5d2db620a7be70810eca648fd152141f8b14/msgpack-aeson/src/Data/MessagePack/Aeson.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveFunctor #
* Conversion functions
* Wrapper instances
* Utility functions
| Convert 'MP.Object' to JSON 'Value'
| Convert JSON 'Value' to 'MP.Object'
instance.
Not as efficient as a direct encoder.
| Encode MessagePack value to JSON document
| Decode MessagePack value from JSON document | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
| Aeson bridge for MessagePack
module Data.MessagePack.Aeson (
toAeson, fromAeson,
unsafeViaToJSON, viaFromJSON,
AsMessagePack(..),
AsAeson(..),
MessagePackAesonError(..),
packAeson, unpackAeson,
decodeMessagePack, encodeMessagePack,
) where
import Control.Applicative
import Control.Arrow
import Control.DeepSeq
import Control.Exception
import Data.Aeson as A
import qualified Data.ByteString.Lazy as L (ByteString)
import Data.Data
import qualified Data.HashMap.Strict as HM
import Data.Int
import Data.Maybe
import Data.MessagePack as MP
import Data.MessagePack.Integer
import Data.Scientific
import qualified Data.Text.Encoding as T
import Data.Traversable (traverse)
import qualified Data.Vector as V
import Data.Word
toAeson :: MP.Object -> A.Result Value
toAeson = \case
ObjectNil -> pure Null
ObjectBool b -> pure (Bool b)
ObjectInt n -> pure $! Number $! fromIntegral n
ObjectFloat f -> pure $! Number $! realToFrac f
ObjectDouble d -> pure $! Number $! realToFrac d
ObjectStr t -> pure (String t)
ObjectBin b -> fail $ "ObjectBin is not supported by JSON"
ObjectArray v -> Array <$> V.mapM toAeson v
ObjectMap m ->
A.Object . HM.fromList . V.toList
<$> V.mapM (\(k, v) -> (,) <$> from k <*> toAeson v) m
where from = mpResult fail pure . MP.fromObject
ObjectExt _ _ -> fail "ObjectExt is not supported by JSON"
fromAeson :: Value -> MP.Result MP.Object
fromAeson = \case
Null -> pure ObjectNil
Bool b -> pure $ ObjectBool b
Number s ->
NOTE floatingOrInteger can OOM on untrusted input
case floatingOrInteger s of
Left n -> pure $ ObjectDouble n
Right (fromIntegerTry -> Right n) -> pure $ ObjectInt n
Right _ -> fail "number out of bounds"
String t -> pure $ ObjectStr t
Array v -> ObjectArray <$> traverse fromAeson v
A.Object o -> (ObjectMap . V.fromList) <$> traverse fromEntry (HM.toList o)
where
fromEntry (k, v) = (\a -> (ObjectStr k, a)) <$> fromAeson v
Helpers to piggyback off a JSON encoder / decoder when creating a MessagePack
viaFromJSON :: FromJSON a => MP.Object -> MP.Result a
viaFromJSON o = case toAeson o >>= fromJSON of
A.Success a -> MP.Success a
A.Error e -> MP.Error e
WARNING : not total for JSON numbers outside the 64 bit range
unsafeViaToJSON :: ToJSON a => a -> MP.Object
unsafeViaToJSON a = case fromAeson $ toJSON a of
MP.Error e -> throw $ MessagePackAesonError e
MP.Success a -> a
data MessagePackAesonError = MessagePackAesonError String
deriving (Eq, Show, Typeable)
instance Exception MessagePackAesonError
| Wrapper for using values as MessagePack value .
newtype AsMessagePack a = AsMessagePack { getAsMessagePack :: a }
deriving (Eq, Ord, Show, Read, Functor, Data, Typeable, NFData)
instance (FromJSON a, ToJSON a) => MessagePack (AsMessagePack a) where
fromObject o = AsMessagePack <$> (aResult fail pure (fromJSON =<< toAeson o))
toObject = unsafeViaToJSON . getAsMessagePack
| Wrapper for using MessagePack values as value .
newtype AsAeson a = AsAeson { getAsAeson :: a }
deriving (Eq, Ord, Show, Read, Functor, Data, Typeable, NFData)
instance MessagePack a => ToJSON (AsAeson a) where
toJSON = aResult (const Null) id . toAeson . toObject . getAsAeson
instance MessagePack a => FromJSON (AsAeson a) where
parseJSON j = case fromAeson j of
MP.Error e -> fail e
MP.Success a -> mpResult fail (pure . AsAeson) $ fromObject a
| Encode to MessagePack via " Data . Aeson " 's ' ToJSON ' instances
packAeson :: ToJSON a => a -> MP.Result L.ByteString
packAeson a = pack <$> (fromAeson $ toJSON a)
| Decode from MessagePack via " Data . Aeson " 's ' FromJSON ' instances
unpackAeson :: FromJSON a => L.ByteString -> A.Result a
unpackAeson b = fromJSON =<< toAeson =<< either fail pure (unpack b)
encodeMessagePack :: MessagePack a => a -> L.ByteString
encodeMessagePack = encode . toJSON . AsAeson
decodeMessagePack :: MessagePack a => L.ByteString -> A.Result a
decodeMessagePack b = getAsAeson <$> (fromJSON =<< either A.Error A.Success (eitherDecode b))
aResult f s = \case
A.Success a -> s a
A.Error e -> f e
mpResult f s = \case
MP.Success a -> s a
MP.Error e -> f e
|
8e6cad5ace3a862ea4acd628191a07f302c09750373e3bd187f2ef2148aa58e9 | 8thlight/hyperion | project.clj | (defproject hyperion/hyperion-gae "3.7.1"
:description "Google App Engine Datastore for Hyperion"
:dependencies [[org.clojure/clojure "1.5.1"]
[hyperion/hyperion-api "3.7.1"]
[com.google.appengine/appengine-api-1.0-sdk "1.6.6"]
[chee "1.1.0"]]
:profiles {:dev {:dependencies [[speclj "2.7.5"]
[com.google.appengine/appengine-testing "1.6.6"]
[com.google.appengine/appengine-api-stubs "1.6.6"]]}}
:test-paths ["spec/"]
:plugins [[speclj "2.7.5"]])
| null | https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/gae/project.clj | clojure | (defproject hyperion/hyperion-gae "3.7.1"
:description "Google App Engine Datastore for Hyperion"
:dependencies [[org.clojure/clojure "1.5.1"]
[hyperion/hyperion-api "3.7.1"]
[com.google.appengine/appengine-api-1.0-sdk "1.6.6"]
[chee "1.1.0"]]
:profiles {:dev {:dependencies [[speclj "2.7.5"]
[com.google.appengine/appengine-testing "1.6.6"]
[com.google.appengine/appengine-api-stubs "1.6.6"]]}}
:test-paths ["spec/"]
:plugins [[speclj "2.7.5"]])
| |
7de6175f95eebe4a9b4902a52f3edbd2f0bbbf81542e26f9056803c1f1b92e46 | javier-paris/erlang-tcpip | out_order.erl | %%%-------------------------------------------------------------------
%%% File : out_order.erl
Author : < >
%%% Description : Out of order Packet management
%%%
Created : 18 Nov 2004 by < >
%%%
%%%
erlang - tcpip , Copyright ( C ) 2004 Javier Paris
%%%
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(out_order).
-export([new/0, merge_data/2, get_out_order/2]).
new() ->
[].
merge_data([], Elem) ->
[Elem];
merge_data(List = [{Lseq, Lis_Fin, Ldata}|T], Elem={Seq, Is_Fin, Data}) ->
Pkt_Nxt = seq:add(Seq, size(Data)),
LPkt_Nxt = seq:add(Lseq, size(Ldata)),
if
Pkt_Nxt == Lseq ->
[{Seq, Lis_Fin, <<Data/binary, Ldata/binary>>} | T];
LPkt_Nxt == Seq ->
New_Data = <<Ldata/binary, Data/binary>>,
merge_data(T, {Lseq, Is_Fin, New_Data});
true ->
case seq:lt(Pkt_Nxt, Lseq) of
true ->
[Elem | List];
false ->
[{Lseq, Lis_Fin, Ldata} | merge_data(T, Elem)]
end
end.
get_out_order([], _) ->
{none, []};
get_out_order([{Lseq, Is_Fin, Data} | T], Seq) ->
case seq:le(Lseq, Seq) of
true ->
{{Lseq, Is_Fin, Data}, T};
false ->
{none, T}
end.
| null | https://raw.githubusercontent.com/javier-paris/erlang-tcpip/708b57fa37176980cddfd8605867426368d33ed1/src/out_order.erl | erlang | -------------------------------------------------------------------
File : out_order.erl
Description : Out of order Packet management
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------- | Author : < >
Created : 18 Nov 2004 by < >
erlang - tcpip , Copyright ( C ) 2004 Javier Paris
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(out_order).
-export([new/0, merge_data/2, get_out_order/2]).
new() ->
[].
merge_data([], Elem) ->
[Elem];
merge_data(List = [{Lseq, Lis_Fin, Ldata}|T], Elem={Seq, Is_Fin, Data}) ->
Pkt_Nxt = seq:add(Seq, size(Data)),
LPkt_Nxt = seq:add(Lseq, size(Ldata)),
if
Pkt_Nxt == Lseq ->
[{Seq, Lis_Fin, <<Data/binary, Ldata/binary>>} | T];
LPkt_Nxt == Seq ->
New_Data = <<Ldata/binary, Data/binary>>,
merge_data(T, {Lseq, Is_Fin, New_Data});
true ->
case seq:lt(Pkt_Nxt, Lseq) of
true ->
[Elem | List];
false ->
[{Lseq, Lis_Fin, Ldata} | merge_data(T, Elem)]
end
end.
get_out_order([], _) ->
{none, []};
get_out_order([{Lseq, Is_Fin, Data} | T], Seq) ->
case seq:le(Lseq, Seq) of
true ->
{{Lseq, Is_Fin, Data}, T};
false ->
{none, T}
end.
|
71aaae582625e243f30b98907b0e1568b12a62729a6bf7cf19feffef162518d7 | dktr0/estuary | Location.hs | module Estuary.Types.Location where
import Data.Text
type Location = (Text,Int)
| null | https://raw.githubusercontent.com/dktr0/estuary/0650557bac660eb94af2e196ea49f916c71e57ca/common/src/Estuary/Types/Location.hs | haskell | module Estuary.Types.Location where
import Data.Text
type Location = (Text,Int)
| |
05d825e0e49f5ff5b00b9d0e9ea55f327197707375589cb6e2809ee39ec2c8ed | McCLIM/McCLIM | port.lisp | ;;; ---------------------------------------------------------------------------
;;; License: LGPL-2.1+ (See file 'Copyright' for details).
;;; ---------------------------------------------------------------------------
;;;
( c ) Copyright 2005 by < >
( c ) Copyright 2014 by < >
;;;
;;; ---------------------------------------------------------------------------
;;;
(in-package #:clim-null)
(defclass null-port (basic-port)
((id)
(window :initform nil :accessor null-port-window))
(:default-initargs :pointer (make-instance 'standard-pointer)))
(defmethod find-port-type ((type (eql :null)))
(values 'null-port 'identity))
(defmethod initialize-instance :after ((port null-port) &rest initargs)
(declare (ignore initargs))
(setf (slot-value port 'id) (gensym "NULL-PORT-"))
;; FIXME: it seems bizarre for this to be necessary
(push (make-instance 'null-frame-manager :port port)
(slot-value port 'climi::frame-managers)))
(defmethod print-object ((object null-port) stream)
(print-unreadable-object (object stream :identity t :type t)
(format stream "~S ~S" :id (slot-value object 'id))))
(defmethod port-set-mirror-geometry ((port null-port) sheet region)
(bounding-rectangle* region))
(defmethod realize-mirror ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod destroy-mirror ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-enable-sheet ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-disable-sheet ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-shrink-sheet ((port null-port) (mirror mirrored-sheet-mixin))
nil)
(defmethod destroy-port :before ((port null-port))
nil)
(defmethod process-next-event ((port null-port) &key wait-function (timeout nil))
(cond ((maybe-funcall wait-function)
(values nil :wait-function))
((not (null timeout))
(sleep timeout)
(if (maybe-funcall wait-function)
(values nil :wait-function)
(values nil :timeout)))
((not (null wait-function))
(loop do (sleep 0.1)
until (funcall wait-function)
finally (return (values nil :wait-function))))
(t
(error "Game over. Listening for an event on Null backend."))))
(defmethod make-graft
((port null-port) &key (orientation :default) (units :device))
(make-instance 'null-graft
:port port :mirror (gensym)
:orientation orientation :units units))
(defmethod make-medium ((port null-port) sheet)
(make-instance 'null-medium :port port :sheet sheet))
(defmethod text-style-mapping
((port null-port) (text-style text-style) &optional character-set)
(declare (ignore port text-style character-set))
nil)
(defmethod (setf text-style-mapping) (font-name
(port null-port)
(text-style text-style)
&optional character-set)
(declare (ignore font-name text-style character-set))
nil)
(defmethod graft ((port null-port))
(first (climi::port-grafts port)))
(defmethod port-modifier-state ((port null-port))
nil)
(defmethod (setf port-keyboard-input-focus) (focus (port null-port))
focus)
(defmethod port-keyboard-input-focus ((port null-port))
nil)
(defmethod port-force-output ((port null-port))
nil)
(defmethod distribute-event :around ((port null-port) event)
(declare (ignore event))
nil)
(defmethod set-sheet-pointer-cursor ((port null-port) sheet cursor)
(declare (ignore sheet cursor))
nil)
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/edbc773336a15d368052d3d93d3e0cdb2acc4585/Backends/Null/port.lisp | lisp | ---------------------------------------------------------------------------
License: LGPL-2.1+ (See file 'Copyright' for details).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
FIXME: it seems bizarre for this to be necessary | ( c ) Copyright 2005 by < >
( c ) Copyright 2014 by < >
(in-package #:clim-null)
(defclass null-port (basic-port)
((id)
(window :initform nil :accessor null-port-window))
(:default-initargs :pointer (make-instance 'standard-pointer)))
(defmethod find-port-type ((type (eql :null)))
(values 'null-port 'identity))
(defmethod initialize-instance :after ((port null-port) &rest initargs)
(declare (ignore initargs))
(setf (slot-value port 'id) (gensym "NULL-PORT-"))
(push (make-instance 'null-frame-manager :port port)
(slot-value port 'climi::frame-managers)))
(defmethod print-object ((object null-port) stream)
(print-unreadable-object (object stream :identity t :type t)
(format stream "~S ~S" :id (slot-value object 'id))))
(defmethod port-set-mirror-geometry ((port null-port) sheet region)
(bounding-rectangle* region))
(defmethod realize-mirror ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod destroy-mirror ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-enable-sheet ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-disable-sheet ((port null-port) (sheet mirrored-sheet-mixin))
nil)
(defmethod port-shrink-sheet ((port null-port) (mirror mirrored-sheet-mixin))
nil)
(defmethod destroy-port :before ((port null-port))
nil)
(defmethod process-next-event ((port null-port) &key wait-function (timeout nil))
(cond ((maybe-funcall wait-function)
(values nil :wait-function))
((not (null timeout))
(sleep timeout)
(if (maybe-funcall wait-function)
(values nil :wait-function)
(values nil :timeout)))
((not (null wait-function))
(loop do (sleep 0.1)
until (funcall wait-function)
finally (return (values nil :wait-function))))
(t
(error "Game over. Listening for an event on Null backend."))))
(defmethod make-graft
((port null-port) &key (orientation :default) (units :device))
(make-instance 'null-graft
:port port :mirror (gensym)
:orientation orientation :units units))
(defmethod make-medium ((port null-port) sheet)
(make-instance 'null-medium :port port :sheet sheet))
(defmethod text-style-mapping
((port null-port) (text-style text-style) &optional character-set)
(declare (ignore port text-style character-set))
nil)
(defmethod (setf text-style-mapping) (font-name
(port null-port)
(text-style text-style)
&optional character-set)
(declare (ignore font-name text-style character-set))
nil)
(defmethod graft ((port null-port))
(first (climi::port-grafts port)))
(defmethod port-modifier-state ((port null-port))
nil)
(defmethod (setf port-keyboard-input-focus) (focus (port null-port))
focus)
(defmethod port-keyboard-input-focus ((port null-port))
nil)
(defmethod port-force-output ((port null-port))
nil)
(defmethod distribute-event :around ((port null-port) event)
(declare (ignore event))
nil)
(defmethod set-sheet-pointer-cursor ((port null-port) sheet cursor)
(declare (ignore sheet cursor))
nil)
|
b7acc808ba163ef2a7c4ac2b2117e5373c36b1b5b74235634e52c863e0bf212c | PaulSD/erlang_cas_client_cowboy | cas_client_cowboy.erl | %%%-------------------------------------------------------------------------------------------------
%%%
Copyright 2013 < >
%%%
%%% This file is part of erlang_cas_client_cowboy.
%%%
%%% erlang_cas_client_cowboy 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 .
%%%
%%% erlang_cas_client_cowboy 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
%%% erlang_cas_client_cowboy. If not, see {/}.
%%%
%%%-------------------------------------------------------------------------------------------------
@doc Application Manager for the CAS Client for Cowboy
-module(cas_client_cowboy).
-export([start/0]).
-behaviour(application).
-export([start/2, stop/1]).
start() ->
ok = application:start(cas_client_cowboy).
start(_Type, _Args) ->
case cas_client_cowboy_config:validate(undefined) of
{error, Message} ->
lager:error("~s", [Message]),
throw({error, Message});
_ -> ok
end,
{ok, self()}.
stop(_Args) ->
ok.
| null | https://raw.githubusercontent.com/PaulSD/erlang_cas_client_cowboy/05aa80174c0021ff9a8183d49c98df09f159f917/src/cas_client_cowboy.erl | erlang | -------------------------------------------------------------------------------------------------
This file is part of erlang_cas_client_cowboy.
erlang_cas_client_cowboy is free software: you can redistribute it and/or modify it under the
erlang_cas_client_cowboy 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.
erlang_cas_client_cowboy. If not, see {/}.
------------------------------------------------------------------------------------------------- | Copyright 2013 < >
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 .
You should have received a copy of the GNU Lesser General Public License along with
@doc Application Manager for the CAS Client for Cowboy
-module(cas_client_cowboy).
-export([start/0]).
-behaviour(application).
-export([start/2, stop/1]).
start() ->
ok = application:start(cas_client_cowboy).
start(_Type, _Args) ->
case cas_client_cowboy_config:validate(undefined) of
{error, Message} ->
lager:error("~s", [Message]),
throw({error, Message});
_ -> ok
end,
{ok, self()}.
stop(_Args) ->
ok.
|
97e1eae5b62bf1f06779361b8ea66b3ce531277a525fea8cc51dbb41606573cc | input-output-hk/plutus | MkPlc.hs | -- editorconfig-checker-disable-file
# LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE PolyKinds #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
module PlutusCore.MkPlc
( TermLike (..)
, UniOf
, mkTyBuiltinOf
, mkTyBuiltin
, mkConstantOf
, mkConstant
, VarDecl (..)
, TyVarDecl (..)
, TyDecl (..)
, mkVar
, mkTyVar
, tyDeclVar
, Def (..)
, embed
, TermDef
, TypeDef
, FunctionType (..)
, FunctionDef (..)
, functionTypeToType
, functionDefToType
, functionDefVarDecl
, mkFunctionDef
, mkImmediateLamAbs
, mkImmediateTyAbs
, mkIterTyForall
, mkIterTyLam
, mkIterApp
, mkIterTyFun
, mkIterLamAbs
, mkIterInst
, mkIterTyAbs
, mkIterTyApp
, mkIterKindArrow
) where
import PlutusPrelude
import Prelude hiding (error)
import PlutusCore.Core
import Universe
| A final encoding for Term , to allow PLC terms to be used transparently as PIR terms .
class TermLike term tyname name uni fun | term -> tyname name uni fun where
var :: ann -> name -> term ann
tyAbs :: ann -> tyname -> Kind ann -> term ann -> term ann
lamAbs :: ann -> name -> Type tyname uni ann -> term ann -> term ann
apply :: ann -> term ann -> term ann -> term ann
constant :: ann -> Some (ValueOf uni) -> term ann
builtin :: ann -> fun -> term ann
tyInst :: ann -> term ann -> Type tyname uni ann -> term ann
unwrap :: ann -> term ann -> term ann
iWrap :: ann -> Type tyname uni ann -> Type tyname uni ann -> term ann -> term ann
error :: ann -> Type tyname uni ann -> term ann
termLet :: ann -> TermDef term tyname name uni ann -> term ann -> term ann
typeLet :: ann -> TypeDef tyname uni ann -> term ann -> term ann
termLet = mkImmediateLamAbs
typeLet = mkImmediateTyAbs
-- TODO: make it @forall {k}@ once we have that.
-- (see -proposals/ghc-proposals/blob/master/proposals/0099-explicit-specificity.rst)
| Embed a type ( given its explicit type tag ) into a PLC type .
mkTyBuiltinOf :: forall k (a :: k) uni tyname ann. ann -> uni (Esc a) -> Type tyname uni ann
mkTyBuiltinOf ann = TyBuiltin ann . SomeTypeIn
-- TODO: make it @forall {k}@ once we have that.
-- (see -proposals/ghc-proposals/blob/master/proposals/0099-explicit-specificity.rst)
| Embed a type ( provided it 's in the universe ) into a PLC type .
mkTyBuiltin
:: forall k (a :: k) uni tyname ann. uni `Contains` a
=> ann -> Type tyname uni ann
mkTyBuiltin ann = mkTyBuiltinOf ann $ knownUni @_ @uni @a
| Embed a value ( given its explicit type tag ) into a PLC term .
mkConstantOf
:: forall a uni fun term tyname name ann. TermLike term tyname name uni fun
=> ann -> uni (Esc a) -> a -> term ann
mkConstantOf ann uni = constant ann . someValueOf uni
| Embed a value ( provided its type is in the universe ) into a PLC term .
mkConstant
:: forall a uni fun term tyname name ann. (TermLike term tyname name uni fun, uni `Includes` a)
=> ann -> a -> term ann
mkConstant ann = constant ann . someValue
instance TermLike (Term tyname name uni fun) tyname name uni fun where
var = Var
tyAbs = TyAbs
lamAbs = LamAbs
apply = Apply
constant = Constant
builtin = Builtin
tyInst = TyInst
unwrap = Unwrap
iWrap = IWrap
error = Error
embed :: TermLike term tyname name uni fun => Term tyname name uni fun ann -> term ann
embed = \case
Var a n -> var a n
TyAbs a tn k t -> tyAbs a tn k (embed t)
LamAbs a n ty t -> lamAbs a n ty (embed t)
Apply a t1 t2 -> apply a (embed t1) (embed t2)
Constant a c -> constant a c
Builtin a bi -> builtin a bi
TyInst a t ty -> tyInst a (embed t) ty
Error a ty -> error a ty
Unwrap a t -> unwrap a (embed t)
IWrap a ty1 ty2 t -> iWrap a ty1 ty2 (embed t)
| Make a ' Var ' referencing the given ' VarDecl ' .
mkVar :: TermLike term tyname name uni fun => ann -> VarDecl tyname name uni ann -> term ann
mkVar ann = var ann . _varDeclName
| Make a ' TyVar ' referencing the given ' TyVarDecl ' .
mkTyVar :: ann -> TyVarDecl tyname ann -> Type tyname uni ann
mkTyVar ann = TyVar ann . _tyVarDeclName
-- | A definition. Pretty much just a pair with more descriptive names.
data Def var val = Def
{ defVar :: var
, defVal :: val
} deriving stock (Show, Eq, Ord, Generic)
-- | A term definition as a variable.
type TermDef term tyname name uni ann = Def (VarDecl tyname name uni ann) (term ann)
-- | A type definition as a type variable.
type TypeDef tyname uni ann = Def (TyVarDecl tyname ann) (Type tyname uni ann)
| The type of a PLC function .
data FunctionType tyname uni ann = FunctionType
{ _functionTypeAnn :: ann -- ^ An annotation.
, _functionTypeDom :: Type tyname uni ann -- ^ The domain of a function.
, _functionTypeCod :: Type tyname uni ann -- ^ The codomain of the function.
}
Should we parameterize ' VarDecl ' by @ty@ rather than @tyname@ , so that we can define
' ' as ' TermDef FunctionType tyname name uni fun ' ?
-- Perhaps we even should define general 'Decl' and 'Def' that cover all of the cases?
-- | A PLC function.
data FunctionDef term tyname name uni fun ann = FunctionDef
{ _functionDefAnn :: ann -- ^ An annotation.
, _functionDefName :: name -- ^ The name of a function.
, _functionDefType :: FunctionType tyname uni ann -- ^ The type of the function.
, _functionDefTerm :: term ann -- ^ The definition of the function.
}
| Convert a ' FunctionType ' to the corresponding ' Type ' .
functionTypeToType :: FunctionType tyname uni ann -> Type tyname uni ann
functionTypeToType (FunctionType ann dom cod) = TyFun ann dom cod
| Get the type of a ' ' .
functionDefToType :: FunctionDef term tyname name uni fun ann -> Type tyname uni ann
functionDefToType (FunctionDef _ _ funTy _) = functionTypeToType funTy
| Convert a ' ' to a ' VarDecl ' . I.e. ignore the actual term .
functionDefVarDecl :: FunctionDef term tyname name uni fun ann -> VarDecl tyname name uni ann
functionDefVarDecl (FunctionDef ann name funTy _) = VarDecl ann name $ functionTypeToType funTy
| Make a ' ' . Return ' Nothing ' if the provided type is not functional .
mkFunctionDef
:: ann
-> name
-> Type tyname uni ann
-> term ann
-> Maybe (FunctionDef term tyname name uni fun ann)
mkFunctionDef annName name (TyFun annTy dom cod) term =
Just $ FunctionDef annName name (FunctionType annTy dom cod) term
mkFunctionDef _ _ _ _ = Nothing
-- | Make a "let-binding" for a term as an immediately applied lambda abstraction.
mkImmediateLamAbs
:: TermLike term tyname name uni fun
=> ann
-> TermDef term tyname name uni ann
-> term ann -- ^ The body of the let, possibly referencing the name.
-> term ann
mkImmediateLamAbs ann1 (Def (VarDecl ann2 name ty) bind) body =
apply ann1 (lamAbs ann2 name ty body) bind
-- | Make a "let-binding" for a type as an immediately instantiated type abstraction. Note: the body must be a value.
mkImmediateTyAbs
:: TermLike term tyname name uni fun
=> ann
-> TypeDef tyname uni ann
-> term ann -- ^ The body of the let, possibly referencing the name.
-> term ann
mkImmediateTyAbs ann1 (Def (TyVarDecl ann2 name k) bind) body =
tyInst ann1 (tyAbs ann2 name k body) bind
-- | Make an iterated application.
mkIterApp
:: TermLike term tyname name uni fun
=> ann
-> term ann -- ^ @f@
-> [term ann] -- ^@[ x0 ... xn ]@
^ @[f ... xn ] @
mkIterApp ann = foldl' (apply ann)
-- | Make an iterated instantiation.
mkIterInst
:: TermLike term tyname name uni fun
=> ann
-> term ann -- ^ @a@
^ @ [ ... xn ] @
^ @ { a ... xn } @
mkIterInst ann = foldl' (tyInst ann)
-- | Lambda abstract a list of names.
mkIterLamAbs
:: TermLike term tyname name uni fun
=> [VarDecl tyname name uni ann]
-> term ann
-> term ann
mkIterLamAbs args body =
foldr (\(VarDecl ann name ty) acc -> lamAbs ann name ty acc) body args
-- | Type abstract a list of names.
mkIterTyAbs
:: TermLike term tyname name uni fun
=> [TyVarDecl tyname ann]
-> term ann
-> term ann
mkIterTyAbs args body =
foldr (\(TyVarDecl ann name kind) acc -> tyAbs ann name kind acc) body args
-- | Make an iterated type application.
mkIterTyApp
:: ann
-> Type tyname uni ann -- ^ @f@
^ @ [ ... xn ] @
-> Type tyname uni ann -- ^ @[ f x0 ... xn ]@
mkIterTyApp ann = foldl' (TyApp ann)
-- | Make an iterated function type.
mkIterTyFun
:: ann
-> [Type tyname uni ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyFun ann tys target = foldr (\ty acc -> TyFun ann ty acc) target tys
-- | Universally quantify a list of names.
mkIterTyForall
:: [TyVarDecl tyname ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyForall args body =
foldr (\(TyVarDecl ann name kind) acc -> TyForall ann name kind acc) body args
-- | Lambda abstract a list of names.
mkIterTyLam
:: [TyVarDecl tyname ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyLam args body =
foldr (\(TyVarDecl ann name kind) acc -> TyLam ann name kind acc) body args
-- | Make an iterated function kind.
mkIterKindArrow
:: ann
-> [Kind ann]
-> Kind ann
-> Kind ann
mkIterKindArrow ann kinds target = foldr (KindArrow ann) target kinds
| null | https://raw.githubusercontent.com/input-output-hk/plutus/107d7e7ec5a1c033228c402ee221794117566d15/plutus-core/plutus-core/src/PlutusCore/MkPlc.hs | haskell | editorconfig-checker-disable-file
# LANGUAGE ConstraintKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
TODO: make it @forall {k}@ once we have that.
(see -proposals/ghc-proposals/blob/master/proposals/0099-explicit-specificity.rst)
TODO: make it @forall {k}@ once we have that.
(see -proposals/ghc-proposals/blob/master/proposals/0099-explicit-specificity.rst)
| A definition. Pretty much just a pair with more descriptive names.
| A term definition as a variable.
| A type definition as a type variable.
^ An annotation.
^ The domain of a function.
^ The codomain of the function.
Perhaps we even should define general 'Decl' and 'Def' that cover all of the cases?
| A PLC function.
^ An annotation.
^ The name of a function.
^ The type of the function.
^ The definition of the function.
| Make a "let-binding" for a term as an immediately applied lambda abstraction.
^ The body of the let, possibly referencing the name.
| Make a "let-binding" for a type as an immediately instantiated type abstraction. Note: the body must be a value.
^ The body of the let, possibly referencing the name.
| Make an iterated application.
^ @f@
^@[ x0 ... xn ]@
| Make an iterated instantiation.
^ @a@
| Lambda abstract a list of names.
| Type abstract a list of names.
| Make an iterated type application.
^ @f@
^ @[ f x0 ... xn ]@
| Make an iterated function type.
| Universally quantify a list of names.
| Lambda abstract a list of names.
| Make an iterated function kind. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE PolyKinds #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
module PlutusCore.MkPlc
( TermLike (..)
, UniOf
, mkTyBuiltinOf
, mkTyBuiltin
, mkConstantOf
, mkConstant
, VarDecl (..)
, TyVarDecl (..)
, TyDecl (..)
, mkVar
, mkTyVar
, tyDeclVar
, Def (..)
, embed
, TermDef
, TypeDef
, FunctionType (..)
, FunctionDef (..)
, functionTypeToType
, functionDefToType
, functionDefVarDecl
, mkFunctionDef
, mkImmediateLamAbs
, mkImmediateTyAbs
, mkIterTyForall
, mkIterTyLam
, mkIterApp
, mkIterTyFun
, mkIterLamAbs
, mkIterInst
, mkIterTyAbs
, mkIterTyApp
, mkIterKindArrow
) where
import PlutusPrelude
import Prelude hiding (error)
import PlutusCore.Core
import Universe
| A final encoding for Term , to allow PLC terms to be used transparently as PIR terms .
class TermLike term tyname name uni fun | term -> tyname name uni fun where
var :: ann -> name -> term ann
tyAbs :: ann -> tyname -> Kind ann -> term ann -> term ann
lamAbs :: ann -> name -> Type tyname uni ann -> term ann -> term ann
apply :: ann -> term ann -> term ann -> term ann
constant :: ann -> Some (ValueOf uni) -> term ann
builtin :: ann -> fun -> term ann
tyInst :: ann -> term ann -> Type tyname uni ann -> term ann
unwrap :: ann -> term ann -> term ann
iWrap :: ann -> Type tyname uni ann -> Type tyname uni ann -> term ann -> term ann
error :: ann -> Type tyname uni ann -> term ann
termLet :: ann -> TermDef term tyname name uni ann -> term ann -> term ann
typeLet :: ann -> TypeDef tyname uni ann -> term ann -> term ann
termLet = mkImmediateLamAbs
typeLet = mkImmediateTyAbs
| Embed a type ( given its explicit type tag ) into a PLC type .
mkTyBuiltinOf :: forall k (a :: k) uni tyname ann. ann -> uni (Esc a) -> Type tyname uni ann
mkTyBuiltinOf ann = TyBuiltin ann . SomeTypeIn
| Embed a type ( provided it 's in the universe ) into a PLC type .
mkTyBuiltin
:: forall k (a :: k) uni tyname ann. uni `Contains` a
=> ann -> Type tyname uni ann
mkTyBuiltin ann = mkTyBuiltinOf ann $ knownUni @_ @uni @a
| Embed a value ( given its explicit type tag ) into a PLC term .
mkConstantOf
:: forall a uni fun term tyname name ann. TermLike term tyname name uni fun
=> ann -> uni (Esc a) -> a -> term ann
mkConstantOf ann uni = constant ann . someValueOf uni
| Embed a value ( provided its type is in the universe ) into a PLC term .
mkConstant
:: forall a uni fun term tyname name ann. (TermLike term tyname name uni fun, uni `Includes` a)
=> ann -> a -> term ann
mkConstant ann = constant ann . someValue
instance TermLike (Term tyname name uni fun) tyname name uni fun where
var = Var
tyAbs = TyAbs
lamAbs = LamAbs
apply = Apply
constant = Constant
builtin = Builtin
tyInst = TyInst
unwrap = Unwrap
iWrap = IWrap
error = Error
embed :: TermLike term tyname name uni fun => Term tyname name uni fun ann -> term ann
embed = \case
Var a n -> var a n
TyAbs a tn k t -> tyAbs a tn k (embed t)
LamAbs a n ty t -> lamAbs a n ty (embed t)
Apply a t1 t2 -> apply a (embed t1) (embed t2)
Constant a c -> constant a c
Builtin a bi -> builtin a bi
TyInst a t ty -> tyInst a (embed t) ty
Error a ty -> error a ty
Unwrap a t -> unwrap a (embed t)
IWrap a ty1 ty2 t -> iWrap a ty1 ty2 (embed t)
| Make a ' Var ' referencing the given ' VarDecl ' .
mkVar :: TermLike term tyname name uni fun => ann -> VarDecl tyname name uni ann -> term ann
mkVar ann = var ann . _varDeclName
| Make a ' TyVar ' referencing the given ' TyVarDecl ' .
mkTyVar :: ann -> TyVarDecl tyname ann -> Type tyname uni ann
mkTyVar ann = TyVar ann . _tyVarDeclName
data Def var val = Def
{ defVar :: var
, defVal :: val
} deriving stock (Show, Eq, Ord, Generic)
type TermDef term tyname name uni ann = Def (VarDecl tyname name uni ann) (term ann)
type TypeDef tyname uni ann = Def (TyVarDecl tyname ann) (Type tyname uni ann)
| The type of a PLC function .
data FunctionType tyname uni ann = FunctionType
}
Should we parameterize ' VarDecl ' by @ty@ rather than @tyname@ , so that we can define
' ' as ' TermDef FunctionType tyname name uni fun ' ?
data FunctionDef term tyname name uni fun ann = FunctionDef
}
| Convert a ' FunctionType ' to the corresponding ' Type ' .
functionTypeToType :: FunctionType tyname uni ann -> Type tyname uni ann
functionTypeToType (FunctionType ann dom cod) = TyFun ann dom cod
| Get the type of a ' ' .
functionDefToType :: FunctionDef term tyname name uni fun ann -> Type tyname uni ann
functionDefToType (FunctionDef _ _ funTy _) = functionTypeToType funTy
| Convert a ' ' to a ' VarDecl ' . I.e. ignore the actual term .
functionDefVarDecl :: FunctionDef term tyname name uni fun ann -> VarDecl tyname name uni ann
functionDefVarDecl (FunctionDef ann name funTy _) = VarDecl ann name $ functionTypeToType funTy
| Make a ' ' . Return ' Nothing ' if the provided type is not functional .
mkFunctionDef
:: ann
-> name
-> Type tyname uni ann
-> term ann
-> Maybe (FunctionDef term tyname name uni fun ann)
mkFunctionDef annName name (TyFun annTy dom cod) term =
Just $ FunctionDef annName name (FunctionType annTy dom cod) term
mkFunctionDef _ _ _ _ = Nothing
mkImmediateLamAbs
:: TermLike term tyname name uni fun
=> ann
-> TermDef term tyname name uni ann
-> term ann
mkImmediateLamAbs ann1 (Def (VarDecl ann2 name ty) bind) body =
apply ann1 (lamAbs ann2 name ty body) bind
mkImmediateTyAbs
:: TermLike term tyname name uni fun
=> ann
-> TypeDef tyname uni ann
-> term ann
mkImmediateTyAbs ann1 (Def (TyVarDecl ann2 name k) bind) body =
tyInst ann1 (tyAbs ann2 name k body) bind
mkIterApp
:: TermLike term tyname name uni fun
=> ann
^ @[f ... xn ] @
mkIterApp ann = foldl' (apply ann)
mkIterInst
:: TermLike term tyname name uni fun
=> ann
^ @ [ ... xn ] @
^ @ { a ... xn } @
mkIterInst ann = foldl' (tyInst ann)
mkIterLamAbs
:: TermLike term tyname name uni fun
=> [VarDecl tyname name uni ann]
-> term ann
-> term ann
mkIterLamAbs args body =
foldr (\(VarDecl ann name ty) acc -> lamAbs ann name ty acc) body args
mkIterTyAbs
:: TermLike term tyname name uni fun
=> [TyVarDecl tyname ann]
-> term ann
-> term ann
mkIterTyAbs args body =
foldr (\(TyVarDecl ann name kind) acc -> tyAbs ann name kind acc) body args
mkIterTyApp
:: ann
^ @ [ ... xn ] @
mkIterTyApp ann = foldl' (TyApp ann)
mkIterTyFun
:: ann
-> [Type tyname uni ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyFun ann tys target = foldr (\ty acc -> TyFun ann ty acc) target tys
mkIterTyForall
:: [TyVarDecl tyname ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyForall args body =
foldr (\(TyVarDecl ann name kind) acc -> TyForall ann name kind acc) body args
mkIterTyLam
:: [TyVarDecl tyname ann]
-> Type tyname uni ann
-> Type tyname uni ann
mkIterTyLam args body =
foldr (\(TyVarDecl ann name kind) acc -> TyLam ann name kind acc) body args
mkIterKindArrow
:: ann
-> [Kind ann]
-> Kind ann
-> Kind ann
mkIterKindArrow ann kinds target = foldr (KindArrow ann) target kinds
|
db1f61ebdb4bb789203d74e138ac477c634c564d15c6606dd1e86ac24532dae1 | rollacaster/sketches | particles_with_images.cljs | (ns sketches.nature-of-code.particle-systems.particles-with-images
(:require [quil.core :as q :include-macros true]
[quil.middleware :as md]
[sketches.mover :as m]))
(defn create-particle [location images]
(assoc (m/create-mover 10 location)
:velocity [(q/random-gaussian) (- (q/random-gaussian) 1.0)]
:lifespan 255.0
:mass 10
:image (rand-nth images)))
(defn setup []
(q/frame-rate 30)
{:images [(q/load-image "images/sojka.jpg")
(q/load-image "images/fcb.jpg")
(q/load-image "images/emacs.png")]
:particles ()
:origin [(/ (q/width) 2) (/ (q/height) 2)]})
(defn draw-particle [{:keys [lifespan image] [x y] :location}]
(q/image-mode :center)
(q/tint 255 lifespan)
(q/image image x y 80 80))
(defn is-dead [{:keys [lifespan]}] (< lifespan 0.0))
(defn dec-lifespan [particle] (update particle :lifespan (comp dec dec dec dec dec)))
(defn update-state [{:keys [images] :as ps}]
(-> ps
(update :particles #(conj % (create-particle (:origin ps) images)))
(update :particles #(map (comp m/compute-position dec-lifespan) %))
(update :particles #(remove is-dead %))))
(defn draw [{:keys [particles]}]
(q/background 255)
(doseq [particle particles]
(draw-particle particle)))
(defn run [host]
(q/defsketch particles-with-images
:host host
:setup setup
:draw draw
:update update-state
:middleware [md/fun-mode]
:size [300 300]))
| null | https://raw.githubusercontent.com/rollacaster/sketches/ba79fccf2a37139de9193ed2ea7a6cc04b63fad0/src/sketches/nature_of_code/particle_systems/particles_with_images.cljs | clojure | (ns sketches.nature-of-code.particle-systems.particles-with-images
(:require [quil.core :as q :include-macros true]
[quil.middleware :as md]
[sketches.mover :as m]))
(defn create-particle [location images]
(assoc (m/create-mover 10 location)
:velocity [(q/random-gaussian) (- (q/random-gaussian) 1.0)]
:lifespan 255.0
:mass 10
:image (rand-nth images)))
(defn setup []
(q/frame-rate 30)
{:images [(q/load-image "images/sojka.jpg")
(q/load-image "images/fcb.jpg")
(q/load-image "images/emacs.png")]
:particles ()
:origin [(/ (q/width) 2) (/ (q/height) 2)]})
(defn draw-particle [{:keys [lifespan image] [x y] :location}]
(q/image-mode :center)
(q/tint 255 lifespan)
(q/image image x y 80 80))
(defn is-dead [{:keys [lifespan]}] (< lifespan 0.0))
(defn dec-lifespan [particle] (update particle :lifespan (comp dec dec dec dec dec)))
(defn update-state [{:keys [images] :as ps}]
(-> ps
(update :particles #(conj % (create-particle (:origin ps) images)))
(update :particles #(map (comp m/compute-position dec-lifespan) %))
(update :particles #(remove is-dead %))))
(defn draw [{:keys [particles]}]
(q/background 255)
(doseq [particle particles]
(draw-particle particle)))
(defn run [host]
(q/defsketch particles-with-images
:host host
:setup setup
:draw draw
:update update-state
:middleware [md/fun-mode]
:size [300 300]))
| |
d70febce948670f4789dea497f70b869c08da738afc85281b7dfb0c973899f0d | corecursive/sicp-study-group | operation.scm | (load "operation.scm")
(load "polynomial-package/representation.scm")
(define (+poly p1 p2)
(if (same-var? p1 p2)
(make-poly
(var p1)
(+terms (term-list p1)
(term-list p2)))
(error "Polys not in same var")))
(define (*poly p1 p2)
(if (same-var? p1 p2)
(make-poly
(var p1)
(*terms (term-list p1)
(term-list p2)))
(error "Polys not in same var")))
(define (+terms L1 L2)
(cond ((empty-term-list? L1) L2)
((empty-term-list? L2) L1)
(else
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(cond ((> (order t1) (order t2))
(adjoin-term
t1
(+terms (rest-terms L1) L2)))
((< (order t1) (order t2))
(adjoin-term
t2
(+terms L1 (rest-terms L2))))
(else
(adjoin-term
(make-term (order t1)
(add (coeff t1) ; note the use of the generic add here
(coeff t2)))
(+terms (rest-terms L1)
(rest-terms L2)))))))))
(define (*terms L1 L2)
(if (empty-term-list? L1)
(empty-term-list)
(+terms (*term-by-terms (first-term L1)
L2)
(*terms (rest-terms L1)
L2))))
(define (*term-by-terms t1 L)
(if (empty-term-list? L)
(empty-term-list)
(let ((t2 (first-term L)))
(adjoin-term
(make-term (+ (order t1)
(order t2))
note the use of the generic here
(coeff t2)))
(*term-by-terms t1
(rest-terms L))))))
(define (adjoin-term term term-list)
(cons term term-list))
(define (first-term term-list)
(car term-list))
(define (rest-terms term-list)
(cdr term-list))
(define (empty-term-list? term-list)
(null? term-list))
(define (empty-term-list)
'()) | null | https://raw.githubusercontent.com/corecursive/sicp-study-group/82b92a9759ed6c72d15cf955c806ce2a94336f83/wulab/lecture-4b/generic-operation/polynomial-package/operation.scm | scheme | note the use of the generic add here | (load "operation.scm")
(load "polynomial-package/representation.scm")
(define (+poly p1 p2)
(if (same-var? p1 p2)
(make-poly
(var p1)
(+terms (term-list p1)
(term-list p2)))
(error "Polys not in same var")))
(define (*poly p1 p2)
(if (same-var? p1 p2)
(make-poly
(var p1)
(*terms (term-list p1)
(term-list p2)))
(error "Polys not in same var")))
(define (+terms L1 L2)
(cond ((empty-term-list? L1) L2)
((empty-term-list? L2) L1)
(else
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(cond ((> (order t1) (order t2))
(adjoin-term
t1
(+terms (rest-terms L1) L2)))
((< (order t1) (order t2))
(adjoin-term
t2
(+terms L1 (rest-terms L2))))
(else
(adjoin-term
(make-term (order t1)
(coeff t2)))
(+terms (rest-terms L1)
(rest-terms L2)))))))))
(define (*terms L1 L2)
(if (empty-term-list? L1)
(empty-term-list)
(+terms (*term-by-terms (first-term L1)
L2)
(*terms (rest-terms L1)
L2))))
(define (*term-by-terms t1 L)
(if (empty-term-list? L)
(empty-term-list)
(let ((t2 (first-term L)))
(adjoin-term
(make-term (+ (order t1)
(order t2))
note the use of the generic here
(coeff t2)))
(*term-by-terms t1
(rest-terms L))))))
(define (adjoin-term term term-list)
(cons term term-list))
(define (first-term term-list)
(car term-list))
(define (rest-terms term-list)
(cdr term-list))
(define (empty-term-list? term-list)
(null? term-list))
(define (empty-term-list)
'()) |
699d3ebf5f66f6eb07b6893141070fdeaa55be8c495f9085fcda462e6c45e509 | antono/guix-debian | moe.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages moe)
#:use-module (guix licenses)
#:use-module (gnu packages ncurses)
#:use-module ((gnu packages compression) #:select (lzip))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public moe
(package
(name "moe")
(version "1.6")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.lz"))
(sha256
(base32
"1cfwi67sdl2qchqbdib4p6wxjpwz2kmn6vxn9hmh1zs0gg4xkbwc"))))
(build-system gnu-build-system)
(native-inputs `(("lzip" ,lzip)))
(inputs `(("ncurses" ,ncurses)))
(home-page "")
(synopsis "Modeless, multiple-buffer, user-friendly 8-bit text editor")
(description
"GNU Moe is a powerful-but-simple-to-use text editor. It works in a
modeless manner, and features an intuitive set of key-bindings that
assign a degree of severity to each key; for example, key
combinations with the Alt key are for harmless commands like cursor
movements while combinations with the Control key are for commands
that will modify the text. Moe features multiple windows, unlimited
undo/redo, unlimited line length, global search and replace, and
more.")
(license gpl3+)))
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/moe.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
for example, key | Copyright © 2014 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages moe)
#:use-module (guix licenses)
#:use-module (gnu packages ncurses)
#:use-module ((gnu packages compression) #:select (lzip))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public moe
(package
(name "moe")
(version "1.6")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.lz"))
(sha256
(base32
"1cfwi67sdl2qchqbdib4p6wxjpwz2kmn6vxn9hmh1zs0gg4xkbwc"))))
(build-system gnu-build-system)
(native-inputs `(("lzip" ,lzip)))
(inputs `(("ncurses" ,ncurses)))
(home-page "")
(synopsis "Modeless, multiple-buffer, user-friendly 8-bit text editor")
(description
"GNU Moe is a powerful-but-simple-to-use text editor. It works in a
modeless manner, and features an intuitive set of key-bindings that
combinations with the Alt key are for harmless commands like cursor
movements while combinations with the Control key are for commands
that will modify the text. Moe features multiple windows, unlimited
undo/redo, unlimited line length, global search and replace, and
more.")
(license gpl3+)))
|
b09e75ac994d4dae329e777db7f4166130e95d8a2189fcccbc3ad83fd8a49fd6 | Frama-C/Frama-C-snapshot | format_parser.mli | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 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 ) .
(* *)
(**************************************************************************)
open Format_types
exception Invalid_format
val check_f_specification : f_conversion_specification -> f_conversion_specification
val check_s_specification : s_conversion_specification -> s_conversion_specification
val check_f_format : f_format -> f_format
val check_s_format : s_format -> s_format
val check_format : format -> format
val parse_f_format : Format_string.t -> f_format
val parse_s_format : Format_string.t -> s_format
val parse_format : format_kind -> Format_string.t -> format
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/variadic/format_parser.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.
************************************************************************ | This file is part of Frama - C.
Copyright ( C ) 2007 - 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 ) .
open Format_types
exception Invalid_format
val check_f_specification : f_conversion_specification -> f_conversion_specification
val check_s_specification : s_conversion_specification -> s_conversion_specification
val check_f_format : f_format -> f_format
val check_s_format : s_format -> s_format
val check_format : format -> format
val parse_f_format : Format_string.t -> f_format
val parse_s_format : Format_string.t -> s_format
val parse_format : format_kind -> Format_string.t -> format
|
b8c0f9a9a60655b5927dada535deb20277a0936ac110a9f46b43a081e49664f8 | tfausak/monadoc-5 | TestExceptionSpec.hs | module Monadoc.Type.TestExceptionSpec where
import Monadoc.Prelude
import Test.Hspec
spec :: Spec
spec = describe "Monadoc.Type.TestException" <| do
pure ()
| null | https://raw.githubusercontent.com/tfausak/monadoc-5/5361dd1870072cf2771857adbe92658118ddaa27/src/test/Monadoc/Type/TestExceptionSpec.hs | haskell | module Monadoc.Type.TestExceptionSpec where
import Monadoc.Prelude
import Test.Hspec
spec :: Spec
spec = describe "Monadoc.Type.TestException" <| do
pure ()
| |
24d86ff1e37cdcc6e77d2bc605fb77a5e857d6d631c529926ef6ede2bb35de2f | kmi/irs | new.lisp | Mode : Lisp ; Package :
File created in WebOnto
(in-package "OCML")
(in-ontology buddyspace)
| null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/buddyspace/new.lisp | lisp | Package : |
File created in WebOnto
(in-package "OCML")
(in-ontology buddyspace)
|
53ac86133af597add48c9ee2a1b42e0a9cdb2d0844e4d3927450d9004f02bddc | unix1/nuk | nuk_user_store_sup.erl | %%%-------------------------------------------------------------------
%% @doc `nuk_user_store_sup' module
%%
%% This supervisor is started by {@link nuk_sup} top level supervisor. It
%% supervises {@link nuk_user_store_server}.
%% @end
%%%-------------------------------------------------------------------
-module(nuk_user_store_sup).
-behaviour(supervisor).
%% Supervision
-export([start_link/0, init/1]).
-define(SERVER, ?MODULE).
%% Helper macro for declaring children of supervisor
-define(CHILD(Id, Module, Args, Type), {Id, {Module, start_link, Args},
permanent, 5000, Type, [Module]}).
%%====================================================================
%% Supervision
%%====================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 0, 1}, children()} }.
%%====================================================================
Internal functions
%%====================================================================
%% @doc Get children specs
@private
%%
%% A convenience function to return all children specs.
%% @end
children() ->
UserStore = ?CHILD(nuk_user_store_server, nuk_user_store_server, [], worker),
[UserStore].
| null | https://raw.githubusercontent.com/unix1/nuk/ad771c8b164c305408d8076627228024c4955ec1/src/nuk_user_store_sup.erl | erlang | -------------------------------------------------------------------
@doc `nuk_user_store_sup' module
This supervisor is started by {@link nuk_sup} top level supervisor. It
supervises {@link nuk_user_store_server}.
@end
-------------------------------------------------------------------
Supervision
Helper macro for declaring children of supervisor
====================================================================
Supervision
====================================================================
====================================================================
====================================================================
@doc Get children specs
A convenience function to return all children specs.
@end |
-module(nuk_user_store_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).
-define(SERVER, ?MODULE).
-define(CHILD(Id, Module, Args, Type), {Id, {Module, start_link, Args},
permanent, 5000, Type, [Module]}).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 0, 1}, children()} }.
Internal functions
@private
children() ->
UserStore = ?CHILD(nuk_user_store_server, nuk_user_store_server, [], worker),
[UserStore].
|
7b4b26eaa449bc54c07513dd90bc1512b3902e691ab84e1d7b7a9791108fd529 | OCamlPro/typerex-lint | plugin_parsetree.pattern_guard.1.ml | let f = function
| x when x > 10 -> 2
| _ -> 1
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/tools/ocp-lint-doc/examples/plugin_parsetree.pattern_guard.1.ml | ocaml | let f = function
| x when x > 10 -> 2
| _ -> 1
| |
198e9f02a37413e5c2dc661a3eb9d3f396bd0b0edb97024b30eef2d55cd2181b | naveensundarg/prover | deque2.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-deque -*-
;;; File: deque2.lisp
The contents of this file are subject to the Mozilla Public License
;;; Version 1.1 (the "License"); you may not use this file except in
;;; compliance with the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS "
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
;;; License for the specific language governing rights and limitations
;;; under the License.
;;;
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 .
All Rights Reserved .
;;;
Contributor(s ): < > .
(in-package :snark-deque)
(defstruct (deque
(:predicate deque?))
(front nil :type list)
(last-of-front nil)
(rear nil :type list)
(last-of-rear nil))
(defun deque-empty? (deque)
(and (null (deque-front deque)) (null (deque-rear deque))))
(defun deque-first (deque)
returns first item in deque , nil if deque is empty
(let ((front (deque-front deque)))
(if front (first front) (deque-last-of-rear deque))))
(defun deque-last (deque)
;; returns last item in deque, nil if deque is empty
(let ((rear (deque-rear deque)))
(if rear (first rear) (deque-last-of-front deque))))
(defun deque-rest (deque)
returns new deque with first item removed , deque if it is empty
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(front
(let ((front* (rest front)))
(make-deque
:front front*
:last-of-front (if front* (deque-last-of-front deque) nil)
:rear rear
:last-of-rear (deque-last-of-rear deque))))
(rear
(let ((front* (rest (reverse rear))))
(make-deque
:front front*
:last-of-front (if front* (first rear) nil)
:rear nil
:last-of-rear nil)))
(t
deque))))
(defun deque-butlast (deque)
;; returns new deque with last item removed, deque if it is empty
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(rear
(let ((rear* (rest rear)))
(make-deque
:rear rear*
:last-of-rear (if rear* (deque-last-of-rear deque) nil)
:front front
:last-of-front (deque-last-of-front deque))))
(front
(let ((rear* (rest (reverse front))))
(make-deque
:rear rear*
:last-of-rear (if rear* (first front) nil)
:front nil
:last-of-front nil)))
(t
deque))))
(defun deque-pop-first (deque)
like deque - rest , but return first item and destructively remove it from deque
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(front
(let ((front* (rest front)))
(setf (deque-front deque) front*)
(when (null front*)
(setf (deque-last-of-front deque) nil))
(first front)))
(rear
(let ((item (deque-last-of-rear deque))
(front* (rest (reverse rear))))
(setf (deque-front deque) front*)
(setf (deque-last-of-front deque) (if front* (first rear) nil))
(setf (deque-rear deque) nil)
(setf (deque-last-of-rear deque) nil)
item))
(t
nil))))
(defun deque-pop-last (deque)
;; like deque-butlast, but return last item and destructively remove it from deque
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(rear
(let ((rear* (rest rear)))
(setf (deque-rear deque) rear*)
(when (null rear*)
(setf (deque-last-of-rear deque) nil))
(first rear)))
(front
(let ((item (deque-last-of-front deque))
(rear* (rest (reverse front))))
(setf (deque-rear deque) rear*)
(setf (deque-last-of-rear deque) (if rear* (first front) nil))
(setf (deque-front deque) nil)
(setf (deque-last-of-front deque) nil)
item))
(t
nil))))
(defun deque-add-first (deque item)
returns new deque with new first item added
(let ((front (deque-front deque)))
(make-deque
:front (cons item front)
:last-of-front (if front (deque-last-of-front deque) item)
:rear (deque-rear deque)
:last-of-rear (deque-last-of-rear deque))))
(defun deque-add-last (deque item)
;; returns new deque with new last item added
(let ((rear (deque-rear deque)))
(make-deque
:rear (cons item rear)
:last-of-rear (if rear (deque-last-of-rear deque) item)
:front (deque-front deque)
:last-of-front (deque-last-of-front deque))))
(defun deque-push-first (deque item)
like deque - add - first , but returns same deque with new first item added destructively
(let ((front (deque-front deque)))
(setf (deque-front deque) (cons item front))
(when (null front)
(setf (deque-last-of-front deque) item))
deque))
(defun deque-push-last (deque item)
;; like deque-add-last, but returns same deque with new last item added destructively
(let ((rear (deque-rear deque)))
(setf (deque-rear deque) (cons item rear))
(when (null rear)
(setf (deque-last-of-rear deque) item))
deque))
(defun deque-length (deque)
(+ (length (deque-front deque)) (length (deque-rear deque))))
(defun deque-delete (deque item)
;; ad hoc function to delete single occurrence of item from deque destructively
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
((and front (eql item (first front)))
(when (null (setf (deque-front deque) (rest front)))
(setf (deque-last-of-front deque) nil))
t)
((and rear (eql item (first rear)))
(when (null (setf (deque-rear deque) (rest rear)))
(setf (deque-last-of-rear deque) nil))
t)
((dotails (l front nil)
(when (and (rest l) (eql item (second l)))
(when (null (setf (rest l) (rrest l)))
(setf (deque-last-of-front deque) (first l)))
(return t))))
((dotails (l rear nil)
(when (and (rest l) (eql item (second l)))
(when (null (setf (rest l) (rrest l)))
(setf (deque-last-of-rear deque) (first l)))
(return t))))
(t
nil))))
(defun deque-delete-if (function deque)
;; ad hoc function to delete items from deque destructively
(let* ((deleted nil)
(front* (prog->
(delete-if (deque-front deque) ->* item)
(when (funcall function item)
(setf deleted t)))))
(when deleted
(setf (deque-front deque) front*)
(setf (deque-last-of-front deque) (first (last front*)))))
(let* ((deleted nil)
(rear* (prog->
(delete-if (deque-rear deque) :from-end t ->* item)
(when (funcall function item)
(setf deleted t)))))
(when deleted
(setf (deque-rear deque) rear*)
(setf (deque-last-of-rear deque) (first (last rear*)))))
deque)
(defun mapnconc-deque (function deque &key reverse)
;; ad hoc function to nconc results of applying function to items in deque
(let ((front (deque-front deque))
(rear (deque-rear deque))
(result nil) result-last)
(dolist (item (if reverse rear front))
(if (or (null function) (eq 'list function) (eq #'list function))
(collect item result)
(ncollect (funcall function item) result)))
(dolist (item (if reverse (reverse front) (reverse rear)))
(if (or (null function) (eq 'list function) (eq #'list function))
(collect item result)
(ncollect (funcall function item) result)))
result))
deque2.lisp EOF
| null | https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/deque2.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-deque -*-
File: deque2.lisp
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
returns last item in deque, nil if deque is empty
returns new deque with last item removed, deque if it is empty
like deque-butlast, but return last item and destructively remove it from deque
returns new deque with new last item added
like deque-add-last, but returns same deque with new last item added destructively
ad hoc function to delete single occurrence of item from deque destructively
ad hoc function to delete items from deque destructively
ad hoc function to nconc results of applying function to items in deque | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 .
All Rights Reserved .
Contributor(s ): < > .
(in-package :snark-deque)
(defstruct (deque
(:predicate deque?))
(front nil :type list)
(last-of-front nil)
(rear nil :type list)
(last-of-rear nil))
(defun deque-empty? (deque)
(and (null (deque-front deque)) (null (deque-rear deque))))
(defun deque-first (deque)
returns first item in deque , nil if deque is empty
(let ((front (deque-front deque)))
(if front (first front) (deque-last-of-rear deque))))
(defun deque-last (deque)
(let ((rear (deque-rear deque)))
(if rear (first rear) (deque-last-of-front deque))))
(defun deque-rest (deque)
returns new deque with first item removed , deque if it is empty
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(front
(let ((front* (rest front)))
(make-deque
:front front*
:last-of-front (if front* (deque-last-of-front deque) nil)
:rear rear
:last-of-rear (deque-last-of-rear deque))))
(rear
(let ((front* (rest (reverse rear))))
(make-deque
:front front*
:last-of-front (if front* (first rear) nil)
:rear nil
:last-of-rear nil)))
(t
deque))))
(defun deque-butlast (deque)
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(rear
(let ((rear* (rest rear)))
(make-deque
:rear rear*
:last-of-rear (if rear* (deque-last-of-rear deque) nil)
:front front
:last-of-front (deque-last-of-front deque))))
(front
(let ((rear* (rest (reverse front))))
(make-deque
:rear rear*
:last-of-rear (if rear* (first front) nil)
:front nil
:last-of-front nil)))
(t
deque))))
(defun deque-pop-first (deque)
like deque - rest , but return first item and destructively remove it from deque
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(front
(let ((front* (rest front)))
(setf (deque-front deque) front*)
(when (null front*)
(setf (deque-last-of-front deque) nil))
(first front)))
(rear
(let ((item (deque-last-of-rear deque))
(front* (rest (reverse rear))))
(setf (deque-front deque) front*)
(setf (deque-last-of-front deque) (if front* (first rear) nil))
(setf (deque-rear deque) nil)
(setf (deque-last-of-rear deque) nil)
item))
(t
nil))))
(defun deque-pop-last (deque)
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
(rear
(let ((rear* (rest rear)))
(setf (deque-rear deque) rear*)
(when (null rear*)
(setf (deque-last-of-rear deque) nil))
(first rear)))
(front
(let ((item (deque-last-of-front deque))
(rear* (rest (reverse front))))
(setf (deque-rear deque) rear*)
(setf (deque-last-of-rear deque) (if rear* (first front) nil))
(setf (deque-front deque) nil)
(setf (deque-last-of-front deque) nil)
item))
(t
nil))))
(defun deque-add-first (deque item)
returns new deque with new first item added
(let ((front (deque-front deque)))
(make-deque
:front (cons item front)
:last-of-front (if front (deque-last-of-front deque) item)
:rear (deque-rear deque)
:last-of-rear (deque-last-of-rear deque))))
(defun deque-add-last (deque item)
(let ((rear (deque-rear deque)))
(make-deque
:rear (cons item rear)
:last-of-rear (if rear (deque-last-of-rear deque) item)
:front (deque-front deque)
:last-of-front (deque-last-of-front deque))))
(defun deque-push-first (deque item)
like deque - add - first , but returns same deque with new first item added destructively
(let ((front (deque-front deque)))
(setf (deque-front deque) (cons item front))
(when (null front)
(setf (deque-last-of-front deque) item))
deque))
(defun deque-push-last (deque item)
(let ((rear (deque-rear deque)))
(setf (deque-rear deque) (cons item rear))
(when (null rear)
(setf (deque-last-of-rear deque) item))
deque))
(defun deque-length (deque)
(+ (length (deque-front deque)) (length (deque-rear deque))))
(defun deque-delete (deque item)
(let ((front (deque-front deque))
(rear (deque-rear deque)))
(cond
((and front (eql item (first front)))
(when (null (setf (deque-front deque) (rest front)))
(setf (deque-last-of-front deque) nil))
t)
((and rear (eql item (first rear)))
(when (null (setf (deque-rear deque) (rest rear)))
(setf (deque-last-of-rear deque) nil))
t)
((dotails (l front nil)
(when (and (rest l) (eql item (second l)))
(when (null (setf (rest l) (rrest l)))
(setf (deque-last-of-front deque) (first l)))
(return t))))
((dotails (l rear nil)
(when (and (rest l) (eql item (second l)))
(when (null (setf (rest l) (rrest l)))
(setf (deque-last-of-rear deque) (first l)))
(return t))))
(t
nil))))
(defun deque-delete-if (function deque)
(let* ((deleted nil)
(front* (prog->
(delete-if (deque-front deque) ->* item)
(when (funcall function item)
(setf deleted t)))))
(when deleted
(setf (deque-front deque) front*)
(setf (deque-last-of-front deque) (first (last front*)))))
(let* ((deleted nil)
(rear* (prog->
(delete-if (deque-rear deque) :from-end t ->* item)
(when (funcall function item)
(setf deleted t)))))
(when deleted
(setf (deque-rear deque) rear*)
(setf (deque-last-of-rear deque) (first (last rear*)))))
deque)
(defun mapnconc-deque (function deque &key reverse)
(let ((front (deque-front deque))
(rear (deque-rear deque))
(result nil) result-last)
(dolist (item (if reverse rear front))
(if (or (null function) (eq 'list function) (eq #'list function))
(collect item result)
(ncollect (funcall function item) result)))
(dolist (item (if reverse (reverse front) (reverse rear)))
(if (or (null function) (eq 'list function) (eq #'list function))
(collect item result)
(ncollect (funcall function item) result)))
result))
deque2.lisp EOF
|
086c77c951d7db1e55760ca5abce50cd09a5170739e862f2d395f2c7cabdde44 | theHamsta/petalisp-cuda | cuda-array.lisp | (defpackage petalisp-cuda.memory.cuda-array
(:use :cl
:iterate
:cl-itertools
:cffi)
(:import-from :cl-cuda.lang.type :cffi-type :cffi-type-size)
(:import-from :cl-cuda
:memory-block-device-ptr
:memory-block-host-ptr
:memory-block-type
:memory-block-size)
(:import-from :petalisp.core
:rank)
(:import-from :alexandria :if-let)
(:import-from :petalisp-cuda.utils.cl-cuda
:sync-memory-block-async)
(:import-from :petalisp-cuda.options
:*max-array-printing-length*
:*silence-cl-cuda*
:*page-locked-host-memory*)
(:export :make-cuda-array
:cuda-array
:cuda-array-shape
:cuda-array-strides
:cuda-array-type
:cuda-array-device
:cuda-array-from-lisp
:cuda-array-memory-block
:free-cuda-array
:copy-memory-block-to-lisp
:copy-cuda-array-to-lisp
:device-ptr
:nd-iter
:cuda-array-p
:type-from-cl-cuda-type
:lisp-type-from-cl-cuda-type))
(in-package :petalisp-cuda.memory.cuda-array)
(defun type-from-cl-cuda-type (element-type)
(cond
((equal element-type :uint8) '(unsigned-byte 8))
((equal element-type :uint16) '(unsigned-byte 16))
((equal element-type :uint32) '(unsigned-byte 32))
((equal element-type :uint64) '(unsigned-byte 64))
((equal element-type :int8) '(signed-byte 8))
((equal element-type :int16) '(signed-byte 16))
((equal element-type :int) '(signed-byte 32))
((equal element-type :int64) '(signed-byte 64))
((equal element-type :float) 'single-float)
((equal element-type :double) 'double-float)
(t (error "Cannot convert ~S to ntype." element-type))))
(defun lisp-type-cuda-array (cu-array)
(type-from-cl-cuda-type (cuda-array-type cu-array)))
; TODO: generalize to (memory-block memory-layout) ?
(defstruct (cuda-array (:constructor %make-cuda-array))
(memory-block :memory-block :type (or cl-cuda.api.memory::memory-block null))
(shape :shape :type list :read-only t)
(strides :strides :type list :read-only t))
(declaim (inline nd-iter))
(defiter nd-iter (shape)
(let* ((ndim (length shape))
(cur (mapcar (lambda (x) (* 0 x)) shape))
(last-idx (1- ndim))
(last-element (mapcar #'1- shape)))
(loop do (progn
(yield cur)
(loop for i from last-idx downto 0
do (progn
(incf (nth i cur))
(if (= (nth i cur) (nth i shape))
(setf (nth i cur) 0)
(loop-finish))))
(when (equal last-element cur)
(progn
(yield cur)
(loop-finish)))))))
;TODO: redo this with allocator type
(defgeneric make-cuda-array (shape dtype &optional strides alloc-function alignment)
(:method ((array cuda-array) dtype &optional strides alloc-function alignment)
(cuda-array-from-cuda-array array dtype strides alloc-function alignment))
(:method ((array array) dtype &optional strides alloc-function alignment)
(cuda-array-from-lisp array dtype strides alloc-function alignment))
;; from raw shape
(:method ((shape list) dtype &optional strides alloc-function alignment)
(let ((alloc-function (or alloc-function
#'cl-cuda:alloc-memory-block))
(alignment (or alignment (alexandria:switch (dtype :test #'equal)
(:half 2)
(:bfloat16 2)))))
(multiple-value-bind (size strides) (mem-layout-from-shape shape strides alignment)
(%make-cuda-array :memory-block (funcall alloc-function dtype (max size 1))
:shape shape
:strides strides))))
;; from raw petalisp:shape
(:method ((shape petalisp:shape) dtype &optional strides alloc-function alignment)
(let ((dimensions (mapcar #'petalisp:range-size (petalisp:shape-ranges shape))))
(make-cuda-array dimensions dtype strides alloc-function alignment))))
(defun cuda-array-from-lisp (lisp-array dtype &optional strides alloc-function alignment)
(let* ((shape (array-dimensions lisp-array))
(cuda-array (make-cuda-array shape dtype strides alloc-function alignment)))
(copy-lisp-to-cuda-array lisp-array cuda-array)))
(defun cuda-array-from-cuda-array (cuda-array dtype &optional strides alloc-function alignment)
(let* ((shape (cuda-array-shape cuda-array))
(new-cuda-array (make-cuda-array shape dtype strides alloc-function alignment))
(from-ptr (memory-block-device-ptr (cuda-array-memory-block cuda-array)))
(to-ptr (memory-block-device-ptr (cuda-array-memory-block new-cuda-array))))
;; TODO: memcpy3d in order to change layout?
(assert (= 0 (petalisp-cuda.cudalibs::cuMemcpyDtoDAsync_v2 to-ptr
from-ptr
(make-pointer (* (cuda-array-size cuda-array)
(cffi-type-size dtype)))
cl-cuda:*cuda-stream*)))
new-cuda-array))
(defun cuda-array-size (cuda-array)
(memory-block-size (cuda-array-memory-block cuda-array)))
(defun free-cuda-array (array &optional free-function)
;TODO: redo this with allocator type
(let ((free-function (or free-function
#'cl-cuda:free-memory-block)))
(funcall free-function (cuda-array-memory-block array))
(setf (cuda-array-memory-block array) nil)))
(defun cuda-array-aref (array indices)
(let ((memory-block (slot-value array 'memory-block))
(strides (slot-value array 'strides)))
(cl-cuda:memory-block-aref memory-block (reduce #'+ (mapcar #'* indices strides)))))
(defun set-cuda-array-aref (array indices value)
(let ((memory-block (slot-value array 'memory-block))
(strides (slot-value array 'strides)))
(setf (cl-cuda:memory-block-aref memory-block (reduce #'+ (mapcar #'* indices strides))) value)))
(defun cuda-array-type (array)
(cffi-type (cl-cuda:memory-block-type (slot-value array 'memory-block))))
(defun device-ptr (array)
(cl-cuda:memory-block-device-ptr (slot-value array 'memory-block)))
(defun element-size (array)
(cffi-type-size (cuda-array-type array)))
(defun raw-memory-strides (array)
(mapcar (lambda (s) (* s (element-size array))) (slot-value array 'strides)))
(defmethod petalisp.core:rank ((array cuda-array))
(length (cuda-array-shape array)))
(defun can-do-dark-pointer-magic-p (cuda-array &optional lisp-array)
#+sbcl
(let* ((lisp-array-type (if lisp-array
(array-element-type lisp-array)
(lisp-type-cuda-array cuda-array))))
(and
(c-layout-p cuda-array) ; at least the host array should have c-layout
(case lisp-array-type
(single-float t)
(double-float t)
((signed-byte 32) (= 4 (element-size cuda-array)))))))
;; TODO: add with-host-memory ensured to only temporarily add host memory and re-use a common host-mem staging area?
(defun host-alloc (element-type size)
(if *page-locked-host-memory*
(with-foreign-object (ptr '(:pointer (:pointer :void)))
(assert (= 0 (petalisp-cuda.cudalibs::cuMemAllocHost_v2 ptr (make-pointer (* size (cffi-type-size element-type))))))
(mem-ref ptr :pointer))
(cl-cuda:alloc-host-memory element-type size)))
(defun ensure-host-memory (cuda-array)
(let ((memory-block (cuda-array-memory-block cuda-array)))
(when (null-pointer-p (memory-block-host-ptr memory-block))
(setf (cuda-array-memory-block cuda-array)
(cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr memory-block)
:host-ptr (host-alloc (memory-block-type memory-block)
(memory-block-size memory-block))
:type (memory-block-type memory-block)
:size (memory-block-size memory-block))))))
(defun copy-cuda-array-to-lisp (cuda-array)
(declare (optimize (debug 0)(speed 3)(safety 0)))
(ensure-host-memory cuda-array)
(let ((memory-block (cuda-array-memory-block cuda-array))
(shape (cuda-array-shape cuda-array))
(cl-cuda:*show-messages* (if *silence-cl-cuda* nil cl-cuda:*show-messages*)))
(if shape
(if (c-layout-p cuda-array)
(if (can-do-dark-pointer-magic-p cuda-array)
c - layout and sbcl : pin array and cudaMemcpy from Lisp
(let ((lisp-array (make-array (cuda-array-shape cuda-array) :element-type (lisp-type-cuda-array cuda-array))))
#+sbcl
(sb-sys:with-pinned-objects ((sb-ext:array-storage-vector lisp-array))
(let ((alien (sb-sys:vector-sap (sb-ext:array-storage-vector lisp-array))))
(let* ((new-memory-block
(cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr memory-block)
:host-ptr alien
:type (memory-block-type memory-block)
:size (memory-block-size memory-block))))
;; not aync since we pinning the lisp array
(cl-cuda:sync-memory-block new-memory-block :device-to-host))))
lisp-array)
;; c-layout: cffi-package
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(foreign-array-to-lisp
(cl-cuda:memory-block-host-ptr (cuda-array-memory-block cuda-array))
`(:array ,(cuda-array-type cuda-array) ,@(cuda-array-shape cuda-array)))))
;; No c-layout: slow generate
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(aops:generate* (lisp-type-cuda-array cuda-array)
(lambda (indices) (cuda-array-aref cuda-array indices))
shape
:subscripts)))
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(make-array nil :initial-element (cuda-array-aref cuda-array '(0)))))))
(defun cuda-array-device (cuda-array)
"Returns the device index on which the array was allocated"
(let ((ptr (memory-block-device-ptr (cuda-array-memory-block cuda-array))))
(with-foreign-object (data '(:pointer :int))
(assert (= 0
(petalisp-cuda.cudalibs::cuPointerGetAttribute data
(foreign-enum-value 'petalisp-cuda.cudalibs::cupointer-attribute-enum
:cu-pointer-attribute-device-ordinal)
ptr)))
(mem-ref data :int))))
(defun copy-lisp-to-cuda-array-slow-fallback (lisp-array cuda-array)
(declare (optimize (debug 0)(speed 3)(safety 0)))
(ensure-host-memory cuda-array)
(iterate (for idx in-it (petalisp-cuda.memory.cuda-array:nd-iter (cuda-array-shape cuda-array)))
(set-cuda-array-aref cuda-array idx (if (equal t (array-element-type lisp-array))
(coerce (apply #'aref `(,lisp-array ,@idx)) 'single-float)
(apply #'aref `(,lisp-array ,@idx))))))
(defun copy-lisp-to-cuda-array (lisp-array cuda-array)
(let ((dark-pointer-magic-p (can-do-dark-pointer-magic-p cuda-array lisp-array)))
(unless dark-pointer-magic-p
(ensure-host-memory cuda-array))
(let ((memory-block (cuda-array-memory-block cuda-array))
(cuda-shape (cuda-array-shape cuda-array))
(cl-cuda:*show-messages* (unless *silence-cl-cuda* cl-cuda:*show-messages*)))
(assert (equalp (array-dimensions lisp-array) cuda-shape))
(if (c-layout-p cuda-array)
(handler-case
;; dirty internals
(if dark-pointer-magic-p
#-sbcl (error "dark-pointer-magic-p is always nil without SBCL")
#+sbcl
(sb-sys:with-pinned-objects ((sb-ext:array-storage-vector lisp-array))
(let ((alien (sb-sys:vector-sap (sb-ext:array-storage-vector lisp-array))))
(let* ((mem-block (cuda-array-memory-block cuda-array))
(new-memory-block (cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr mem-block)
:host-ptr alien
:type (memory-block-type mem-block)
:size (memory-block-size mem-block))))
;; not aync since we pinning the lisp array
(cl-cuda:sync-memory-block new-memory-block :host-to-device))))
;; copy to foreign
(lisp-array-to-foreign lisp-array
(cl-cuda:memory-block-host-ptr (cuda-array-memory-block cuda-array))
`(:array ,(cuda-array-type cuda-array) ,@(cuda-array-shape cuda-array))))
(type-error (e)
(declare (ignore e))
(copy-lisp-to-cuda-array-slow-fallback lisp-array cuda-array)))
(copy-lisp-to-cuda-array-slow-fallback lisp-array cuda-array))
(unless dark-pointer-magic-p
(sync-memory-block-async memory-block :host-to-device))
cuda-array)))
(defun round-up (number multiple)
(* multiple (ceiling number multiple)))
(defun mem-layout-from-shape (shape &optional strides alignment)
(c-mem-layout-from-shape shape strides alignment))
(defun c-mem-layout-from-shape (shape &optional strides alignment)
(let* ((alignment (or alignment 1))
(strides (or strides
(reverse (iter (for element in (reverse shape))
(accumulate element by #'* :initial-value 1 into acc)
(collect (if (= acc element)
1
(round-up (/ acc element) alignment)))))))
(size (reduce #'max (mapcar #'* strides shape)
even with all - zeros strides we need at least one element
:initial-value 1)))
(values (round-up size alignment) strides)))
(defun c-layout-p (cuda-array)
(multiple-value-bind (size strides) (c-mem-layout-from-shape (cuda-array-shape cuda-array))
(declare (ignore size))
(loop for stride in (cuda-array-strides cuda-array)
for range in (cuda-array-strides cuda-array)
for c-stride in strides
always (or (= range 1) (= range 0) (= c-stride stride)))))
(defmethod petalisp.core:shape ((array cuda-array))
(let* ((shape (cuda-array-shape array)))
(petalisp.core::make-shape
(mapcar (lambda (s) (petalisp.core:range s)) shape))))
CUresult CUDAAPI cuPointerGetAttribute(void * data , CUpointer_attribute attribute , ) ;
;; :cu-pointer-attribute-is-managed
(defun is-managed (device-pointer)
(with-forein-object data (:pointer :bool)
(assert
(= 0
(cuPointerGetAttribute data
:cu-pointer-attribute-is-managed
device-pointer)))
(mem-ref data :bool)))
(defmethod print-object :after ((cuda-array cuda-array) stream)
(unless (or *print-readably* (= *max-array-printing-length* 0))
(ensure-host-memory cuda-array)
(let ((cl-cuda:*show-messages* (if *silence-cl-cuda* nil cl-cuda:*show-messages*)))
(cl-cuda:sync-memory-block (cuda-array-memory-block cuda-array) :device-to-host)
(let* ((shape (cuda-array-shape cuda-array))
(rank (length shape))
(max-idx (mapcar #'1- shape))
(max-border (mapcar (lambda (i) (- i *max-array-printing-length*)) shape)))
(format stream "~%~%")
(if (= rank 0)
(format stream "~A~%" (cuda-array-aref cuda-array '(0)))
(iterate (for idx in-it (petalisp-cuda.memory.cuda-array:nd-iter shape))
(when (every (lambda (i max) (or (<= i *max-array-printing-length*) (> i max))) idx max-border)
(dotimes (i rank)
(when (every (lambda (i) (= i 0)) (subseq idx i))
(format stream "(")))
(if (some (lambda (i) (= i *max-array-printing-length*)) idx)
(format stream "... ")
(format stream "~A " (cuda-array-aref cuda-array idx)))
(dotimes (i rank)
(when (every (lambda (i max) (= i max)) (subseq idx i) (subseq max-idx i))
(format stream ")")))
(when (= (car (last idx)) (1- (car (last shape))))
(format stream "~%")))))))))
| null | https://raw.githubusercontent.com/theHamsta/petalisp-cuda/12b9ee426e14edf492d862d5bd2dbec18ec427c6/src/memory/cuda-array.lisp | lisp | TODO: generalize to (memory-block memory-layout) ?
TODO: redo this with allocator type
from raw shape
from raw petalisp:shape
TODO: memcpy3d in order to change layout?
TODO: redo this with allocator type
at least the host array should have c-layout
TODO: add with-host-memory ensured to only temporarily add host memory and re-use a common host-mem staging area?
not aync since we pinning the lisp array
c-layout: cffi-package
No c-layout: slow generate
dirty internals
not aync since we pinning the lisp array
copy to foreign
:cu-pointer-attribute-is-managed | (defpackage petalisp-cuda.memory.cuda-array
(:use :cl
:iterate
:cl-itertools
:cffi)
(:import-from :cl-cuda.lang.type :cffi-type :cffi-type-size)
(:import-from :cl-cuda
:memory-block-device-ptr
:memory-block-host-ptr
:memory-block-type
:memory-block-size)
(:import-from :petalisp.core
:rank)
(:import-from :alexandria :if-let)
(:import-from :petalisp-cuda.utils.cl-cuda
:sync-memory-block-async)
(:import-from :petalisp-cuda.options
:*max-array-printing-length*
:*silence-cl-cuda*
:*page-locked-host-memory*)
(:export :make-cuda-array
:cuda-array
:cuda-array-shape
:cuda-array-strides
:cuda-array-type
:cuda-array-device
:cuda-array-from-lisp
:cuda-array-memory-block
:free-cuda-array
:copy-memory-block-to-lisp
:copy-cuda-array-to-lisp
:device-ptr
:nd-iter
:cuda-array-p
:type-from-cl-cuda-type
:lisp-type-from-cl-cuda-type))
(in-package :petalisp-cuda.memory.cuda-array)
(defun type-from-cl-cuda-type (element-type)
(cond
((equal element-type :uint8) '(unsigned-byte 8))
((equal element-type :uint16) '(unsigned-byte 16))
((equal element-type :uint32) '(unsigned-byte 32))
((equal element-type :uint64) '(unsigned-byte 64))
((equal element-type :int8) '(signed-byte 8))
((equal element-type :int16) '(signed-byte 16))
((equal element-type :int) '(signed-byte 32))
((equal element-type :int64) '(signed-byte 64))
((equal element-type :float) 'single-float)
((equal element-type :double) 'double-float)
(t (error "Cannot convert ~S to ntype." element-type))))
(defun lisp-type-cuda-array (cu-array)
(type-from-cl-cuda-type (cuda-array-type cu-array)))
(defstruct (cuda-array (:constructor %make-cuda-array))
(memory-block :memory-block :type (or cl-cuda.api.memory::memory-block null))
(shape :shape :type list :read-only t)
(strides :strides :type list :read-only t))
(declaim (inline nd-iter))
(defiter nd-iter (shape)
(let* ((ndim (length shape))
(cur (mapcar (lambda (x) (* 0 x)) shape))
(last-idx (1- ndim))
(last-element (mapcar #'1- shape)))
(loop do (progn
(yield cur)
(loop for i from last-idx downto 0
do (progn
(incf (nth i cur))
(if (= (nth i cur) (nth i shape))
(setf (nth i cur) 0)
(loop-finish))))
(when (equal last-element cur)
(progn
(yield cur)
(loop-finish)))))))
(defgeneric make-cuda-array (shape dtype &optional strides alloc-function alignment)
(:method ((array cuda-array) dtype &optional strides alloc-function alignment)
(cuda-array-from-cuda-array array dtype strides alloc-function alignment))
(:method ((array array) dtype &optional strides alloc-function alignment)
(cuda-array-from-lisp array dtype strides alloc-function alignment))
(:method ((shape list) dtype &optional strides alloc-function alignment)
(let ((alloc-function (or alloc-function
#'cl-cuda:alloc-memory-block))
(alignment (or alignment (alexandria:switch (dtype :test #'equal)
(:half 2)
(:bfloat16 2)))))
(multiple-value-bind (size strides) (mem-layout-from-shape shape strides alignment)
(%make-cuda-array :memory-block (funcall alloc-function dtype (max size 1))
:shape shape
:strides strides))))
(:method ((shape petalisp:shape) dtype &optional strides alloc-function alignment)
(let ((dimensions (mapcar #'petalisp:range-size (petalisp:shape-ranges shape))))
(make-cuda-array dimensions dtype strides alloc-function alignment))))
(defun cuda-array-from-lisp (lisp-array dtype &optional strides alloc-function alignment)
(let* ((shape (array-dimensions lisp-array))
(cuda-array (make-cuda-array shape dtype strides alloc-function alignment)))
(copy-lisp-to-cuda-array lisp-array cuda-array)))
(defun cuda-array-from-cuda-array (cuda-array dtype &optional strides alloc-function alignment)
(let* ((shape (cuda-array-shape cuda-array))
(new-cuda-array (make-cuda-array shape dtype strides alloc-function alignment))
(from-ptr (memory-block-device-ptr (cuda-array-memory-block cuda-array)))
(to-ptr (memory-block-device-ptr (cuda-array-memory-block new-cuda-array))))
(assert (= 0 (petalisp-cuda.cudalibs::cuMemcpyDtoDAsync_v2 to-ptr
from-ptr
(make-pointer (* (cuda-array-size cuda-array)
(cffi-type-size dtype)))
cl-cuda:*cuda-stream*)))
new-cuda-array))
(defun cuda-array-size (cuda-array)
(memory-block-size (cuda-array-memory-block cuda-array)))
(defun free-cuda-array (array &optional free-function)
(let ((free-function (or free-function
#'cl-cuda:free-memory-block)))
(funcall free-function (cuda-array-memory-block array))
(setf (cuda-array-memory-block array) nil)))
(defun cuda-array-aref (array indices)
(let ((memory-block (slot-value array 'memory-block))
(strides (slot-value array 'strides)))
(cl-cuda:memory-block-aref memory-block (reduce #'+ (mapcar #'* indices strides)))))
(defun set-cuda-array-aref (array indices value)
(let ((memory-block (slot-value array 'memory-block))
(strides (slot-value array 'strides)))
(setf (cl-cuda:memory-block-aref memory-block (reduce #'+ (mapcar #'* indices strides))) value)))
(defun cuda-array-type (array)
(cffi-type (cl-cuda:memory-block-type (slot-value array 'memory-block))))
(defun device-ptr (array)
(cl-cuda:memory-block-device-ptr (slot-value array 'memory-block)))
(defun element-size (array)
(cffi-type-size (cuda-array-type array)))
(defun raw-memory-strides (array)
(mapcar (lambda (s) (* s (element-size array))) (slot-value array 'strides)))
(defmethod petalisp.core:rank ((array cuda-array))
(length (cuda-array-shape array)))
(defun can-do-dark-pointer-magic-p (cuda-array &optional lisp-array)
#+sbcl
(let* ((lisp-array-type (if lisp-array
(array-element-type lisp-array)
(lisp-type-cuda-array cuda-array))))
(and
(case lisp-array-type
(single-float t)
(double-float t)
((signed-byte 32) (= 4 (element-size cuda-array)))))))
(defun host-alloc (element-type size)
(if *page-locked-host-memory*
(with-foreign-object (ptr '(:pointer (:pointer :void)))
(assert (= 0 (petalisp-cuda.cudalibs::cuMemAllocHost_v2 ptr (make-pointer (* size (cffi-type-size element-type))))))
(mem-ref ptr :pointer))
(cl-cuda:alloc-host-memory element-type size)))
(defun ensure-host-memory (cuda-array)
(let ((memory-block (cuda-array-memory-block cuda-array)))
(when (null-pointer-p (memory-block-host-ptr memory-block))
(setf (cuda-array-memory-block cuda-array)
(cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr memory-block)
:host-ptr (host-alloc (memory-block-type memory-block)
(memory-block-size memory-block))
:type (memory-block-type memory-block)
:size (memory-block-size memory-block))))))
(defun copy-cuda-array-to-lisp (cuda-array)
(declare (optimize (debug 0)(speed 3)(safety 0)))
(ensure-host-memory cuda-array)
(let ((memory-block (cuda-array-memory-block cuda-array))
(shape (cuda-array-shape cuda-array))
(cl-cuda:*show-messages* (if *silence-cl-cuda* nil cl-cuda:*show-messages*)))
(if shape
(if (c-layout-p cuda-array)
(if (can-do-dark-pointer-magic-p cuda-array)
c - layout and sbcl : pin array and cudaMemcpy from Lisp
(let ((lisp-array (make-array (cuda-array-shape cuda-array) :element-type (lisp-type-cuda-array cuda-array))))
#+sbcl
(sb-sys:with-pinned-objects ((sb-ext:array-storage-vector lisp-array))
(let ((alien (sb-sys:vector-sap (sb-ext:array-storage-vector lisp-array))))
(let* ((new-memory-block
(cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr memory-block)
:host-ptr alien
:type (memory-block-type memory-block)
:size (memory-block-size memory-block))))
(cl-cuda:sync-memory-block new-memory-block :device-to-host))))
lisp-array)
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(foreign-array-to-lisp
(cl-cuda:memory-block-host-ptr (cuda-array-memory-block cuda-array))
`(:array ,(cuda-array-type cuda-array) ,@(cuda-array-shape cuda-array)))))
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(aops:generate* (lisp-type-cuda-array cuda-array)
(lambda (indices) (cuda-array-aref cuda-array indices))
shape
:subscripts)))
(progn
(cl-cuda:sync-memory-block memory-block :device-to-host)
(make-array nil :initial-element (cuda-array-aref cuda-array '(0)))))))
(defun cuda-array-device (cuda-array)
"Returns the device index on which the array was allocated"
(let ((ptr (memory-block-device-ptr (cuda-array-memory-block cuda-array))))
(with-foreign-object (data '(:pointer :int))
(assert (= 0
(petalisp-cuda.cudalibs::cuPointerGetAttribute data
(foreign-enum-value 'petalisp-cuda.cudalibs::cupointer-attribute-enum
:cu-pointer-attribute-device-ordinal)
ptr)))
(mem-ref data :int))))
(defun copy-lisp-to-cuda-array-slow-fallback (lisp-array cuda-array)
(declare (optimize (debug 0)(speed 3)(safety 0)))
(ensure-host-memory cuda-array)
(iterate (for idx in-it (petalisp-cuda.memory.cuda-array:nd-iter (cuda-array-shape cuda-array)))
(set-cuda-array-aref cuda-array idx (if (equal t (array-element-type lisp-array))
(coerce (apply #'aref `(,lisp-array ,@idx)) 'single-float)
(apply #'aref `(,lisp-array ,@idx))))))
(defun copy-lisp-to-cuda-array (lisp-array cuda-array)
(let ((dark-pointer-magic-p (can-do-dark-pointer-magic-p cuda-array lisp-array)))
(unless dark-pointer-magic-p
(ensure-host-memory cuda-array))
(let ((memory-block (cuda-array-memory-block cuda-array))
(cuda-shape (cuda-array-shape cuda-array))
(cl-cuda:*show-messages* (unless *silence-cl-cuda* cl-cuda:*show-messages*)))
(assert (equalp (array-dimensions lisp-array) cuda-shape))
(if (c-layout-p cuda-array)
(handler-case
(if dark-pointer-magic-p
#-sbcl (error "dark-pointer-magic-p is always nil without SBCL")
#+sbcl
(sb-sys:with-pinned-objects ((sb-ext:array-storage-vector lisp-array))
(let ((alien (sb-sys:vector-sap (sb-ext:array-storage-vector lisp-array))))
(let* ((mem-block (cuda-array-memory-block cuda-array))
(new-memory-block (cl-cuda.api.memory::%make-memory-block :device-ptr (memory-block-device-ptr mem-block)
:host-ptr alien
:type (memory-block-type mem-block)
:size (memory-block-size mem-block))))
(cl-cuda:sync-memory-block new-memory-block :host-to-device))))
(lisp-array-to-foreign lisp-array
(cl-cuda:memory-block-host-ptr (cuda-array-memory-block cuda-array))
`(:array ,(cuda-array-type cuda-array) ,@(cuda-array-shape cuda-array))))
(type-error (e)
(declare (ignore e))
(copy-lisp-to-cuda-array-slow-fallback lisp-array cuda-array)))
(copy-lisp-to-cuda-array-slow-fallback lisp-array cuda-array))
(unless dark-pointer-magic-p
(sync-memory-block-async memory-block :host-to-device))
cuda-array)))
(defun round-up (number multiple)
(* multiple (ceiling number multiple)))
(defun mem-layout-from-shape (shape &optional strides alignment)
(c-mem-layout-from-shape shape strides alignment))
(defun c-mem-layout-from-shape (shape &optional strides alignment)
(let* ((alignment (or alignment 1))
(strides (or strides
(reverse (iter (for element in (reverse shape))
(accumulate element by #'* :initial-value 1 into acc)
(collect (if (= acc element)
1
(round-up (/ acc element) alignment)))))))
(size (reduce #'max (mapcar #'* strides shape)
even with all - zeros strides we need at least one element
:initial-value 1)))
(values (round-up size alignment) strides)))
(defun c-layout-p (cuda-array)
(multiple-value-bind (size strides) (c-mem-layout-from-shape (cuda-array-shape cuda-array))
(declare (ignore size))
(loop for stride in (cuda-array-strides cuda-array)
for range in (cuda-array-strides cuda-array)
for c-stride in strides
always (or (= range 1) (= range 0) (= c-stride stride)))))
(defmethod petalisp.core:shape ((array cuda-array))
(let* ((shape (cuda-array-shape array)))
(petalisp.core::make-shape
(mapcar (lambda (s) (petalisp.core:range s)) shape))))
(defun is-managed (device-pointer)
(with-forein-object data (:pointer :bool)
(assert
(= 0
(cuPointerGetAttribute data
:cu-pointer-attribute-is-managed
device-pointer)))
(mem-ref data :bool)))
(defmethod print-object :after ((cuda-array cuda-array) stream)
(unless (or *print-readably* (= *max-array-printing-length* 0))
(ensure-host-memory cuda-array)
(let ((cl-cuda:*show-messages* (if *silence-cl-cuda* nil cl-cuda:*show-messages*)))
(cl-cuda:sync-memory-block (cuda-array-memory-block cuda-array) :device-to-host)
(let* ((shape (cuda-array-shape cuda-array))
(rank (length shape))
(max-idx (mapcar #'1- shape))
(max-border (mapcar (lambda (i) (- i *max-array-printing-length*)) shape)))
(format stream "~%~%")
(if (= rank 0)
(format stream "~A~%" (cuda-array-aref cuda-array '(0)))
(iterate (for idx in-it (petalisp-cuda.memory.cuda-array:nd-iter shape))
(when (every (lambda (i max) (or (<= i *max-array-printing-length*) (> i max))) idx max-border)
(dotimes (i rank)
(when (every (lambda (i) (= i 0)) (subseq idx i))
(format stream "(")))
(if (some (lambda (i) (= i *max-array-printing-length*)) idx)
(format stream "... ")
(format stream "~A " (cuda-array-aref cuda-array idx)))
(dotimes (i rank)
(when (every (lambda (i max) (= i max)) (subseq idx i) (subseq max-idx i))
(format stream ")")))
(when (= (car (last idx)) (1- (car (last shape))))
(format stream "~%")))))))))
|
9d708319efd50f19ee46b1cf677d652d86d11c1ab5059a932bd2d7531454207f | kawasima/jagrid | core.clj | (ns jagrid.example.core
(:require [compojure.core :refer :all]
[ring.util.response :refer [file-response content-type]]
[jagrid.css.core :as css]
[jagrid.example.index :as index]
[jagrid.example.basic :as basic]
[jagrid.example.sales-report :as sales-report]))
(defn build-examples []
(spit "example/index.html" (index/view))
(spit "example/basic.html" (basic/view))
(spit "example/sales-report.html" (sales-report/view)))
(defroutes example-routes
(GET "/" [] (index/view))
(GET "/basic.html" [] (basic/view))
(GET "/sales-report.html" [] (sales-report/view))
(GET "/js/jagrid.js" [] (-> (file-response "js/jagrid.js")
(content-type "text/javascript")))
(GET "/example.css" [] (-> (file-response "example/example.css")
(content-type "text/css")))
(GET "/css/*.css" {{filename :*} :params}
(-> (file-response (str "css/" filename ".css"))
(content-type "text/css"))))
| null | https://raw.githubusercontent.com/kawasima/jagrid/524b351c47ba2648f96ce8ef5ee431d0eb594d28/src/jagrid/example/core.clj | clojure | (ns jagrid.example.core
(:require [compojure.core :refer :all]
[ring.util.response :refer [file-response content-type]]
[jagrid.css.core :as css]
[jagrid.example.index :as index]
[jagrid.example.basic :as basic]
[jagrid.example.sales-report :as sales-report]))
(defn build-examples []
(spit "example/index.html" (index/view))
(spit "example/basic.html" (basic/view))
(spit "example/sales-report.html" (sales-report/view)))
(defroutes example-routes
(GET "/" [] (index/view))
(GET "/basic.html" [] (basic/view))
(GET "/sales-report.html" [] (sales-report/view))
(GET "/js/jagrid.js" [] (-> (file-response "js/jagrid.js")
(content-type "text/javascript")))
(GET "/example.css" [] (-> (file-response "example/example.css")
(content-type "text/css")))
(GET "/css/*.css" {{filename :*} :params}
(-> (file-response (str "css/" filename ".css"))
(content-type "text/css"))))
| |
1d3ca7ed64857dbf8e8287052ce3bf5b828524fceeb8d9a0534d8d669a9db73c | rd--/hsc3 | b_alloc.help.hs | ---- ; help
Sound.Sc3.sc3_scdoc_help_server_command_open False "/b_alloc"
Buffer indices are not restricted by the number of available buffers
at the server. Below allocates a buffer at index 2 ^ 15. Note the
b_alloc_setn1, which adds a b_set completion message to the b_alloc
message, is still asynchronous.
> import Sound.Sc3 {- hsc3 -}
> b0 :: Num n => n
> b0 = 2 ^ 15
> m0 = b_alloc_setn1 b0 0 [0,3,7,10]
b0 == 2 ^ 15
withSc3 (async m0)
withSc3 (b_getn1_data b0 (0,4))
> g0 =
> let x = mouseX KR 0 9 Linear 0.1
> k = degreeToKey b0 x 12
> in sinOsc AR (midiCps (48 + k)) 0 * 0.1
| null | https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Server/b_alloc.help.hs | haskell | -- ; help
hsc3 | Sound.Sc3.sc3_scdoc_help_server_command_open False "/b_alloc"
Buffer indices are not restricted by the number of available buffers
at the server. Below allocates a buffer at index 2 ^ 15. Note the
b_alloc_setn1, which adds a b_set completion message to the b_alloc
message, is still asynchronous.
> b0 :: Num n => n
> b0 = 2 ^ 15
> m0 = b_alloc_setn1 b0 0 [0,3,7,10]
b0 == 2 ^ 15
withSc3 (async m0)
withSc3 (b_getn1_data b0 (0,4))
> g0 =
> let x = mouseX KR 0 9 Linear 0.1
> k = degreeToKey b0 x 12
> in sinOsc AR (midiCps (48 + k)) 0 * 0.1
|
10deb8d98647f64a63eebf9a018d5ea76975455a95dbcdafc4de5ab015ce7e84 | ocamllabs/ocaml-scry | repo.ml | open Sexplib.Std
type r = {
r_cmd : string;
r_args : string list;
r_env : string array;
r_cwd : string;
r_duration : Time.duration;
r_stdout : string;
r_stderr : string;
} [@@deriving sexp]
type proc_status =
| Exited of int
| Signaled of int
| Stopped of int
[@@deriving sexp]
exception ProcessError of proc_status * r
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-scry/3ba35317975fe78dab06cd28822219a0eab7c318/lib/repo.ml | ocaml | open Sexplib.Std
type r = {
r_cmd : string;
r_args : string list;
r_env : string array;
r_cwd : string;
r_duration : Time.duration;
r_stdout : string;
r_stderr : string;
} [@@deriving sexp]
type proc_status =
| Exited of int
| Signaled of int
| Stopped of int
[@@deriving sexp]
exception ProcessError of proc_status * r
| |
ae582be81ed34174f62ef48fb4c934694ea549f6450beec4f830ecc04834e0dc | kupl/LearnML | original.ml | type nat = ZERO | SUCC of nat
let two : nat = SUCC (SUCC ZERO)
let three : nat = SUCC (SUCC (SUCC ZERO))
let rec natadd (n1 : nat) (n2 : nat) : nat =
if n1 = two then SUCC (SUCC n2) else SUCC (SUCC (SUCC n2))
let rec natmul (n1 : nat) (n2 : nat) : nat =
if n1 = two then if n2 = two then SUCC (SUCC n2) else SUCC (SUCC (SUCC n2))
else if n2 = two then SUCC (SUCC (SUCC n2))
else SUCC (SUCC (SUCC (SUCC (SUCC (SUCC n2)))))
let (_ : nat) = natadd two two
let (_ : nat) = natadd two three
let (_ : nat) = natadd three two
let (_ : nat) = natadd three three
let (_ : nat) = natmul two three
let (_ : nat) = natmul two two
let (_ : nat) = natmul three three
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/nat/sub21/original.ml | ocaml | type nat = ZERO | SUCC of nat
let two : nat = SUCC (SUCC ZERO)
let three : nat = SUCC (SUCC (SUCC ZERO))
let rec natadd (n1 : nat) (n2 : nat) : nat =
if n1 = two then SUCC (SUCC n2) else SUCC (SUCC (SUCC n2))
let rec natmul (n1 : nat) (n2 : nat) : nat =
if n1 = two then if n2 = two then SUCC (SUCC n2) else SUCC (SUCC (SUCC n2))
else if n2 = two then SUCC (SUCC (SUCC n2))
else SUCC (SUCC (SUCC (SUCC (SUCC (SUCC n2)))))
let (_ : nat) = natadd two two
let (_ : nat) = natadd two three
let (_ : nat) = natadd three two
let (_ : nat) = natadd three three
let (_ : nat) = natmul two three
let (_ : nat) = natmul two two
let (_ : nat) = natmul three three
| |
b0d82fa9bf3faefd72d86f247ed1c3aef05a9999372654e07cf6e2ee4010d11f | facebook/infer | ToplAstOps.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
let pp_pattern f (pattern : ToplAst.label_pattern) =
match pattern with
| ArrayWritePattern ->
F.fprintf f "#ArrayWrite"
| ProcedureNamePattern procedure_name ->
F.fprintf f "\"%s\"" procedure_name
let pp_constant f (constant : ToplAst.constant) =
match constant with LiteralInt x -> F.fprintf f "%d" x
let pp_register = F.pp_print_string
let pp_variable = F.pp_print_string
let pp_fieldname = F.pp_print_string
let pp_classname = F.pp_print_string
let rec pp_value f (value : ToplAst.value) =
match value with
| Constant c ->
pp_constant f c
| Register r ->
pp_register f r
| Binding v ->
pp_variable f v
| FieldAccess {value; class_name; field_name} ->
F.fprintf f "@[%a:%a.%a@]@," pp_value value pp_classname class_name pp_fieldname field_name
let pp_binop f (binop : ToplAst.binop) =
match binop with
| LeadsTo ->
F.fprintf f "~~>"
| OpEq ->
F.fprintf f "=="
| OpNe ->
F.fprintf f "!="
| OpGe ->
F.fprintf f ">="
| OpGt ->
F.fprintf f ">"
| OpLe ->
F.fprintf f "<="
| OpLt ->
F.fprintf f "<"
let pp_predicate f (predicate : ToplAst.predicate) =
match predicate with
| Binop (op, l, r) ->
F.fprintf f "@[%a%a%a@]@," pp_value l pp_binop op pp_value r
| Value v ->
F.fprintf f "@[%a@]" pp_value v
let pp_condition f (condition : ToplAst.condition) =
match condition with
| [] ->
()
| predicates ->
F.fprintf f "@ @[when@ %a@]" (Pp.seq ~sep:" && " pp_predicate) predicates
let pp_assignment f (register, variable) =
F.fprintf f "@,@[%a=%a@]" pp_register register pp_variable variable
let pp_action f action =
match action with
| [] ->
()
| assignments ->
F.fprintf f "@ @[=>@ %a@]" (Pp.seq ~sep:"; " pp_assignment) assignments
let pp_arguments f arguments =
match arguments with
| None ->
()
| Some arguments ->
F.fprintf f "(%a)" (Pp.seq ~sep:"," pp_variable) arguments
let pp_raw_label f {ToplAst.pattern; arguments; condition; action} =
F.fprintf f "@[%a%a@,%a%a@]" pp_pattern pattern pp_arguments arguments pp_condition condition
pp_action action
let pp_label f label =
match label with None -> F.fprintf f "*" | Some raw_label -> pp_raw_label f raw_label
| null | https://raw.githubusercontent.com/facebook/infer/c0df05ee9e8b928ae6c1bf09b95a81a84d2401f0/infer/src/topl/ToplAstOps.ml | ocaml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
let pp_pattern f (pattern : ToplAst.label_pattern) =
match pattern with
| ArrayWritePattern ->
F.fprintf f "#ArrayWrite"
| ProcedureNamePattern procedure_name ->
F.fprintf f "\"%s\"" procedure_name
let pp_constant f (constant : ToplAst.constant) =
match constant with LiteralInt x -> F.fprintf f "%d" x
let pp_register = F.pp_print_string
let pp_variable = F.pp_print_string
let pp_fieldname = F.pp_print_string
let pp_classname = F.pp_print_string
let rec pp_value f (value : ToplAst.value) =
match value with
| Constant c ->
pp_constant f c
| Register r ->
pp_register f r
| Binding v ->
pp_variable f v
| FieldAccess {value; class_name; field_name} ->
F.fprintf f "@[%a:%a.%a@]@," pp_value value pp_classname class_name pp_fieldname field_name
let pp_binop f (binop : ToplAst.binop) =
match binop with
| LeadsTo ->
F.fprintf f "~~>"
| OpEq ->
F.fprintf f "=="
| OpNe ->
F.fprintf f "!="
| OpGe ->
F.fprintf f ">="
| OpGt ->
F.fprintf f ">"
| OpLe ->
F.fprintf f "<="
| OpLt ->
F.fprintf f "<"
let pp_predicate f (predicate : ToplAst.predicate) =
match predicate with
| Binop (op, l, r) ->
F.fprintf f "@[%a%a%a@]@," pp_value l pp_binop op pp_value r
| Value v ->
F.fprintf f "@[%a@]" pp_value v
let pp_condition f (condition : ToplAst.condition) =
match condition with
| [] ->
()
| predicates ->
F.fprintf f "@ @[when@ %a@]" (Pp.seq ~sep:" && " pp_predicate) predicates
let pp_assignment f (register, variable) =
F.fprintf f "@,@[%a=%a@]" pp_register register pp_variable variable
let pp_action f action =
match action with
| [] ->
()
| assignments ->
F.fprintf f "@ @[=>@ %a@]" (Pp.seq ~sep:"; " pp_assignment) assignments
let pp_arguments f arguments =
match arguments with
| None ->
()
| Some arguments ->
F.fprintf f "(%a)" (Pp.seq ~sep:"," pp_variable) arguments
let pp_raw_label f {ToplAst.pattern; arguments; condition; action} =
F.fprintf f "@[%a%a@,%a%a@]" pp_pattern pattern pp_arguments arguments pp_condition condition
pp_action action
let pp_label f label =
match label with None -> F.fprintf f "*" | Some raw_label -> pp_raw_label f raw_label
| |
a6a394ff96df6c7002a551e16a92d13876e3ab7a64eed1a569e6ca9362d01352 | ferd/ReVault | maestro_sup.erl | %%%-------------------------------------------------------------------
%% @doc maestro top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(maestro_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%% sup_flags() = #{strategy => strategy(), % optional
%% intensity => non_neg_integer(), % optional
period = > ( ) } % optional
%% child_spec() = #{id => child_id(), % mandatory
start = > ( ) , % mandatory
%% restart => restart(), % optional
%% shutdown => shutdown(), % optional
%% type => worker(), % optional
%% modules => modules()} % optional
init([]) ->
SupFlags = #{strategy => one_for_all,
intensity => 0,
period => 1},
ChildSpecs = [
#{id => loader,
start => {maestro_loader, start_link, []}
}
],
{ok, {SupFlags, ChildSpecs}}.
%% internal functions
| null | https://raw.githubusercontent.com/ferd/ReVault/23bc9d897a682ccaf2489740a4d38f913958f656/apps/maestro/src/maestro_sup.erl | erlang | -------------------------------------------------------------------
@doc maestro top level supervisor.
@end
-------------------------------------------------------------------
sup_flags() = #{strategy => strategy(), % optional
intensity => non_neg_integer(), % optional
optional
child_spec() = #{id => child_id(), % mandatory
mandatory
restart => restart(), % optional
shutdown => shutdown(), % optional
type => worker(), % optional
modules => modules()} % optional
internal functions |
-module(maestro_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
SupFlags = #{strategy => one_for_all,
intensity => 0,
period => 1},
ChildSpecs = [
#{id => loader,
start => {maestro_loader, start_link, []}
}
],
{ok, {SupFlags, ChildSpecs}}.
|
ba81d27d8c93b7a29758a4021a02b3021c9a8651429508ac5c7d3c56a46a9ab8 | garrigue/lablgl | test19.ml | #!/usr/bin/env lablglut
open Printf
Copyright ( c ) 1994 .
(* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. *)
(* This test makes sure damaged gets set when a window is
resized smaller. *)
let width = ref (-1);;
let height = ref (-1);;
let displayCount = ref 0;;
let onDone ~value =
if (!displayCount <> 2) then failwith "test19 damage expected\n";
fprintf stderr "PASS : test19\n" ;
exit(0);
;;
let reshape ~w ~h =
printf "window reshaped : w=%d h=%d\n" w h ;
width := w;
height := h;
;;
let display () =
if not (Glut.layerGet Glut.NORMAL_DAMAGED) then
failwith "test19 damage expected\n" ;
incr displayCount;
if (!width = -1 || !height = -1) then
failwith "test19 reshape not called\n" ;
GlClear.clear [`color];
Gl.flush();
if (!displayCount = 1) then begin
Glut.reshapeWindow (!width / 2) (!height / 2);
Glut.timerFunc 1000 onDone 0 ;
end
;;
let main () =
ignore(Glut.init Sys.argv);
ignore(Glut.createWindow("test19"));
Glut.displayFunc(display);
Glut.reshapeFunc(reshape);
Glut.mainLoop();
;;
let _ = main();;
| null | https://raw.githubusercontent.com/garrigue/lablgl/d76e4ac834b6d803e7a6c07c3b71bff0e534614f/LablGlut/examples/glut3.7/test/test19.ml | ocaml | This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain.
This test makes sure damaged gets set when a window is
resized smaller. | #!/usr/bin/env lablglut
open Printf
Copyright ( c ) 1994 .
let width = ref (-1);;
let height = ref (-1);;
let displayCount = ref 0;;
let onDone ~value =
if (!displayCount <> 2) then failwith "test19 damage expected\n";
fprintf stderr "PASS : test19\n" ;
exit(0);
;;
let reshape ~w ~h =
printf "window reshaped : w=%d h=%d\n" w h ;
width := w;
height := h;
;;
let display () =
if not (Glut.layerGet Glut.NORMAL_DAMAGED) then
failwith "test19 damage expected\n" ;
incr displayCount;
if (!width = -1 || !height = -1) then
failwith "test19 reshape not called\n" ;
GlClear.clear [`color];
Gl.flush();
if (!displayCount = 1) then begin
Glut.reshapeWindow (!width / 2) (!height / 2);
Glut.timerFunc 1000 onDone 0 ;
end
;;
let main () =
ignore(Glut.init Sys.argv);
ignore(Glut.createWindow("test19"));
Glut.displayFunc(display);
Glut.reshapeFunc(reshape);
Glut.mainLoop();
;;
let _ = main();;
|
b09df4055220ba6b745b531b9fa5644f5fa3ed4402c484f3c23bf46694ec9b6f | ocaml-gospel/gospel | exn_arity.mli | exception E of int * int
val f : int -> unit
(*@ f i
raises E _ -> false *)
{ gospel_expected|
[ 125 ] File " exn_arity.mli " , line 5 , characters 11 - 23 :
5 | raises E _ - > false
[125] File "exn_arity.mli", line 5, characters 11-23:
5 | raises E _ -> false *)
^^^^^^^^^^^^
Error: Type checking error: Exception pattern doesn't match its type.
|gospel_expected} *)
| null | https://raw.githubusercontent.com/ocaml-gospel/gospel/79841c510baeb396d9a695ae33b290899188380b/test/negative/exn_arity.mli | ocaml | @ f i
raises E _ -> false | exception E of int * int
val f : int -> unit
{ gospel_expected|
[ 125 ] File " exn_arity.mli " , line 5 , characters 11 - 23 :
5 | raises E _ - > false
[125] File "exn_arity.mli", line 5, characters 11-23:
5 | raises E _ -> false *)
^^^^^^^^^^^^
Error: Type checking error: Exception pattern doesn't match its type.
|gospel_expected} *)
|
dd4dbd354ed9397f2a9cbebd789e63506eb1668c4288c85edae8372c141cc57d | mbutterick/aoc-racket | day07.rkt | #lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[7]
@defmodule[aoc-racket/day07]
@link[""]{The puzzle}. Our @link-rp["day07-input.txt"]{input} describes an electrical circuit, with each line of the file describing the signal provided to a particular wire.
@chunk[<day07>
<day07-setup>
<day07-ops>
<day07-q1>
<day07-q2>
<day07-test>]
@isection{What's the signal on wire @tt{a}?}
The first question we should ask is — how do we model a wire? We're told that it's a thing with inputs that can be evaluated to get a value. So it sounds a lot like a function. Thus, what we'll do is convert our wire descriptions into functions, and then run the function called @racket[a].
In other languages, creating functions from text strings would be a difficult trick. But this facility is built into Racket with @iracket[define-syntax]. Essentially our program will run in two phases: in the syntax-transformation phase, we'll read in the list of wire descriptions and expand them into code that represents functions. In the second phase, the program — including our new functions, created via syntax transformation — will compile & run as usual.
The @racket[convert-input-to-wire-functions] transformer takes the input strings and first converts each into a @italic{datum} — that is, a fragment of Racket code. So an input string like this:
@racket["bn RSHIFT 2 -> bo"]
becomes a datum like this:
@racket[(wire bn RSHIFT 2 -> bo)]
Next, this transformer converts the datums into @italic{syntax}, a process that adds contextual information (for instance, the meanings of identifiers) so the code can be evaluated.
Then the @racket[wire] transformer moves the arguments around to define functions, by matching the three definition patterns that appear in the input. Thus, syntax like this:
@racket[(wire bn RSHIFT 2 -> bo)]
becomes:
@racket[(define (bo) (RSHIFT (evaluate-arg bn) (evaluate-arg 2)))]
@racket[evaluate-arg] lets us handle the fact that some of the arguments for our wires are other wires, and some arguments are numbers. Rather than detect these differences during the syntax-transformation phase, we'll just wrap every input argument with @racket[evaluate-arg], which will do the right thing in the next phase.
(@racket[wire-value-cache] is just a performance enhancement, so that wire values don't have to be computed multiple times.)
One gotcha when using syntax transformers is that identifiers introduced by a transformer can silently override others (in the same way that identifiers defined inside a @iracket[let] will override those with the same name outside the @racket[let]). For instance, one of the wires in our input is named @tt{if}. When our syntax transformer defines the @tt{if} function, it will override the usual meaning of @iracket[if]. There are plenty of elegant ways to prevent these name collisions. (The most important of which is called @italic{syntax hygiene}, and permeates the design of Racket's syntax-transformation system.) But because this is a puzzle, we'll take the cheap way out: we won't use @racket[if] elsewhere in our code, and instead use @iracket[cond].
@chunk[<day07-setup>
(require racket rackunit
(for-syntax racket/file racket/string))
(provide (all-defined-out))
(define-syntax (convert-input-to-wire-functions stx)
(syntax-case stx ()
[(_)
(let* ([input-strings (file->lines "day07-input.txt")]
[wire-strings (map (λ (str) (format "(wire ~a)" str)) input-strings)]
[wire-datums (map (compose1 read open-input-string) wire-strings)])
(datum->syntax stx `(begin ,@wire-datums)))]))
(define-syntax (wire stx)
(syntax-case stx (->)
[(_ arg -> wire-name)
#'(define (wire-name) (evaluate-arg arg))]
[(_ 16bit-op arg -> wire-name)
#'(define (wire-name) (16bit-op (evaluate-arg arg)))]
[(_ arg1 16bit-op arg2 -> wire-name)
#'(define (wire-name) (16bit-op (evaluate-arg arg1) (evaluate-arg arg2)))]
[(_ expr) #'(begin expr)]
[else #'(void)]))
(convert-input-to-wire-functions)
(define wire-value-cache (make-hash))
(define (evaluate-arg x)
(cond
[(procedure? x) (hash-ref! wire-value-cache x (thunk* (x)))]
[else x]))
]
We also need to implement our 16-bit math operations. As we saw above, our syntax transformers are generating code that looks like, for instance, @racket[(RSHIFT (evaluate-arg bn) (evaluate-arg 2))]. This code won't work unless we've defined an @racket[RSHIFT] function too.
These next definitions use @racket[define-syntax-rule] as a shortcut, which is another syntax transformer. (Thanks to @link[""]{Jay McCarthy} for the 16-bit operations.)
@chunk[<day07-ops>
(define (16bitize x)
(define 16bit-max (expt 2 16))
(define r (modulo x 16bit-max))
(cond
[(negative? r) (16bitize (+ 16bit-max r))]
[else r]))
(define-syntax-rule (define-16bit id proc)
(define id (compose1 16bitize proc)))
(define-16bit AND bitwise-and)
(define-16bit OR bitwise-ior)
(define-16bit LSHIFT arithmetic-shift)
(define-16bit RSHIFT (λ (x y) (arithmetic-shift x (- y))))
(define-16bit NOT bitwise-not)]
After that, we just evaluate wire function @racket[a] to get our answer.
@chunk[<day07-q1>
(define (q1) (a))]
@isection{What's the signal on wire @tt{a} if wire @tt{b} is overridden with @tt{a}'s original value?}
Having done the heavy lifting, this is easy. We'll redefine wire function @racket[b] to produce the new value, and then check the value of @racket[a] again.
Ordinarily, as a safety measure, Racket won't let you redefine functions. But we can circumvent this limitation by setting @iracket[compile-enforce-module-constants] to @racket[#f]. We'll also need to reset our cache, since this change will affect the other wires too.
@chunk[<day07-q2>
(compile-enforce-module-constants #f)
(define (q2)
(define first-a-val (a))
(set! b (thunk* first-a-val))
(set! wire-value-cache (make-hash))
(a))
]
@section{Testing Day 7}
@chunk[<day07-test>
(module+ test
(check-equal? (q1) 46065)
(check-equal? (q2) 14134))]
| null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/day07.rkt | racket | #lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[7]
@defmodule[aoc-racket/day07]
@link[""]{The puzzle}. Our @link-rp["day07-input.txt"]{input} describes an electrical circuit, with each line of the file describing the signal provided to a particular wire.
@chunk[<day07>
<day07-setup>
<day07-ops>
<day07-q1>
<day07-q2>
<day07-test>]
@isection{What's the signal on wire @tt{a}?}
The first question we should ask is — how do we model a wire? We're told that it's a thing with inputs that can be evaluated to get a value. So it sounds a lot like a function. Thus, what we'll do is convert our wire descriptions into functions, and then run the function called @racket[a].
In other languages, creating functions from text strings would be a difficult trick. But this facility is built into Racket with @iracket[define-syntax]. Essentially our program will run in two phases: in the syntax-transformation phase, we'll read in the list of wire descriptions and expand them into code that represents functions. In the second phase, the program — including our new functions, created via syntax transformation — will compile & run as usual.
The @racket[convert-input-to-wire-functions] transformer takes the input strings and first converts each into a @italic{datum} — that is, a fragment of Racket code. So an input string like this:
@racket["bn RSHIFT 2 -> bo"]
becomes a datum like this:
@racket[(wire bn RSHIFT 2 -> bo)]
Next, this transformer converts the datums into @italic{syntax}, a process that adds contextual information (for instance, the meanings of identifiers) so the code can be evaluated.
Then the @racket[wire] transformer moves the arguments around to define functions, by matching the three definition patterns that appear in the input. Thus, syntax like this:
@racket[(wire bn RSHIFT 2 -> bo)]
becomes:
@racket[(define (bo) (RSHIFT (evaluate-arg bn) (evaluate-arg 2)))]
@racket[evaluate-arg] lets us handle the fact that some of the arguments for our wires are other wires, and some arguments are numbers. Rather than detect these differences during the syntax-transformation phase, we'll just wrap every input argument with @racket[evaluate-arg], which will do the right thing in the next phase.
(@racket[wire-value-cache] is just a performance enhancement, so that wire values don't have to be computed multiple times.)
One gotcha when using syntax transformers is that identifiers introduced by a transformer can silently override others (in the same way that identifiers defined inside a @iracket[let] will override those with the same name outside the @racket[let]). For instance, one of the wires in our input is named @tt{if}. When our syntax transformer defines the @tt{if} function, it will override the usual meaning of @iracket[if]. There are plenty of elegant ways to prevent these name collisions. (The most important of which is called @italic{syntax hygiene}, and permeates the design of Racket's syntax-transformation system.) But because this is a puzzle, we'll take the cheap way out: we won't use @racket[if] elsewhere in our code, and instead use @iracket[cond].
@chunk[<day07-setup>
(require racket rackunit
(for-syntax racket/file racket/string))
(provide (all-defined-out))
(define-syntax (convert-input-to-wire-functions stx)
(syntax-case stx ()
[(_)
(let* ([input-strings (file->lines "day07-input.txt")]
[wire-strings (map (λ (str) (format "(wire ~a)" str)) input-strings)]
[wire-datums (map (compose1 read open-input-string) wire-strings)])
(datum->syntax stx `(begin ,@wire-datums)))]))
(define-syntax (wire stx)
(syntax-case stx (->)
[(_ arg -> wire-name)
#'(define (wire-name) (evaluate-arg arg))]
[(_ 16bit-op arg -> wire-name)
#'(define (wire-name) (16bit-op (evaluate-arg arg)))]
[(_ arg1 16bit-op arg2 -> wire-name)
#'(define (wire-name) (16bit-op (evaluate-arg arg1) (evaluate-arg arg2)))]
[(_ expr) #'(begin expr)]
[else #'(void)]))
(convert-input-to-wire-functions)
(define wire-value-cache (make-hash))
(define (evaluate-arg x)
(cond
[(procedure? x) (hash-ref! wire-value-cache x (thunk* (x)))]
[else x]))
]
We also need to implement our 16-bit math operations. As we saw above, our syntax transformers are generating code that looks like, for instance, @racket[(RSHIFT (evaluate-arg bn) (evaluate-arg 2))]. This code won't work unless we've defined an @racket[RSHIFT] function too.
These next definitions use @racket[define-syntax-rule] as a shortcut, which is another syntax transformer. (Thanks to @link[""]{Jay McCarthy} for the 16-bit operations.)
@chunk[<day07-ops>
(define (16bitize x)
(define 16bit-max (expt 2 16))
(define r (modulo x 16bit-max))
(cond
[(negative? r) (16bitize (+ 16bit-max r))]
[else r]))
(define-syntax-rule (define-16bit id proc)
(define id (compose1 16bitize proc)))
(define-16bit AND bitwise-and)
(define-16bit OR bitwise-ior)
(define-16bit LSHIFT arithmetic-shift)
(define-16bit RSHIFT (λ (x y) (arithmetic-shift x (- y))))
(define-16bit NOT bitwise-not)]
After that, we just evaluate wire function @racket[a] to get our answer.
@chunk[<day07-q1>
(define (q1) (a))]
@isection{What's the signal on wire @tt{a} if wire @tt{b} is overridden with @tt{a}'s original value?}
Having done the heavy lifting, this is easy. We'll redefine wire function @racket[b] to produce the new value, and then check the value of @racket[a] again.
Ordinarily, as a safety measure, Racket won't let you redefine functions. But we can circumvent this limitation by setting @iracket[compile-enforce-module-constants] to @racket[#f]. We'll also need to reset our cache, since this change will affect the other wires too.
@chunk[<day07-q2>
(compile-enforce-module-constants #f)
(define (q2)
(define first-a-val (a))
(set! b (thunk* first-a-val))
(set! wire-value-cache (make-hash))
(a))
]
@section{Testing Day 7}
@chunk[<day07-test>
(module+ test
(check-equal? (q1) 46065)
(check-equal? (q2) 14134))]
| |
ca86b183292ae8a6fa522318b25a3c6c8f3d58d60a9da030e7dbf790a22e041d | racket/pkg-build | install-step.rkt | #lang racket/base
(require racket/format
racket/runtime-path
racket/file
file/untgz
remote-shell/vbox
remote-shell/docker
remote-shell/ssh
pkg/lib
net/url
"config.rkt"
"vm.rkt"
"status.rkt")
(provide install-step)
(define-runtime-path pkg-list-rkt "pkg-list.rkt")
(define-runtime-path pkg-adds-rkt "pkg-adds.rkt")
(define (install-step vms
config
installer-dir
installer-name
archive-dir
extra-packages
work-dir
install-doc-list-file
machine-independent?)
(define (do-install ssh scp-to rt vm
#:filesystem-catalog? [filesystem-catalog? #f]
#:pre-pkg-install [pre-pkg-install void])
(define there-dir (vm-dir vm))
(status "Preparing directory ~a\n" there-dir)
(ssh rt "rm -rf " (~a (q there-dir) "/*"))
(ssh rt "mkdir -p " (q there-dir))
(ssh rt "mkdir -p " (q (~a there-dir "/user")))
(ssh rt "mkdir -p " (q (~a there-dir "/built")))
(scp-to rt (build-path installer-dir installer-name) there-dir)
(ssh rt "cd " (q there-dir) " && " " sh " (q installer-name) " --in-place --dest ./racket")
;; VM-side helper modules:
(scp-to rt pkg-adds-rkt (~a there-dir "/pkg-adds.rkt"))
(scp-to rt pkg-list-rkt (~a there-dir "/pkg-list.rkt"))
(define MCR (mcr vm machine-independent?))
(when machine-independent?
(status "Bulding machine-dependent bytecode at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco setup --recompile-only"))
(status "Setting catalogs at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg config -i --set catalogs "
(cond
[filesystem-catalog?
(~a " file://" (q there-dir) "/catalogs/built/catalog"
" file://" (q there-dir) "/catalogs/archive/catalog")]
[else
(~a " :" (~a (config-server-port config)) "/built/catalog/"
" :" (~a (config-server-port config)) "/archive/catalog/")]))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg config -i --set trash-max-packages 0")
(unless (null? extra-packages)
(pre-pkg-install)
(status "Extra package installs at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg install -i --recompile-only --auto"
" " (apply ~a #:separator " " extra-packages))))
(define (extract-installed rt vm)
(define there-dir (vm-dir vm))
(define MCR (mcr vm machine-independent?))
(status "Getting installed packages\n")
(ssh rt (cd-racket vm)
" && bin/racket" MCR " ../pkg-list.rkt > ../pkg-list.rktd")
(scp rt (at-remote rt (~a there-dir "/pkg-list.rktd"))
(build-path work-dir "install-list.rktd"))
(status "Stashing installation docs\n")
(ssh rt (cd-racket vm)
" && bin/racket" MCR " ../pkg-adds.rkt --all > ../pkg-adds.rktd")
(ssh rt (cd-racket vm)
" && tar zcf ../install-doc.tgz doc")
(scp rt (at-remote rt (~a there-dir "/pkg-adds.rktd"))
(build-path work-dir "install-adds.rktd"))
(scp rt (at-remote rt (~a there-dir "/install-doc.tgz"))
(build-path work-dir "install-doc.tgz")))
(define (install vm
#:extract-installed? [extract-installed? #f])
(cond
VirtualBox mode
[(vm-vbox? vm)
(status "Starting VM ~a\n" (vm-name vm))
(stop-vbox-vm (vm-name vm))
(restore-vbox-snapshot (vm-name vm) (vm-vbox-init-snapshot vm))
(dynamic-wind
(lambda () (start-vbox-vm (vm-name vm)))
(lambda ()
(define rt (vm-remote vm config machine-independent?))
(define (scp-to rt src dest)
(scp rt src (at-remote rt dest)))
(make-sure-vm-is-ready vm rt)
(do-install ssh scp-to rt vm)
(when extract-installed?
(extract-installed rt vm)))
(lambda ()
(stop-vbox-vm (vm-name vm))))
(status "Taking installation snapshopt\n")
(when (exists-vbox-snapshot? (vm-name vm) (vm-vbox-installed-snapshot vm))
(delete-vbox-snapshot (vm-name vm) (vm-vbox-installed-snapshot vm)))
(take-vbox-snapshot (vm-name vm) (vm-vbox-installed-snapshot vm))]
;; Docker mode
[(vm-docker? vm)
(status "Building VM ~a\n" (vm-name vm))
(when (docker-image-id #:name (vm-name vm))
(when (docker-running? #:name (vm-name vm))
(docker-stop #:name (vm-name vm)))
(when (docker-id #:name (vm-name vm))
(docker-remove #:name (vm-name vm)))
(docker-image-remove #:name (vm-name vm)))
(define build-dir (make-temporary-file "pkg-build-~a" 'directory))
(unless (null? extra-packages)
(pkg-catalog-archive #:fast-file-copy? #t
#:relative-sources? #t
#:include extra-packages
#:include-deps? #t
(build-path build-dir "archive")
(list (url->string (path->url (build-path archive-dir "catalog"))))))
(dynamic-wind
void
(lambda ()
(call-with-output-file*
(build-path build-dir "Dockerfile")
(lambda (o)
(fprintf o "FROM ~a\n" (vm-docker-from-image vm))
(for ([p (in-list (vm-env vm))])
(fprintf o "ENV ~a ~a\n" (car p) (cdr p)))
(define (build-ssh rt . strs)
(fprintf o "RUN ")
(for ([str (in-list strs)])
(fprintf o "~a" str))
(newline o))
(define (build-scp-to rt here there)
(define-values (base name dir?) (split-path here))
(copy-file here (build-path build-dir name))
(fprintf o "COPY ~a ~a\n" name there))
(do-install build-ssh build-scp-to 'dummy-rt vm
#:filesystem-catalog? #t
#:pre-pkg-install
(lambda ()
(fprintf o "COPY archive ~a/catalogs/archive\n" (q (vm-dir vm)))))
(unless (null? extra-packages)
(fprintf o "RUN rm -r ~a/catalogs/archive" (q (vm-dir vm))))))
(docker-build #:content build-dir
#:name (vm-name vm))
(status "Container built as ~a\n" (docker-image-id #:name (vm-name vm))))
(lambda ()
(delete-directory/files build-dir)))
(when extract-installed?
(vm-reset vm config)
(dynamic-wind
(lambda ()
(vm-start vm #:max-vms 1))
(lambda ()
(extract-installed (vm-remote vm config machine-independent?) vm))
(lambda ()
(vm-stop vm))))]))
(define (check-and-install vm #:extract-installed? [extract-installed? #f])
(define uuids (with-handlers ([exn:fail? (lambda (exn)
(hash))])
(define ht
(call-with-input-file*
(build-path work-dir "install-uuids.rktd")
read))
(if (hash? ht)
ht
(hash))))
(define key (list (vm-name vm) (vm-config-key vm)))
(define uuid (hash-ref uuids key #f))
(define (get-vm-id)
(cond
[(vm-vbox? vm)
(get-vbox-snapshot-uuid (vm-name vm) (vm-vbox-installed-snapshot vm))]
[(vm-docker? vm)
(docker-image-id #:name (vm-name vm))]))
(cond
[(and uuid (equal? uuid (get-vm-id)))
(status "VM ~a is up-to-date~a\n" (vm-name vm)
(if (vm-vbox? vm)
(format " for ~a" (vm-vbox-installed-snapshot vm))
""))]
[else
(install vm #:extract-installed? extract-installed?)
(define uuid (get-vm-id))
(call-with-output-file*
(build-path work-dir "install-uuids.rktd")
#:exists 'truncate
(lambda (o)
(writeln (hash-set uuids key uuid) o)))]))
(for ([vm (in-list vms)]
[i (in-naturals)])
(check-and-install vm #:extract-installed? (zero? i))
(when (vm-minimal-variant vm)
(check-and-install (vm-minimal-variant vm))))
(when install-doc-list-file
(call-with-output-file*
(build-path work-dir install-doc-list-file)
#:exists 'truncate
(lambda (o)
(untgz (build-path work-dir "install-doc.tgz")
#:filter (lambda (p . _)
(displayln p o)
#f))))))
| null | https://raw.githubusercontent.com/racket/pkg-build/31fea3651b501e2ad333cf6133527290abd2eed1/private/install-step.rkt | racket | VM-side helper modules:
Docker mode | #lang racket/base
(require racket/format
racket/runtime-path
racket/file
file/untgz
remote-shell/vbox
remote-shell/docker
remote-shell/ssh
pkg/lib
net/url
"config.rkt"
"vm.rkt"
"status.rkt")
(provide install-step)
(define-runtime-path pkg-list-rkt "pkg-list.rkt")
(define-runtime-path pkg-adds-rkt "pkg-adds.rkt")
(define (install-step vms
config
installer-dir
installer-name
archive-dir
extra-packages
work-dir
install-doc-list-file
machine-independent?)
(define (do-install ssh scp-to rt vm
#:filesystem-catalog? [filesystem-catalog? #f]
#:pre-pkg-install [pre-pkg-install void])
(define there-dir (vm-dir vm))
(status "Preparing directory ~a\n" there-dir)
(ssh rt "rm -rf " (~a (q there-dir) "/*"))
(ssh rt "mkdir -p " (q there-dir))
(ssh rt "mkdir -p " (q (~a there-dir "/user")))
(ssh rt "mkdir -p " (q (~a there-dir "/built")))
(scp-to rt (build-path installer-dir installer-name) there-dir)
(ssh rt "cd " (q there-dir) " && " " sh " (q installer-name) " --in-place --dest ./racket")
(scp-to rt pkg-adds-rkt (~a there-dir "/pkg-adds.rkt"))
(scp-to rt pkg-list-rkt (~a there-dir "/pkg-list.rkt"))
(define MCR (mcr vm machine-independent?))
(when machine-independent?
(status "Bulding machine-dependent bytecode at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco setup --recompile-only"))
(status "Setting catalogs at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg config -i --set catalogs "
(cond
[filesystem-catalog?
(~a " file://" (q there-dir) "/catalogs/built/catalog"
" file://" (q there-dir) "/catalogs/archive/catalog")]
[else
(~a " :" (~a (config-server-port config)) "/built/catalog/"
" :" (~a (config-server-port config)) "/archive/catalog/")]))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg config -i --set trash-max-packages 0")
(unless (null? extra-packages)
(pre-pkg-install)
(status "Extra package installs at ~a\n" (vm-name vm))
(ssh rt (cd-racket vm)
" && bin/racket" MCR " -l- raco pkg install -i --recompile-only --auto"
" " (apply ~a #:separator " " extra-packages))))
(define (extract-installed rt vm)
(define there-dir (vm-dir vm))
(define MCR (mcr vm machine-independent?))
(status "Getting installed packages\n")
(ssh rt (cd-racket vm)
" && bin/racket" MCR " ../pkg-list.rkt > ../pkg-list.rktd")
(scp rt (at-remote rt (~a there-dir "/pkg-list.rktd"))
(build-path work-dir "install-list.rktd"))
(status "Stashing installation docs\n")
(ssh rt (cd-racket vm)
" && bin/racket" MCR " ../pkg-adds.rkt --all > ../pkg-adds.rktd")
(ssh rt (cd-racket vm)
" && tar zcf ../install-doc.tgz doc")
(scp rt (at-remote rt (~a there-dir "/pkg-adds.rktd"))
(build-path work-dir "install-adds.rktd"))
(scp rt (at-remote rt (~a there-dir "/install-doc.tgz"))
(build-path work-dir "install-doc.tgz")))
(define (install vm
#:extract-installed? [extract-installed? #f])
(cond
VirtualBox mode
[(vm-vbox? vm)
(status "Starting VM ~a\n" (vm-name vm))
(stop-vbox-vm (vm-name vm))
(restore-vbox-snapshot (vm-name vm) (vm-vbox-init-snapshot vm))
(dynamic-wind
(lambda () (start-vbox-vm (vm-name vm)))
(lambda ()
(define rt (vm-remote vm config machine-independent?))
(define (scp-to rt src dest)
(scp rt src (at-remote rt dest)))
(make-sure-vm-is-ready vm rt)
(do-install ssh scp-to rt vm)
(when extract-installed?
(extract-installed rt vm)))
(lambda ()
(stop-vbox-vm (vm-name vm))))
(status "Taking installation snapshopt\n")
(when (exists-vbox-snapshot? (vm-name vm) (vm-vbox-installed-snapshot vm))
(delete-vbox-snapshot (vm-name vm) (vm-vbox-installed-snapshot vm)))
(take-vbox-snapshot (vm-name vm) (vm-vbox-installed-snapshot vm))]
[(vm-docker? vm)
(status "Building VM ~a\n" (vm-name vm))
(when (docker-image-id #:name (vm-name vm))
(when (docker-running? #:name (vm-name vm))
(docker-stop #:name (vm-name vm)))
(when (docker-id #:name (vm-name vm))
(docker-remove #:name (vm-name vm)))
(docker-image-remove #:name (vm-name vm)))
(define build-dir (make-temporary-file "pkg-build-~a" 'directory))
(unless (null? extra-packages)
(pkg-catalog-archive #:fast-file-copy? #t
#:relative-sources? #t
#:include extra-packages
#:include-deps? #t
(build-path build-dir "archive")
(list (url->string (path->url (build-path archive-dir "catalog"))))))
(dynamic-wind
void
(lambda ()
(call-with-output-file*
(build-path build-dir "Dockerfile")
(lambda (o)
(fprintf o "FROM ~a\n" (vm-docker-from-image vm))
(for ([p (in-list (vm-env vm))])
(fprintf o "ENV ~a ~a\n" (car p) (cdr p)))
(define (build-ssh rt . strs)
(fprintf o "RUN ")
(for ([str (in-list strs)])
(fprintf o "~a" str))
(newline o))
(define (build-scp-to rt here there)
(define-values (base name dir?) (split-path here))
(copy-file here (build-path build-dir name))
(fprintf o "COPY ~a ~a\n" name there))
(do-install build-ssh build-scp-to 'dummy-rt vm
#:filesystem-catalog? #t
#:pre-pkg-install
(lambda ()
(fprintf o "COPY archive ~a/catalogs/archive\n" (q (vm-dir vm)))))
(unless (null? extra-packages)
(fprintf o "RUN rm -r ~a/catalogs/archive" (q (vm-dir vm))))))
(docker-build #:content build-dir
#:name (vm-name vm))
(status "Container built as ~a\n" (docker-image-id #:name (vm-name vm))))
(lambda ()
(delete-directory/files build-dir)))
(when extract-installed?
(vm-reset vm config)
(dynamic-wind
(lambda ()
(vm-start vm #:max-vms 1))
(lambda ()
(extract-installed (vm-remote vm config machine-independent?) vm))
(lambda ()
(vm-stop vm))))]))
(define (check-and-install vm #:extract-installed? [extract-installed? #f])
(define uuids (with-handlers ([exn:fail? (lambda (exn)
(hash))])
(define ht
(call-with-input-file*
(build-path work-dir "install-uuids.rktd")
read))
(if (hash? ht)
ht
(hash))))
(define key (list (vm-name vm) (vm-config-key vm)))
(define uuid (hash-ref uuids key #f))
(define (get-vm-id)
(cond
[(vm-vbox? vm)
(get-vbox-snapshot-uuid (vm-name vm) (vm-vbox-installed-snapshot vm))]
[(vm-docker? vm)
(docker-image-id #:name (vm-name vm))]))
(cond
[(and uuid (equal? uuid (get-vm-id)))
(status "VM ~a is up-to-date~a\n" (vm-name vm)
(if (vm-vbox? vm)
(format " for ~a" (vm-vbox-installed-snapshot vm))
""))]
[else
(install vm #:extract-installed? extract-installed?)
(define uuid (get-vm-id))
(call-with-output-file*
(build-path work-dir "install-uuids.rktd")
#:exists 'truncate
(lambda (o)
(writeln (hash-set uuids key uuid) o)))]))
(for ([vm (in-list vms)]
[i (in-naturals)])
(check-and-install vm #:extract-installed? (zero? i))
(when (vm-minimal-variant vm)
(check-and-install (vm-minimal-variant vm))))
(when install-doc-list-file
(call-with-output-file*
(build-path work-dir install-doc-list-file)
#:exists 'truncate
(lambda (o)
(untgz (build-path work-dir "install-doc.tgz")
#:filter (lambda (p . _)
(displayln p o)
#f))))))
|
2bc8b1c2a6c43596ab1c606737ff4bdfd294b15ef99c32ac15a72e909daf4239 | chr15m/slingcode | slingcode-site-bootleg.clj | (let [template (html "../build/index.html")
template (enlive/at template [:head] (enlive/append (html "slingcode-social.html" :hickory-seq)))
template (enlive/at template [:link] (fn [t] (update-in t [:attrs :href] (fn [a] (str "public/" a)))))
template (enlive/at template [:link.rm] nil)
template (enlive/at template [:script] (enlive/substitute nil))
static (html "slingcode-static.html")
static (enlive/at static [:section#about] (enlive/content (markdown (str "../" (last *command-line-args*)) :hickory-seq)))
static (enlive/at static [:p#gh-logo] (enlive/substitute nil))
static (enlive/at static [:section#about] (enlive/prepend (convert-to [:img {:src "public/img/computers-in-our-lives.jpg"}] :hickory-seq)))
static (enlive/at static [:p#youtube] (enlive/substitute (html "slingcode-embed.html" :hickory-seq)))
static ( enlive / at static [: section#about ] ( enlive / prepend ( convert - to [: div [: p.title " personal computing platform . " ] ] : hickory - seq ) ) )
]
(enlive/at template [:body] (enlive/content static)))
| null | https://raw.githubusercontent.com/chr15m/slingcode/aef42bf097aef82f2eda297f4fe63ddd2763ff83/src/slingcode-site-bootleg.clj | clojure | (let [template (html "../build/index.html")
template (enlive/at template [:head] (enlive/append (html "slingcode-social.html" :hickory-seq)))
template (enlive/at template [:link] (fn [t] (update-in t [:attrs :href] (fn [a] (str "public/" a)))))
template (enlive/at template [:link.rm] nil)
template (enlive/at template [:script] (enlive/substitute nil))
static (html "slingcode-static.html")
static (enlive/at static [:section#about] (enlive/content (markdown (str "../" (last *command-line-args*)) :hickory-seq)))
static (enlive/at static [:p#gh-logo] (enlive/substitute nil))
static (enlive/at static [:section#about] (enlive/prepend (convert-to [:img {:src "public/img/computers-in-our-lives.jpg"}] :hickory-seq)))
static (enlive/at static [:p#youtube] (enlive/substitute (html "slingcode-embed.html" :hickory-seq)))
static ( enlive / at static [: section#about ] ( enlive / prepend ( convert - to [: div [: p.title " personal computing platform . " ] ] : hickory - seq ) ) )
]
(enlive/at template [:body] (enlive/content static)))
| |
84026ed714b9cf3f83e5f206e85374680047937da99554be50f151b26f275833 | blindglobe/clocc | cil.lisp | ;;;; cil.lsp: Chess In Lisp foundation programming toolkit
Revised : 1997.06.08
Send comments to : ( )
This source file is the foundation of the Chess In Lisp programming
;; toolkit. It contains the core processing functions needed to perform
;; research in the chess domain using Lisp.
;; Global optimization options
(declaim
(optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)))
;;; --- Constants -----------------------------------------------
;; Colors
(defconstant c-limit 4)
(defconstant rc-limit 2)
(defconstant c-nil -1)
(defconstant c-w 0) ; white
(defconstant c-b 1) ; black
(defconstant c-v 2) ; vacant
(defconstant c-x 3) ; extra
(defparameter c-strings
(make-array c-limit
:initial-contents '("w" "b" " " "?")))
(defparameter color-strings
(make-array rc-limit
:initial-contents '("white" "black")))
(defparameter player-strings
(make-array rc-limit
:initial-contents '("White" "Black")))
(defparameter invc-v
(make-array rc-limit
:element-type 'fixnum
:initial-contents `(,c-b ,c-w)))
;; Pieces
(defconstant p-limit 8)
(defconstant rp-limit 6)
(defconstant p-nil -1)
(defconstant p-p 0) ; pawn
(defconstant p-n 1) ; knight
(defconstant p-b 2) ; bishop
(defconstant p-r 3) ; rook
(defconstant p-q 4) ; queen
(defconstant p-k 5) ; king
(defconstant p-v 6) ; vacant
(defconstant p-x 7) ; extra
(defparameter p-strings
(make-array p-limit
:initial-contents '("P" "N" "B" "R" "Q" "K" " " "?")))
(defparameter piece-strings
(make-array rp-limit
:initial-contents
'("pawn" "knight" "bishop" "rook" "queen" "king")))
(defparameter lcp-strings
(make-array p-limit
:initial-contents '("p" "n" "b" "r" "q" "k" " " "?")))
Color - pieces
(defconstant cp-limit 16)
(defconstant rcp-limit 12)
(defconstant cp-nil -1)
(defconstant cp-wp 0) ; white
(defconstant cp-wn 1) ; white
(defconstant cp-wb 2) ; white
(defconstant cp-wr 3) ; white
(defconstant cp-wq 4) ; white
(defconstant cp-wk 5) ; white
(defconstant cp-bp 6) ; black
(defconstant cp-bn 7) ; black
(defconstant cp-bb 8) ; black
(defconstant cp-br 9) ; black
(defconstant cp-bq 10) ; black
(defconstant cp-bk 11) ; black
(defconstant cp-v0 12) ; vacant
(defconstant cp-x0 13) ; extra
(defconstant cp-x1 14) ; extra extra
(defconstant cp-x2 15) ; extra extra extra
(defparameter cp-strings
(make-array cp-limit
:initial-contents
'("wP" "wN" "wB" "wR" "wQ" "wK"
"bP" "bN" "bB" "bR" "bQ" "bK"
" " "??" "?1" "?2")))
(defparameter mapv-c
(make-array cp-limit
:element-type 'fixnum
:initial-contents
`(,c-w ,c-w ,c-w ,c-w ,c-w ,c-w
,c-b ,c-b ,c-b ,c-b ,c-b ,c-b
,c-v ,c-x ,c-x ,c-x)))
(defparameter mapv-p
(make-array cp-limit
:element-type 'fixnum
:initial-contents
`(,p-p ,p-n ,p-b ,p-r ,p-q ,p-k
,p-p ,p-n ,p-b ,p-r ,p-q ,p-k
,p-v ,p-x ,p-x ,p-x)))
(defparameter mapv-cp
(make-array `(,rc-limit ,rp-limit)
:element-type 'fixnum
:initial-contents
`((,cp-wp ,cp-wn ,cp-wb ,cp-wr ,cp-wq ,cp-wk)
(,cp-bp ,cp-bn ,cp-bb ,cp-br ,cp-bq ,cp-bk))))
(defparameter sweeper-cp
(make-array rcp-limit
:element-type 'fixnum
:initial-contents
'(0 0 1 1 1 0 0 0 1 1 1 0)))
;; Edge limit
(defparameter edge-limit 8)
;; Ranks
(defparameter rank-limit edge-limit)
(defconstant rank-nil -1)
(defconstant rank-1 0) ; first rank
second rank
third rank
fourth rank
fifth rank
sixth rank
seventh rank
(defconstant rank-8 7) ; eighth rank
(defparameter rank-strings
(make-array rank-limit
:initial-contents '("1" "2" "3" "4" "5" "6" "7" "8")))
;; Files
(defparameter file-limit edge-limit)
(defconstant file-nil -1)
(defconstant file-a 0) ; queen rook file
(defconstant file-b 1) ; queen knight file
(defconstant file-c 2) ; queen bishop file
(defconstant file-d 3) ; queen file
(defconstant file-e 4) ; king file
(defconstant file-f 5) ; king bishop file
(defconstant file-g 6) ; king knight file
king rook file
(defparameter file-strings
(make-array file-limit
:initial-contents '("a" "b" "c" "d" "e" "f" "g" "h")))
;; Squares
(defparameter sq-limit (* rank-limit file-limit))
(defconstant sq-nil -1)
(defparameter sq-a1 (+ file-a (* rank-1 file-limit)))
(defparameter sq-b1 (+ file-b (* rank-1 file-limit)))
(defparameter sq-c1 (+ file-c (* rank-1 file-limit)))
(defparameter sq-d1 (+ file-d (* rank-1 file-limit)))
(defparameter sq-e1 (+ file-e (* rank-1 file-limit)))
(defparameter sq-f1 (+ file-f (* rank-1 file-limit)))
(defparameter sq-g1 (+ file-g (* rank-1 file-limit)))
(defparameter sq-h1 (+ file-h (* rank-1 file-limit)))
(defparameter sq-a2 (+ file-a (* rank-2 file-limit)))
(defparameter sq-b2 (+ file-b (* rank-2 file-limit)))
(defparameter sq-c2 (+ file-c (* rank-2 file-limit)))
(defparameter sq-d2 (+ file-d (* rank-2 file-limit)))
(defparameter sq-e2 (+ file-e (* rank-2 file-limit)))
(defparameter sq-f2 (+ file-f (* rank-2 file-limit)))
(defparameter sq-g2 (+ file-g (* rank-2 file-limit)))
(defparameter sq-h2 (+ file-h (* rank-2 file-limit)))
(defparameter sq-a3 (+ file-a (* rank-3 file-limit)))
(defparameter sq-b3 (+ file-b (* rank-3 file-limit)))
(defparameter sq-c3 (+ file-c (* rank-3 file-limit)))
(defparameter sq-d3 (+ file-d (* rank-3 file-limit)))
(defparameter sq-e3 (+ file-e (* rank-3 file-limit)))
(defparameter sq-f3 (+ file-f (* rank-3 file-limit)))
(defparameter sq-g3 (+ file-g (* rank-3 file-limit)))
(defparameter sq-h3 (+ file-h (* rank-3 file-limit)))
(defparameter sq-a4 (+ file-a (* rank-4 file-limit)))
(defparameter sq-b4 (+ file-b (* rank-4 file-limit)))
(defparameter sq-c4 (+ file-c (* rank-4 file-limit)))
(defparameter sq-d4 (+ file-d (* rank-4 file-limit)))
(defparameter sq-e4 (+ file-e (* rank-4 file-limit)))
(defparameter sq-f4 (+ file-f (* rank-4 file-limit)))
(defparameter sq-g4 (+ file-g (* rank-4 file-limit)))
(defparameter sq-h4 (+ file-h (* rank-4 file-limit)))
(defparameter sq-a5 (+ file-a (* rank-5 file-limit)))
(defparameter sq-b5 (+ file-b (* rank-5 file-limit)))
(defparameter sq-c5 (+ file-c (* rank-5 file-limit)))
(defparameter sq-d5 (+ file-d (* rank-5 file-limit)))
(defparameter sq-e5 (+ file-e (* rank-5 file-limit)))
(defparameter sq-f5 (+ file-f (* rank-5 file-limit)))
(defparameter sq-g5 (+ file-g (* rank-5 file-limit)))
(defparameter sq-h5 (+ file-h (* rank-5 file-limit)))
(defparameter sq-a6 (+ file-a (* rank-6 file-limit)))
(defparameter sq-b6 (+ file-b (* rank-6 file-limit)))
(defparameter sq-c6 (+ file-c (* rank-6 file-limit)))
(defparameter sq-d6 (+ file-d (* rank-6 file-limit)))
(defparameter sq-e6 (+ file-e (* rank-6 file-limit)))
(defparameter sq-f6 (+ file-f (* rank-6 file-limit)))
(defparameter sq-g6 (+ file-g (* rank-6 file-limit)))
(defparameter sq-h6 (+ file-h (* rank-6 file-limit)))
(defparameter sq-a7 (+ file-a (* rank-7 file-limit)))
(defparameter sq-b7 (+ file-b (* rank-7 file-limit)))
(defparameter sq-c7 (+ file-c (* rank-7 file-limit)))
(defparameter sq-d7 (+ file-d (* rank-7 file-limit)))
(defparameter sq-e7 (+ file-e (* rank-7 file-limit)))
(defparameter sq-f7 (+ file-f (* rank-7 file-limit)))
(defparameter sq-g7 (+ file-g (* rank-7 file-limit)))
(defparameter sq-h7 (+ file-h (* rank-7 file-limit)))
(defparameter sq-a8 (+ file-a (* rank-8 file-limit)))
(defparameter sq-b8 (+ file-b (* rank-8 file-limit)))
(defparameter sq-c8 (+ file-c (* rank-8 file-limit)))
(defparameter sq-d8 (+ file-d (* rank-8 file-limit)))
(defparameter sq-e8 (+ file-e (* rank-8 file-limit)))
(defparameter sq-f8 (+ file-f (* rank-8 file-limit)))
(defparameter sq-g8 (+ file-g (* rank-8 file-limit)))
(defparameter sq-h8 (+ file-h (* rank-8 file-limit)))
(defparameter sq-strings
(make-array sq-limit
:initial-contents
'(
"a1" "b1" "c1" "d1" "e1" "f1" "g1" "h1"
"a2" "b2" "c2" "d2" "e2" "f2" "g2" "h2"
"a3" "b3" "c3" "d3" "e3" "f3" "g3" "h3"
"a4" "b4" "c4" "d4" "e4" "f4" "g4" "h4"
"a5" "b5" "c5" "d5" "e5" "f5" "g5" "h5"
"a6" "b6" "c6" "d6" "e6" "f6" "g6" "h6"
"a7" "b7" "c7" "d7" "e7" "f7" "g7" "h7"
"a8" "b8" "c8" "d8" "e8" "f8" "g8" "h8")))
Directions : 4 orthogonal , 4 diagonal , 8 knight
(defconstant dx-limit 16)
(defconstant rdx-limit 8)
(defconstant dx-nil -1)
(defconstant dx-0 0) ; east
(defconstant dx-1 1) ; north
(defconstant dx-2 2) ; west
(defconstant dx-3 3) ; south
(defconstant dx-4 4) ; northeast
(defconstant dx-5 5) ; northwest
(defconstant dx-6 6) ; southwest
(defconstant dx-7 7) ; southeast
(defconstant dx-8 8) ; east by northeast
(defconstant dx-9 9) ; north by northeast
(defconstant dx-a 10) ; north by northwest
(defconstant dx-b 11) ; west by northwest
(defconstant dx-c 12) ; west by southwest
(defconstant dx-d 13) ; south by southwest
(defconstant dx-e 14) ; south by southeast
(defconstant dx-f 15) ; east by southeast
;; Directional rank deltas
(defconstant dr-0 0)
(defconstant dr-1 1)
(defconstant dr-2 0)
(defconstant dr-3 -1)
(defconstant dr-4 1)
(defconstant dr-5 1)
(defconstant dr-6 -1)
(defconstant dr-7 -1)
(defconstant dr-8 1)
(defconstant dr-9 2)
(defconstant dr-a 2)
(defconstant dr-b 1)
(defconstant dr-c -1)
(defconstant dr-d -2)
(defconstant dr-e -2)
(defconstant dr-f -1)
(defparameter mapv-dr
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,dr-0 ,dr-1 ,dr-2 ,dr-3 ,dr-4 ,dr-5 ,dr-6 ,dr-7
,dr-8 ,dr-9 ,dr-a ,dr-b ,dr-c ,dr-d ,dr-e ,dr-f)))
;; Directional file deltas
(defconstant df-0 1)
(defconstant df-1 0)
(defconstant df-2 -1)
(defconstant df-3 0)
(defconstant df-4 1)
(defconstant df-5 -1)
(defconstant df-6 -1)
(defconstant df-7 1)
(defconstant df-8 2)
(defconstant df-9 1)
(defconstant df-a -1)
(defconstant df-b -2)
(defconstant df-c -2)
(defconstant df-d -1)
(defconstant df-e 1)
(defconstant df-f 2)
(defparameter mapv-df
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,df-0 ,df-1 ,df-2 ,df-3 ,df-4 ,df-5 ,df-6 ,df-7
,df-8 ,df-9 ,df-a ,df-b ,df-c ,df-d ,df-e ,df-f)))
;; Directional offsets
(defparameter dv-0 (+ df-0 (* rank-limit dr-0)))
(defparameter dv-1 (+ df-1 (* rank-limit dr-1)))
(defparameter dv-2 (+ df-2 (* rank-limit dr-2)))
(defparameter dv-3 (+ df-3 (* rank-limit dr-3)))
(defparameter dv-4 (+ df-4 (* rank-limit dr-4)))
(defparameter dv-5 (+ df-5 (* rank-limit dr-5)))
(defparameter dv-6 (+ df-6 (* rank-limit dr-6)))
(defparameter dv-7 (+ df-7 (* rank-limit dr-7)))
(defparameter dv-8 (+ df-8 (* rank-limit dr-8)))
(defparameter dv-9 (+ df-9 (* rank-limit dr-9)))
(defparameter dv-a (+ df-a (* rank-limit dr-a)))
(defparameter dv-b (+ df-b (* rank-limit dr-b)))
(defparameter dv-c (+ df-c (* rank-limit dr-c)))
(defparameter dv-d (+ df-d (* rank-limit dr-d)))
(defparameter dv-e (+ df-e (* rank-limit dr-e)))
(defparameter dv-f (+ df-f (* rank-limit dr-f)))
(defparameter mapv-dv
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,dv-0 ,dv-1 ,dv-2 ,dv-3 ,dv-4 ,dv-5 ,dv-6 ,dv-7
,dv-8 ,dv-9 ,dv-a ,dv-b ,dv-c ,dv-d ,dv-e ,dv-f)))
;; Flanks
(defconstant flank-limit 2)
(defconstant flank-nil -1)
(defconstant flank-k 0) ; kingside
(defconstant flank-q 1) ; queenside
Flank castling strings
(defparameter fc-strings
(make-array flank-limit
:initial-contents '("O-O" "O-O-O")))
;; Castling status bit positions
white KS castling
white QS castling
black KS castling
black QS castling
Castling bitfields
(defconstant cflg-wk (ash 1 csbp-wk))
(defconstant cflg-wq (ash 1 csbp-wq))
(defconstant cflg-bk (ash 1 csbp-bk))
(defconstant cflg-bq (ash 1 csbp-bq))
;; Special case move indications
(defconstant scmv-limit 8)
(defconstant scmv-nil -1)
(defconstant scmv-reg 0) ; regular
(defconstant scmv-cks 1) ; castle kingside
(defconstant scmv-cqs 2) ; castle queenside
(defconstant scmv-epc 3) ; en passant capture
(defconstant scmv-ppn 4) ; pawn promotes to a knight
(defconstant scmv-ppb 5) ; pawn promotes to a bishop
(defconstant scmv-ppr 6) ; pawn promotes to a rook
(defconstant scmv-ppq 7) ; pawn promotes to a queen
;; Move flag type bit positions
(defconstant mfbp-anfd 0) ; algebraic notation needs file disambiguation
(defconstant mfbp-anrd 1) ; algebraic notation needs rank disambiguation
(defconstant mfbp-bust 2) ; illegal move
(defconstant mfbp-chec 3) ; checking move, including checkmating
(defconstant mfbp-chmt 4) ; checkmating move
(defconstant mfbp-exec 5) ; executed move
(defconstant mfbp-null 6) ; null move
(defconstant mfbp-srch 7) ; searched move
(defconstant mfbp-stmt 8) ; stalemating move
Move flag type bitfields
(defconstant mflg-anfd (ash 1 mfbp-anfd))
(defconstant mflg-anrd (ash 1 mfbp-anrd))
(defconstant mflg-bust (ash 1 mfbp-bust))
(defconstant mflg-chec (ash 1 mfbp-chec))
(defconstant mflg-chmt (ash 1 mfbp-chmt))
(defconstant mflg-exec (ash 1 mfbp-exec))
(defconstant mflg-null (ash 1 mfbp-null))
(defconstant mflg-srch (ash 1 mfbp-srch))
(defconstant mflg-stmt (ash 1 mfbp-stmt))
;; Move structure
(defstruct move
(frsq sq-nil :type fixnum) ; from square
(tosq sq-nil :type fixnum) ; to square
(frcp cp-nil :type fixnum) ; from color-piece
(tocp cp-nil :type fixnum) ; to color-piece
(scmv scmv-nil :type fixnum) ; special case indication
(mflg 0 :type fixnum) ; move flags
)
;; The null move
(defvar null-move
(make-move :mflg mflg-null))
;; The empty move
(defvar empty-move
(make-move))
;; PGN Seven Tag Roster
the Seven Tag Roster
PGN Event
(defconstant tag-name-site 1) ; PGN Site
PGN Date
PGN Round
PGN White
PGN Black
PGN Result
(defparameter tag-name-strings
(make-array tag-name-limit
:initial-contents
`("Event" "Site" "Date" "Round" "White" "Black" "Result")))
;; game termination indicators
(defconstant gtim-limit 4)
(defconstant gtim-nil -1)
(defconstant gtim-white 0) ; White wins
(defconstant gtim-black 1) ; Black wins
(defconstant gtim-draw 2) ; drawn
(defconstant gtim-unknown 3) ; unknown or not specified
(defparameter gtim-strings
(make-array gtim-limit
:initial-contents '("1-0" "0-1" "1/2-1/2" "*")))
Fifty move draw rule limit
(defconstant fmrfmv-limit 50)
(defconstant fmrhmv-limit (* fmrfmv-limit rc-limit))
;; Ply search depth limit
(defconstant ply-limit 64)
;; Game full move history limit (maximum full moves per game)
(defconstant gfmh-limit 200)
Game half move history limit ( maximum half moves per game )
(defconstant ghmh-limit (* gfmh-limit rc-limit))
;; The null bitboard
(defparameter null-bb
(make-array sq-limit
:element-type 'bit
:initial-element 0))
;; Directional edge bitboard vector (dx0..dx7)
(defvar debbv
(make-array rdx-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
;; Directional scanning array of lists of squares
(defvar ds-offsets
(make-array `(,dx-limit ,sq-limit)
:element-type 'fixnum
:initial-element 0))
;; Sum of ray/knight distances for all squares and all directions
(defconstant ds-square-limit 2816)
;; Squares along a ray/knight (indexed by ds-offsets)
(defvar ds-squares
(make-array ds-square-limit
:element-type 'fixnum
:initial-element 0))
;; Directional locator; gives direction from sq0 to sq1
(defvar dloc
(make-array `(,sq-limit ,sq-limit)
:element-type 'fixnum
:initial-element dx-nil))
;; On-board-next; check for continuing along a direction from a square
(defvar obnext
(make-array `(,dx-limit ,sq-limit)
:element-type t
:initial-element nil))
;; Interpath squares bitboard array
(defvar ipbbv
(make-array `(,sq-limit ,sq-limit)
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
Knight moves bitboard vector ( sq - a1 .. sq - h8 )
(defvar nmbbv
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
;; King moves bitboard vector (sq-a1..sq-h8)
(defvar kmbbv
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
;; Centipawn material evaluations (can be tuned)
(defconstant cpe-p 100) ; pawn
(defconstant cpe-n 325) ; knight
(defconstant cpe-b 350) ; bishop
(defconstant cpe-r 500) ; rook
(defconstant cpe-q 900) ; queen
(defconstant cpe-k 0) ; king
(defparameter cpe-pv
(make-array rp-limit
:element-type 'fixnum
:initial-contents
`(,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k)))
(defparameter cpe-cpv
(make-array rcp-limit
:element-type 'fixnum
:initial-contents
`(,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k
,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k)))
;;; --- Variables -----------------------------------------------
IDV : Internal Database Variables ( must keep mutually synchronized )
[ IDV ] The board
(declaim (type (simple-array fixnum 64) *board*))
(defvar *board*
(make-array sq-limit
:element-type 'fixnum
:initial-element cp-v0))
[ IDV ] Current status items ( included in Forsyth - Edwards Notation )
(declaim (type fixnum *actc*))
(declaim (type fixnum *pasc*))
(declaim (type fixnum *cast*))
(declaim (type fixnum *epsq*))
(declaim (type fixnum *hmvc*))
(declaim (type fixnum *fmvn*))
(defvar *actc* c-w) ; active color
passive color ( not used in FEN )
(defvar *cast* 0) ; castling availability
(defvar *epsq* sq-nil) ; en passant target square
half move clock
(defvar *fmvn* 1) ; full move number
[ IDV ] Color - piece occupancy bitboard vector ( cp - wp .. cp - bk )
(defvar *cpbbv*
(make-array rcp-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Color occupancy bitboard vector ( unions of * cpbbv * by color )
(defvar *c0bbv*
(make-array rc-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] All men merged ( union of * c0bbv * )
(defvar *ammbb*
(make-array sq-limit
:element-type 'bit
:initial-element 0))
[ IDV ] Attack to by color bitboard vector ( c - w .. c - b )
(defvar *acbbv*
(make-array rc-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Attack to by ( sq - a1 .. sq - h8 )
(defvar *atbbv*
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Attack from by ( sq - a1 .. sq - h8 )
(defvar *afbbv*
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
;;; PIV: Ply Indexed Variables
;; [PIV] The current ply, used as an index for several variables
(declaim (type fixnum *ply*))
(defvar *ply* 0)
;; [PIV] The move generation stack
average of 64 moves per ply
(defvar *mgs* (make-array mgs-limit :element-type 'move))
[ PIV ] The MGS base ( saved values ; start of moves for a ply )
(declaim (type fixnum *mgs-base-local*))
(defvar *mgs-base-local* 0) ; local for this ply (direct index to *mgs*)
(defvar *mgs-base*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS current move index ( saved values ; current move in ply )
(declaim (type fixnum *mgs-current-local*))
(defvar *mgs-current-local* 0) ; local for this ply (direct index to *mgs*)
(defvar *mgs-current*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS move count ( saved values ; number of moves per ply )
(declaim (type fixnum *mgs-count-local*))
(defvar *mgs-count-local* 0) ; local value for this ply
(defvar *mgs-count*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS castling ( indicates castling status at ply )
(defvar *mgs-cast*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS ep targets ( indicates ep target at ply )
(defvar *mgs-epsq*
(make-array ply-limit
:element-type 'fixnum
:initial-element sq-nil))
[ PIV ] The MGS halfmove clocks ( indicates hmvc at ply )
(defvar *mgs-hmvc*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS fullmove numbers ( indicates fmvn at ply )
(defvar *mgs-fmvn*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
;;; GHV: Game History Variables
[ GHV ] Move count in history ; the master index for the GHV set ( )
(declaim (type fixnum *gmh-count*))
(defvar *gmh-count* 0)
;; [GHV] Moves in history
(defvar *gmh-move* (make-array ghmh-limit :element-type 'move))
[ GHV ] Boards in history
(defvar *gmh-board* (make-array ghmh-limit))
;; [GHV] Active colors in history
(defvar *gmh-actc* (make-array ghmh-limit :element-type 'fixnum))
;; [GHV] Castling availabilities in history
(defvar *gmh-cast* (make-array ghmh-limit :element-type 'fixnum))
;; [GHV] En passant target squares in history
(defvar *gmh-epsq* (make-array ghmh-limit :element-type 'fixnum))
;; [GHV] Halfmove clocks in history
(defvar *gmh-hmvc* (make-array ghmh-limit :element-type 'fixnum))
;; [GHV] Fullmove numbers in history
(defvar *gmh-fmvn* (make-array ghmh-limit :element-type 'fixnum))
;; Counters
(defvar *count-execute* 0)
;; Files
(defvar *pathway-file-stream* nil)
;;; --- Functions -----------------------------------------------
;;; *** Attack bitboard database management functions
(defun attack-add (sq)
"Add attacks for a square; piece already on board"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq))
(c (aref mapv-c cp))
(p (aref mapv-p cp))
(bb (copy-seq null-bb)))
(declare (type fixnum cp c p))
(cond
((eql p p-p)
(if (eql c c-w)
(progn
(if (aref obnext dx-4 sq)
(setf (sbit bb (+ sq dv-4)) 1))
(if (aref obnext dx-5 sq)
(setf (sbit bb (+ sq dv-5)) 1)))
(progn
(if (aref obnext dx-6 sq)
(setf (sbit bb (+ sq dv-6)) 1))
(if (aref obnext dx-7 sq)
(setf (sbit bb (+ sq dv-7)) 1)))))
((eql p p-n)
(setf bb (copy-seq (aref nmbbv sq))))
((eql p p-b)
(do* ((dx dx-4)) ((eql dx dx-8))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-r)
(do* ((dx dx-0)) ((eql dx dx-4))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-q)
(do* ((dx dx-0)) ((eql dx dx-8))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-k)
(setf bb (copy-seq (aref kmbbv sq)))))
(setf (aref *afbbv* sq) (copy-seq bb))
(bit-ior (aref *acbbv* c) bb t)
(do* ((rsq)) ((equal bb null-bb))
(declare (type fixnum rsq))
(setf rsq (position 1 bb))
(setf (sbit (aref *atbbv* rsq) sq) 1)
(setf (sbit bb rsq) 0))))
(defun attack-del (sq)
"Delete attacks for an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq))
(c (aref mapv-c cp))
(bb (copy-seq (aref *afbbv* sq))))
(declare (type fixnum cp c))
(setf (aref *afbbv* sq) (copy-seq null-bb))
(do* ((rsq)) ((equal bb null-bb))
(declare (type fixnum rsq))
(setf rsq (position 1 bb))
(setf (sbit bb rsq) 0)
(setf (sbit (aref *atbbv* rsq) sq) 0)
(if (equal
(bit-and (aref *atbbv* rsq) (aref *c0bbv* c)) null-bb)
(setf (sbit (aref *acbbv* c) rsq) 0)))))
(defun attack-pro (sq)
"Propagate attacks through an empty square"
(declare (type fixnum sq))
(let* ((bb (copy-seq (aref *atbbv* sq))))
(do* ((asq)) ((equal bb null-bb))
(declare (type fixnum asq))
(setf asq (position 1 bb))
(setf (sbit bb asq) 0)
(let* ((acp (aref *board* asq)))
(declare (type fixnum acp))
(when (eql (aref sweeper-cp acp) 1)
(let*
((dx (aref dloc asq sq))
(debb (copy-seq (aref debbv dx))))
(declare (type fixnum dx))
(if (eql (sbit debb sq) 0)
(let*
((ac (aref mapv-c acp))
(axbb (copy-seq null-bb))
(bsbb (bit-ior debb *ammbb*))
(dv (aref mapv-dv dx))
(rsq sq))
(declare (type fixnum ac dv rsq))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 1)
(setf (sbit axbb rsq) 1)
(do () ((eql (sbit bsbb rsq) 1))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 1)
(setf (sbit axbb rsq) 1))
(bit-ior (aref *afbbv* asq) axbb t)
(bit-ior (aref *acbbv* ac) axbb t)))))))))
(defun attack-cut (sq)
"Cut attacks through an empty square"
(declare (type fixnum sq))
(let* ((bb (copy-seq (aref *atbbv* sq))))
(do* ((asq)) ((equal bb null-bb))
(declare (type fixnum asq))
(setf asq (position 1 bb))
(setf (sbit bb asq) 0)
(let* ((acp (aref *board* asq)))
(declare (type fixnum acp))
(when (eql (aref sweeper-cp acp) 1)
(let*
((dx (aref dloc asq sq))
(debb (copy-seq (aref debbv dx))))
(declare (type fixnum dx))
(if (eql (sbit debb sq) 0)
(let*
((ac (aref mapv-c acp))
(c0bb (copy-seq (aref *c0bbv* ac)))
(bsbb (bit-ior debb *ammbb*))
(dv (aref mapv-dv dx))
(rsq sq))
(declare (type fixnum ac dv rsq))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 0)
(setf (sbit (aref *afbbv* asq) rsq) 0)
(when (equal
(bit-and (aref *atbbv* rsq) c0bb)
null-bb)
(setf (sbit (aref *acbbv* ac) rsq) 0))
(do () ((eql (sbit bsbb rsq) 1))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 0)
(setf (sbit (aref *afbbv* asq) rsq) 0)
(when (equal
(bit-and (aref *atbbv* rsq) c0bb)
null-bb)
(setf (sbit (aref *acbbv* ac) rsq) 0)))))))))))
;;; *** Square set/clear interface routines to the attack bitboard managament functions
(defun square-clear (sq)
"Clear the contents of an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq)))
(declare (type fixnum cp))
(setf (sbit *ammbb* sq) 0)
(setf (sbit (aref *c0bbv* (aref mapv-c cp)) sq) 0)
(setf (sbit (aref *cpbbv* cp) sq) 0))
(attack-del sq)
(setf (aref *board* sq) cp-v0)
(attack-pro sq))
(defun square-set (sq cp)
"Set the contents of a vacant square"
(declare (type fixnum sq cp))
(attack-cut sq)
(setf (aref *board* sq) cp)
(attack-add sq)
(setf (sbit *ammbb* sq) 1)
(setf (sbit (aref *c0bbv* (aref mapv-c cp)) sq) 1)
(setf (sbit (aref *cpbbv* cp) sq) 1))
;;; *** Various reset routines for the internal database variables
(defun clear-bitboard-sets ()
"Clear all the bitboard items for the current position"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *afbbv* sq) (copy-seq null-bb))
(setf (aref *atbbv* sq) (copy-seq null-bb)))
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref *cpbbv* cp) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *c0bbv* c) (copy-seq null-bb))
(setf (aref *acbbv* c) (copy-seq null-bb)))
(setf *ammbb* (copy-seq null-bb)))
(defun clear-position-scalars ()
"Clear the basic position scalars"
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* 0)
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1))
(defun clear-board ()
"Clear the board array"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *board* sq) cp-v0)))
(defun clear-position ()
"Clear the current position"
(clear-position-scalars)
(clear-board)
(clear-bitboard-sets))
;;; *** Helper routines for board/square access
(declaim (inline on-board-next))
(defun on-board-next (dx sq)
"Determine if the next square along a direction is really on the board"
(declare (type fixnum dx sq))
(let*
((new-file (the fixnum (+ (map-file sq) (aref mapv-df dx))))
(new-rank (the fixnum (+ (map-rank sq) (aref mapv-dr dx)))))
(declare (type fixnum new-rank new-file))
(and
(>= new-file file-a) (<= new-file file-h)
(>= new-rank rank-1) (<= new-rank rank-8))))
;;; *** Various initialization routines; each called only once
(defun initialize-obnext ()
"Initialize the on-board-next array"
(dotimes (dx dx-limit)
(declare (type fixnum dx))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref obnext dx sq) (on-board-next dx sq)))))
(defun initialize-knight-move-bitboards ()
"Initialize the knight moves bitboard vector"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref nmbbv sq) (copy-seq null-bb))
(do* ((dx rdx-limit)) ((eql dx dx-limit))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(setf (sbit (aref nmbbv sq) (+ sq (aref mapv-dv dx))) 1))
(incf dx))))
(defun initialize-king-move-bitboards ()
"Initialize the king moves bitboard vector"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref kmbbv sq) (copy-seq null-bb))
(dotimes (dx rdx-limit)
(declare (type fixnum dx))
(if (aref obnext dx sq)
(setf (sbit (aref kmbbv sq) (+ sq (aref mapv-dv dx))) 1)))))
(defun initialize-directional-edge-bitboards ()
"Initialize the directional edge bitboards"
(dotimes (dx dx-4)
(declare (type fixnum dx))
(setf (aref debbv dx) (copy-seq null-bb)))
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(setf (sbit (aref debbv dx-0) (map-sq rank file-h)) 1)
(setf (sbit (aref debbv dx-2) (map-sq rank file-a)) 1))
(dotimes (file file-limit)
(declare (type fixnum file))
(setf (sbit (aref debbv dx-1) (map-sq rank-8 file)) 1)
(setf (sbit (aref debbv dx-3) (map-sq rank-1 file)) 1))
(setf (aref debbv dx-4) (bit-ior (aref debbv dx-0) (aref debbv dx-1)))
(setf (aref debbv dx-5) (bit-ior (aref debbv dx-1) (aref debbv dx-2)))
(setf (aref debbv dx-6) (bit-ior (aref debbv dx-2) (aref debbv dx-3)))
(setf (aref debbv dx-7) (bit-ior (aref debbv dx-3) (aref debbv dx-0))))
(defun initialize-directional-scanning-array ()
"Initialize the direction scanning items: offsets and squares"
(let* ((sqdex 0))
(declare (type fixnum sqdex))
(dotimes (dx rdx-limit)
(declare (type fixnum dx))
(let* ((delta (aref mapv-dv dx)) (edge (copy-seq (aref debbv dx))))
(declare (type fixnum delta))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref ds-offsets dx sq) sqdex)
(let* ((rsq sq))
(declare (type fixnum rsq))
(do* () ((eql (sbit edge rsq) 1))
(incf rsq delta)
(setf (aref ds-squares sqdex) rsq)
(incf sqdex))
(setf (aref ds-squares sqdex) sq-nil)
(incf sqdex)))))
(do* ((dx rdx-limit)) ((eql dx dx-limit))
(declare (type fixnum dx))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref ds-offsets dx sq) sqdex)
(when (aref obnext dx sq)
(setf (aref ds-squares sqdex) (+ sq (aref mapv-dv dx)))
(incf sqdex))
(setf (aref ds-squares sqdex) sq-nil)
(incf sqdex))
(incf dx))))
(defun initialize-directional-locator-array ()
"Intiailize the directional locator array"
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref dloc sq0 sq1) dx-nil)))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (dx dx-limit)
(declare (type fixnum dx))
(do* ((sqdex (aref ds-offsets dx sq0))) ((eql (aref ds-squares sqdex) sq-nil))
(declare (type fixnum sqdex))
(setf (aref dloc sq0 (aref ds-squares sqdex)) dx)
(incf sqdex)))))
(defun initialize-intersquare-pathway-bitboards ()
"Initialize the intersquare pathway bitboard vector"
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref ipbbv sq0 sq1) (copy-seq null-bb))))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(let* ((dx (aref dloc sq0 sq1)))
(declare (type fixnum dx))
(if (and (>= dx dx-0) (<= dx dx-7))
(do* ((rsq (+ sq0 (aref mapv-dv dx)))) ((eql rsq sq1))
(declare (type fixnum rsq))
(setf (sbit (aref ipbbv sq0 sq1) rsq) 1)
(incf rsq (aref mapv-dv dx))))))))
(defun initialize-constants ()
"Perform initialization of constant values"
(initialize-obnext)
(initialize-directional-edge-bitboards)
(initialize-directional-scanning-array)
(initialize-directional-locator-array)
(initialize-intersquare-pathway-bitboards)
(initialize-knight-move-bitboards)
(initialize-king-move-bitboards))
(defun initialize-variables ()
"Perform initialization of variable values"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *board* sq) cp-v0))
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* (logior cflg-wk cflg-wq cflg-bk cflg-bq))
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1)
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref *cpbbv* cp) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *c0bbv* c) (copy-seq null-bb)))
(setf *ammbb* (copy-seq null-bb))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *afbbv* sq) (copy-seq null-bb)))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *atbbv* sq) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *acbbv* c) (copy-seq null-bb)))
(setf *ply* 0)
(dotimes (index mgs-limit)
(declare (type fixnum index))
(setf (aref *mgs* index) (make-move)))
(setf *mgs-base-local* 0)
(setf *mgs-current-local* 0)
(setf *mgs-count-local* 0)
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *mgs-base* index) 0)
(setf (aref *mgs-current* index) 0)
(setf (aref *mgs-count* index) 0))
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *mgs-cast* index) 0)
(setf (aref *mgs-epsq* index) sq-nil)
(setf (aref *mgs-hmvc* index) 0)
(setf (aref *mgs-fmvn* index) 0))
(setf *gmh-count* 0)
(dotimes (index ghmh-limit)
(declare (type fixnum index))
(setf (aref *gmh-move* index) (make-move))
(setf (aref *gmh-board* index) (copy-seq *board*))
(setf (aref *gmh-cast* index) 0)
(setf (aref *gmh-epsq* index) sq-nil)
(setf (aref *gmh-hmvc* index) 0)
(setf (aref *gmh-fmvn* index) 0))
(setf *count-execute* 0)
(new-game))
(defun initialize ()
"Perform one time initialization"
(initialize-constants)
(initialize-variables)
(format t "~%Ready~%")
(values))
;;; *** Printing and string generation routines for bitboard items
(defun print-bitboard (bb)
"Print a bitboard character string (eight lines long)"
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(dotimes (file file-limit)
(declare (type fixnum file))
(format t " ~d" (sbit bb (map-sq (- rank-8 rank) file))))
(format t "~%"))
(values))
(defun genstr-square-set (bb)
"Generate a square set string from a bitboard"
(let* ((s "[") (flag nil))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(when (eql (sbit bb sq) 1)
(if flag
(setf s (strcat s " "))
(setf flag t))
(setf s (strcat s (aref sq-strings sq)))))
(setf s (strcat s "]"))
s))
(defun print-square-set (bb)
"Print a square set string from a bitboard"
(format t "~a" (genstr-square-set bb))
(values))
;;; *** Debugging output routines for bitboard items
(defun pbaf (sq)
"Print bitboard: afbbv[sq]"
(print-bitboard (aref *afbbv* sq)))
(defun pbat (sq)
"Print bitboard: atbbv[sq]"
(print-bitboard (aref *atbbv* sq)))
(defun pbac (c)
"Print bitboard: acbbv[c]"
(print-bitboard (aref *acbbv* c)))
(defun pbcp (cp)
"Print bitboard: cpbbv[cp]"
(print-bitboard (aref *cpbbv* cp)))
(defun pbc0 (c)
"Print bitboard: c0bbv[c]"
(print-bitboard (aref *c0bbv* c)))
;;; *** Debugging output routines for various tests
(defun pe (n)
(pathway-enumerate n))
;;; *** Game history status routines
(defun regenerate-bitboards ()
"Regenerate the bitboard environment from the board"
(let* ((board (copy-seq *board*)))
(clear-bitboard-sets)
(clear-board)
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(if (not (eql (aref board sq) cp-v0))
(square-set sq (aref board sq))))))
(defun history-clear ()
"Clear the history for a new game or set-up position"
(setf *gmh-count* 0))
(defun history-push ()
"Push the current status items on to the history stack"
(setf (aref *gmh-move* *gmh-count*)
(copy-move (aref *mgs* *mgs-current-local*)))
(setf (aref *gmh-board* *gmh-count*) (copy-seq *board*))
(setf (aref *gmh-actc* *gmh-count*) *actc*)
(setf (aref *gmh-cast* *gmh-count*) *cast*)
(setf (aref *gmh-epsq* *gmh-count*) *epsq*)
(setf (aref *gmh-hmvc* *gmh-count*) *hmvc*)
(setf (aref *gmh-fmvn* *gmh-count*) *fmvn*)
(incf *gmh-count*))
(defun history-pop ()
"Pop the current status items off from the history stack"
(decf *gmh-count*)
(setf *board* (copy-seq (aref *gmh-board* *gmh-count*)))
(setf *actc* (aref *gmh-actc* *gmh-count*))
(setf *pasc* (aref invc-v *actc*))
(setf *cast* (aref *gmh-cast* *gmh-count*))
(setf *epsq* (aref *gmh-epsq* *gmh-count*))
(setf *hmvc* (aref *gmh-hmvc* *gmh-count*))
(setf *fmvn* (aref *gmh-fmvn* *gmh-count*))
(clear-move-generation)
(regenerate-bitboards)
(generate)
(setf *mgs-current-local* (ms-find-move (aref *gmh-move* *gmh-count*))))
(defun create ()
"Create/recreate the environment at ply zero"
(history-clear)
(clear-move-generation)
(if (valid-position)
(generate)
(format t "Warning: invalid position~%")))
;;; *** Move execution and retraction routines
(defun execute ()
"Execute the current move in the internal environment"
(incf *count-execute*)
(let* ((move (aref *mgs* *mgs-current-local*)) (scmv (move-scmv move)))
(cond
((eql scmv scmv-reg)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) (move-frcp move))))
((eql scmv scmv-cks)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-e1)
(square-set sq-g1 cp-wk)
(square-clear sq-h1)
(square-set sq-f1 cp-wr))
(progn
(square-clear sq-e8)
(square-set sq-g8 cp-bk)
(square-clear sq-h8)
(square-set sq-f8 cp-br))))
((eql scmv scmv-cqs)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-e1)
(square-set sq-c1 cp-wk)
(square-clear sq-a1)
(square-set sq-d1 cp-wr))
(progn
(square-clear sq-e8)
(square-set sq-c8 cp-bk)
(square-clear sq-a8)
(square-set sq-d8 cp-br))))
((eql scmv scmv-epc)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (+ (move-tosq move) dv-3))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wp))
(progn
(square-clear (+ (move-tosq move) dv-1))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bp))))
((eql scmv scmv-ppn)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wn))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bn))))
((eql scmv scmv-ppb)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wb))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bb))))
((eql scmv scmv-ppr)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wr))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-br))))
((eql scmv scmv-ppq)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wq))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bq)))))
(setf *actc* (aref invc-v *actc*))
(setf *pasc* (aref invc-v *pasc*))
(setf (aref *mgs-cast* *ply*) *cast*)
(setf (aref *mgs-epsq* *ply*) *epsq*)
(setf (aref *mgs-hmvc* *ply*) *hmvc*)
(setf (aref *mgs-fmvn* *ply*) *fmvn*)
(mf-set mfbp-exec)
(if (in-check)
(mf-set mfbp-chec))
(if (busted)
(mf-set mfbp-bust))
(when (not (eql *cast* 0))
(if
(and
(logbitp csbp-wk *cast*)
(or
(eql (move-frsq move) sq-e1)
(eql (move-frsq move) sq-h1)
(eql (move-tosq move) sq-h1)))
(setf *cast* (logxor *cast* cflg-wk)))
(if
(and
(logbitp csbp-wq *cast*)
(or
(eql (move-frsq move) sq-e1)
(eql (move-frsq move) sq-a1)
(eql (move-tosq move) sq-a1)))
(setf *cast* (logxor *cast* cflg-wq)))
(if
(and
(logbitp csbp-bk *cast*)
(or
(eql (move-frsq move) sq-e8)
(eql (move-frsq move) sq-h8)
(eql (move-tosq move) sq-h8)))
(setf *cast* (logxor *cast* cflg-bk)))
(if
(and
(logbitp csbp-bq *cast*)
(or
(eql (move-frsq move) sq-e8)
(eql (move-frsq move) sq-a8)
(eql (move-tosq move) sq-a8)))
(setf *cast* (logxor *cast* cflg-bq))))
(setf *epsq* sq-nil)
(if
(and
(eql (move-frcp move) cp-wp)
(eql (map-rank (move-frsq move)) rank-2)
(eql (map-rank (move-tosq move)) rank-4))
(setf *epsq* (+ (move-frsq move) dv-1)))
(if
(and
(eql (move-frcp move) cp-bp)
(eql (map-rank (move-frsq move)) rank-7)
(eql (map-rank (move-tosq move)) rank-5))
(setf *epsq* (+ (move-frsq move) dv-3)))
(if (or (eql (aref mapv-p (move-frcp move)) p-p) (not (eql (move-tocp move) cp-v0)))
(setf *hmvc* 0)
(incf *hmvc*))
(if (eql (aref mapv-c (move-frcp move)) c-b)
(incf *fmvn*)))
(setf (aref *mgs-base* *ply*) *mgs-base-local*)
(setf (aref *mgs-current* *ply*) *mgs-current-local*)
(setf (aref *mgs-count* *ply*) *mgs-count-local*)
(setf *mgs-base-local* (+ *mgs-base-local* *mgs-count-local*))
(setf *mgs-current-local* *mgs-base-local*)
(setf *mgs-count-local* 0)
(incf *ply*))
(defun retract ()
"Retract the previously executed move in the internal environment"
(decf *ply*)
(setf *mgs-base-local* (aref *mgs-base* *ply*))
(setf *mgs-current-local* (aref *mgs-current* *ply*))
(setf *mgs-count-local* (aref *mgs-count* *ply*))
(setf *actc* (aref invc-v *actc*))
(setf *pasc* (aref invc-v *pasc*))
(setf *cast* (aref *mgs-cast* *ply*))
(setf *epsq* (aref *mgs-epsq* *ply*))
(setf *hmvc* (aref *mgs-hmvc* *ply*))
(setf *fmvn* (aref *mgs-fmvn* *ply*))
(let* ((move (aref *mgs* *mgs-current-local*)) (scmv (move-scmv move)))
(cond
((eql scmv scmv-reg)
(progn
(square-clear (move-tosq move))
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move)))
(square-set (move-frsq move) (move-frcp move))))
((eql scmv scmv-cks)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-g1)
(square-set sq-e1 cp-wk)
(square-clear sq-f1)
(square-set sq-h1 cp-wr))
(progn
(square-clear sq-g8)
(square-set sq-e8 cp-bk)
(square-clear sq-f8)
(square-set sq-h8 cp-br))))
((eql scmv scmv-cqs)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-c1)
(square-set sq-e1 cp-wk)
(square-clear sq-d1)
(square-set sq-a1 cp-wr))
(progn
(square-clear sq-c8)
(square-set sq-e8 cp-bk)
(square-clear sq-d8)
(square-set sq-a8 cp-br))))
((eql scmv scmv-epc)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(square-set (+ (move-tosq move) dv-3) cp-bp))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(square-set (+ (move-tosq move) dv-1) cp-wp))))
((eql scmv scmv-ppn)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppb)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppr)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppq)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move)))))))))
* * * PGN routines
(defun genstr-tag-pair (tag-name tag-value)
"Generate a tag pair string"
(format nil "[~a \"~a\"]" tag-name tag-value))
(defun print-tag-pair (tag-name tag-value)
"Print a tag pair string on a line"
(format t "~a~%" (genstr-tag-pair tag-name tag-value)))
(defun strcat (s0 s1)
"Return the concatenation of two strings"
(let* ((len0 (length s0)) (len1 (length s1))
(s2 (make-string (+ len0 len1))))
(dotimes (i len0)
(setf (schar s2 i) (schar s0 i)))
(dotimes (i len1)
(setf (schar s2 (+ len0 i)) (schar s1 i)))
s2))
;;; *** Move generation routines
(defun generate-psuedolegal-frsq-wp (sq)
"Generate psuedolegal moves for a white pawn"
(declare (type fixnum sq))
(let* ((gmove (make-move)))
(when (eql (aref *board* (+ sq dv-1)) cp-v0)
(if (not (eql (map-rank sq) rank-7))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-1))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(when
(and
(eql (map-rank sq) rank-2)
(eql (aref *board* (+ sq (* dv-1 2))) cp-v0))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq (* dv-1 2)))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-1))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))
(dolist (dx `(,dx-4 ,dx-5))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(let*
((tosq (+ sq (aref mapv-dv dx)))
(tocp (aref *board* tosq)))
(declare (type fixnum tosq tocp))
(when (eql (aref mapv-c tocp) c-b)
(if (not (eql (map-rank sq) rank-7))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(progn
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))))))
(dolist (dx `(,dx-4 ,dx-5))
(declare (type fixnum dx))
(when
(and
(not (eql *epsq* sq-nil))
(eql (map-rank sq) rank-5)
(aref obnext dx sq)
(eql *epsq* (+ sq (aref mapv-dv dx))))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) *epsq*)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-epc)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))))
(defun generate-psuedolegal-frsq-bp (sq)
"Generate psuedolegal moves for a black pawn"
(declare (type fixnum sq))
(let* ((gmove (make-move)))
(when (eql (aref *board* (+ sq dv-3)) cp-v0)
(if (not (eql (map-rank sq) rank-2))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-3))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(when
(and
(eql (map-rank sq) rank-7)
(eql (aref *board* (+ sq (* dv-3 2))) cp-v0))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq (* dv-3 2)))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-3))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))
(dolist (dx `(,dx-6 ,dx-7))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(let*
((tosq (+ sq (aref mapv-dv dx)))
(tocp (aref *board* tosq)))
(declare (type fixnum tosq tocp))
(when (eql (aref mapv-c tocp) c-w)
(if (not (eql (map-rank sq) rank-2))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(progn
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))))))
(dolist (dx `(,dx-6 ,dx-7))
(declare (type fixnum dx))
(when
(and
(not (eql *epsq* sq-nil))
(eql (map-rank sq) rank-4)
(aref obnext dx sq)
(eql *epsq* (+ sq (aref mapv-dv dx))))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) *epsq*)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-epc)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))))
(defun generate-psuedolegal-frsq-wk (sq)
"Generate psuedolegal moves for a white king"
(declare (type fixnum sq))
(let*
((bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c-w))))
(gmove (make-move)))
(setf bb (bit-and bb (bit-not (aref *acbbv* c-b))))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-wk *cast*)
(eql (aref *board* sq-f1) cp-v0)
(eql (aref *board* sq-g1) cp-v0)
(eql (sbit (aref *acbbv* c-b) sq-e1) 0)
(eql (sbit (aref *acbbv* c-b) sq-f1) 0)
(eql (sbit (aref *acbbv* c-b) sq-g1) 0))
(setf (move-frsq gmove) sq-e1)
(setf (move-tosq gmove) sq-g1)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cks)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-wq *cast*)
(eql (aref *board* sq-d1) cp-v0)
(eql (aref *board* sq-c1) cp-v0)
(eql (aref *board* sq-b1) cp-v0)
(eql (sbit (aref *acbbv* c-b) sq-e1) 0)
(eql (sbit (aref *acbbv* c-b) sq-d1) 0)
(eql (sbit (aref *acbbv* c-b) sq-c1) 0))
(setf (move-frsq gmove) sq-e1)
(setf (move-tosq gmove) sq-c1)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cqs)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq-bk (sq)
"Generate psuedolegal moves for a black king"
(declare (type fixnum sq))
(let*
((bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c-b))))
(gmove (make-move)))
(setf bb (bit-and bb (bit-not (aref *acbbv* c-w))))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-bk *cast*)
(eql (aref *board* sq-f8) cp-v0)
(eql (aref *board* sq-g8) cp-v0)
(eql (sbit (aref *acbbv* c-w) sq-e8) 0)
(eql (sbit (aref *acbbv* c-w) sq-f8) 0)
(eql (sbit (aref *acbbv* c-w) sq-g8) 0))
(setf (move-frsq gmove) sq-e8)
(setf (move-tosq gmove) sq-g8)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cks)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-bq *cast*)
(eql (aref *board* sq-d8) cp-v0)
(eql (aref *board* sq-c8) cp-v0)
(eql (aref *board* sq-b8) cp-v0)
(eql (sbit (aref *acbbv* c-w) sq-e8) 0)
(eql (sbit (aref *acbbv* c-w) sq-d8) 0)
(eql (sbit (aref *acbbv* c-w) sq-c8) 0))
(setf (move-frsq gmove) sq-e8)
(setf (move-tosq gmove) sq-c8)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cqs)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq-regular (sq)
"Generate psuedolegal moves for a knight, bishop, rook, or queen"
(declare (type fixnum sq))
(let*
((cp (aref *board* sq))
(c (aref mapv-c cp))
(bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c))))
(gmove (make-move)))
(declare (type fixnum cp c))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq (sq)
"Generate psuedolegal moves for from an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq)) (p (aref mapv-p cp)) (c (aref mapv-c cp)))
(declare (type fixnum cp p c))
(cond
((eql p p-p)
(if (eql c c-w)
(generate-psuedolegal-frsq-wp sq)
(generate-psuedolegal-frsq-bp sq)))
((eql p p-k)
(if (eql c c-w)
(generate-psuedolegal-frsq-wk sq)
(generate-psuedolegal-frsq-bk sq)))
(t
(generate-psuedolegal-frsq-regular sq)))))
(defun generate-psuedolegal ()
"Generate psuedolegal moves for the current position at the current ply"
(setf *mgs-current-local* *mgs-base-local*)
(setf *mgs-count-local* 0)
(let ((bb (copy-seq (aref *c0bbv* *actc*))))
(do* ((frsq)) ((equal bb null-bb))
(declare (type fixnum frsq))
(setf frsq (position 1 bb))
(setf (sbit bb frsq) 0)
(generate-psuedolegal-frsq frsq))))
(defun generate-legal ()
"Generate legal moves for the current position at the current ply"
(generate-psuedolegal)
(ms-execute)
(ms-compact))
(defun generate ()
"Generate legal moves with full notation"
(generate-legal)
(ms-matescan)
(ms-disambiguate))
(defun clear-move-generation ()
"Clear the move generation variables for ply zero"
(setf *mgs-base-local* 0)
(setf *mgs-current-local* 0)
(setf *mgs-count-local* 0))
(defun fetch-move-strings (base count)
"Return a list of move strings for the indicated bounds"
(let* ((sl nil) (index base) (limit (+ base count)))
(do () ((eql index limit))
(setf sl (cons (genstr-san (aref *mgs* index)) sl))
(incf index))
(reverse sl)))
(defun fetch-move-strings-at-ply (ply)
"Return a list of move strings for the indicated ply"
(if (eql ply *ply*)
(fetch-move-strings *mgs-base-local* *mgs-count-local*)
(fetch-move-strings (aref *mgs-base* *ply*) (aref *mgs-count* *ply*))))
(defun fetch-move-strings-at-current ()
"Return a list of move strings for the current level"
(fetch-move-strings-at-ply *ply*))
(defun fetch-move-strings-at-base ()
"Return a list of move strings for the base level"
(fetch-move-strings-at-ply 0))
* * * * Moveset manipulation routines
(defun ms-execute-print ()
"Execute and retract each move in the current set with diagnostic output"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(format t "Move: ~a~%" (genstr-san (aref *mgs* *mgs-current-local*)))
(execute)
(format t "FEN: ~a~%" (genstr-fen))
(retract)
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)
limit))
(defun ms-execute ()
"Execute and retract each move in the current set (move flags: exec/bust)"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(declare (type fixnum save-index limit))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(declare (type fixnum index))
(execute)
(retract)
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)
limit))
(defun ms-compact ()
"Compact current moveset by eliminating illegal moves"
(let* ((limit *mgs-count-local*) (busted 0) (dst 0))
(declare (type fixnum limit busted dst))
(dotimes (src limit)
(declare (type fixnum src))
(setf *mgs-current-local* (+ src *mgs-base-local*))
(if (mf-test mfbp-bust)
(incf busted)
(progn
(if (not (eql src dst))
(setf (aref *mgs* (+ *mgs-base-local* dst))
(aref *mgs* (+ *mgs-base-local* src))))
(incf dst))))
(decf *mgs-count-local* busted)
(setf *mgs-current-local* *mgs-base-local*)
*mgs-count-local*))
(defun ms-no-moves ()
"Determine if no moves exist for the current position"
(let* ((no-moves t))
(generate-psuedolegal)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0)) ((or (not no-moves) (eql index *mgs-count-local*)))
(declare (type fixnum index))
(execute)
(retract)
(if (not (mf-test mfbp-bust))
(setf no-moves nil))
(incf index)
(incf *mgs-current-local*))
no-moves))
(defun ms-matescan ()
"Scan for mates and set checkmate and stalemate flags"
(let* ((limit *mgs-count-local*) (save-current *mgs-current-local*))
(declare (type fixnum limit save-current))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(declare (type fixnum index))
(let* ((no-moves-flag))
(when (not (mf-test mfbp-bust))
(execute)
(setf no-moves-flag (ms-no-moves))
(retract)
(if no-moves-flag
(if (mf-test mfbp-chec)
(mf-set mfbp-chmt)
(mf-set mfbp-stmt))))
(incf *mgs-current-local*)))
(setf *mgs-current-local* save-current)))
(defun ms-disambiguate ()
"Assign rank and file disambiguation flags in the current moveset"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(declare (type fixnum save-index limit))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (i limit)
(declare (type fixnum i))
(let* (
(move0 (aref *mgs* *mgs-current-local*))
(frcp0 (move-frcp move0))
(frp0 (aref mapv-p frcp0)))
(declare (type fixnum frcp0 frp0))
(when (and (not (eql frp0 p-p)) (not (eql frp0 p-k)))
(let*
((frsq0 (move-frsq move0))
(tosq0 (move-tosq move0))
(frr0 (map-rank frsq0))
(frf0 (map-file frsq0))
(pun-frr 0)
(pun-frf 0)
(pun-tosq 0))
(declare (type fixnum frsq0 tosq0 frr0 frf0 pun-frr pun-frf pun-tosq))
(dotimes (j limit)
(declare (type fixnum j))
(let*
((move1 (aref *mgs* (+ j *mgs-base-local*)))
(frcp1 (move-frcp move1))
(frsq1 (move-frsq move1))
(tosq1 (move-tosq move1)))
(declare (type fixnum frcp1 frsq1 tosq1))
(when (and
(eql frcp0 frcp1)
(eql tosq0 tosq1)
(not (eql i j)))
(incf pun-tosq)
(if (eql frr0 (map-rank frsq1))
(incf pun-frr))
(if (eql frf0 (map-file frsq1))
(incf pun-frf)))))
(when (> pun-tosq 0)
(if (or (> pun-frr 0) (and (eql pun-frr 0) (eql pun-frf 0)))
(mf-set mfbp-anfd))
(if (> pun-frf 0)
(mf-set mfbp-anrd))))))
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)))
;;; *** Move location routines
(defun find-san-move (san)
"Return the move stack index of the SAN move in the current set"
(let*
((found nil)
(save-index *mgs-current-local*)
(limit *mgs-count-local*)
(index 0)
(result -1))
(declare (type fixnum save-index limit index result))
(setf *mgs-current-local* *mgs-base-local*)
(do () ((or (eql index limit) found))
(if (string= san (genstr-san (aref *mgs* *mgs-current-local*)))
(setf found t)
(progn
(incf index)
(incf *mgs-current-local*))))
(setf *mgs-current-local* save-index)
(if found
(setf result (+ index *mgs-base-local*)))
result))
(defun ms-find-move (move)
"Return the move stack index of the move in the current set"
(let* ((found nil) (limit *mgs-count-local*) (index 0) (result -1))
(declare (type fixnum limit index result))
(do ((tmove)) ((or (eql index limit) found))
(setf tmove (aref *mgs* (+ index *mgs-base-local*)))
(if
(and
(eql (move-tosq tmove) (move-tosq move))
(eql (move-frcp tmove) (move-frcp move))
(eql (move-frsq tmove) (move-frsq move))
(eql (move-scmv tmove) (move-scmv move))
(eql (move-tocp tmove) (move-tocp move)))
(setf found t)
(incf index)))
(if found
(setf result (+ index *mgs-base-local*)))
result))
(defun ms-find-move2 (frsq tosq)
"Return the move stack index of the first matching move in the current set"
(let*
((found nil)
(limit *mgs-count-local*)
(index 0)
(result -1))
(declare (type fixnum limit index result))
(do ((tmove)) ((or (eql index limit) found))
(setf tmove (aref *mgs* (+ index *mgs-base-local*)))
(if
(and
(eql (move-tosq tmove) tosq)
(eql (move-frsq tmove) frsq))
(setf found t)
(incf index)))
(if found
(setf result (+ index *mgs-base-local*)))
result))
;;; *** Move flags access routines
(declaim (inline mf-set))
(defun mf-set (bitpos)
"Set the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logior flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-clear))
(defun mf-clear (bitpos)
"Clear the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logandc2 flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-toggle))
(defun mf-toggle (bitpos)
"Toggle the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logxor flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-test))
(defun mf-test (bitpos)
"Test the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(logbitp bitpos (move-mflg (aref *mgs* *mgs-current-local*))))
;;; *** SAN (Standard Algebraic Notation) routines
(defun genstr-san (move)
"Return the SAN (Standard Algebraic Notation) string for a move"
(let*
((san "")
(frsq (move-frsq move))
(tosq (move-tosq move))
(frcp (move-frcp move))
(tocp (move-tocp move))
(scmv (move-scmv move))
(mflg (move-mflg move))
(frfile (map-file frsq))
(frrank (map-rank frsq))
(torank (map-rank tosq)))
(if (logbitp mfbp-bust mflg)
(setf san (strcat san "*")))
(cond
((eql scmv scmv-reg)
(if (eql (aref mapv-p frcp) p-p)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq))))))
(progn
(setf san (strcat san (aref p-strings (aref mapv-p frcp))))
(if (logbitp mfbp-anfd mflg)
(setf san (strcat san (aref file-strings frfile))))
(if (logbitp mfbp-anrd mflg)
(setf san (strcat san (aref rank-strings frrank))))
(if (not (eql tocp cp-v0))
(setf san (strcat san "x")))
(setf san (strcat san (aref sq-strings tosq))))))
((eql scmv scmv-cks)
(setf san (strcat san (aref fc-strings flank-k))))
((eql scmv scmv-cqs)
(setf san (strcat san (aref fc-strings flank-q))))
((eql scmv scmv-epc)
(progn
(setf san (strcat san (aref file-strings frfile)))
(setf san (strcat san "x")))
(setf san (strcat san (aref sq-strings tosq))))
((eql scmv scmv-ppn)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-n)))))
((eql scmv scmv-ppb)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-b)))))
((eql scmv scmv-ppr)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-r)))))
((eql scmv scmv-ppq)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-q))))))
(if (logbitp mfbp-chec mflg)
(if (logbitp mfbp-chmt mflg)
(setf san (strcat san "#"))
(setf san (strcat san "+"))))
san))
;;; *** Re-initialization routines (may be called more than once)
(defun new-game ()
"Initialize for a new game"
(clear-position)
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* (logior cflg-wk cflg-wq cflg-bk cflg-bq))
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1)
(square-set sq-a1 cp-wr)
(square-set sq-b1 cp-wn)
(square-set sq-c1 cp-wb)
(square-set sq-d1 cp-wq)
(square-set sq-e1 cp-wk)
(square-set sq-f1 cp-wb)
(square-set sq-g1 cp-wn)
(square-set sq-h1 cp-wr)
(square-set sq-a2 cp-wp)
(square-set sq-b2 cp-wp)
(square-set sq-c2 cp-wp)
(square-set sq-d2 cp-wp)
(square-set sq-e2 cp-wp)
(square-set sq-f2 cp-wp)
(square-set sq-g2 cp-wp)
(square-set sq-h2 cp-wp)
(square-set sq-a7 cp-bp)
(square-set sq-b7 cp-bp)
(square-set sq-c7 cp-bp)
(square-set sq-d7 cp-bp)
(square-set sq-e7 cp-bp)
(square-set sq-f7 cp-bp)
(square-set sq-g7 cp-bp)
(square-set sq-h7 cp-bp)
(square-set sq-a8 cp-br)
(square-set sq-b8 cp-bn)
(square-set sq-c8 cp-bb)
(square-set sq-d8 cp-bq)
(square-set sq-e8 cp-bk)
(square-set sq-f8 cp-bb)
(square-set sq-g8 cp-bn)
(square-set sq-h8 cp-br)
(create))
* * * FEN / EPD ( Forsyth - Edwards Notation / Expanded Position Description ) routines
(defun genstr-ppd ()
"Generate a piece position description string"
(let* ((ppd ""))
(dotimes (aux-rank rank-limit)
(declare (type fixnum aux-rank))
(let* ((rank (- rank-8 aux-rank)) (s 0))
(declare (type fixnum rank s))
(dotimes (file file-limit)
(let* ((sq (map-sq rank file)) (cp (aref *board* sq)))
(declare (type fixnum sq cp))
(if (eql cp cp-v0)
(incf s)
(progn
(if (> s 0)
(progn
(setf ppd (strcat ppd (format nil "~d" s)))
(setf s 0)))
(if (eql (aref mapv-c cp) c-w)
(setf ppd (strcat ppd (aref p-strings (aref mapv-p cp))))
(setf ppd (strcat ppd (aref lcp-strings (aref mapv-p cp)))))))))
(if (> s 0)
(setf ppd (strcat ppd (format nil "~d" s))))
(if (> rank rank-1)
(setf ppd (strcat ppd "/")))))
ppd))
(defun genstr-actc ()
"Generate a string with the active color"
(aref c-strings *actc*))
(defun genstr-cast ()
"Generate a string with the castling availability"
(let* ((cast ""))
(if (eql *cast* 0)
(setf cast (strcat cast "-"))
(progn
(if (logbitp csbp-wk *cast*)
(setf cast (strcat cast (aref p-strings p-k))))
(if (logbitp csbp-wq *cast*)
(setf cast (strcat cast (aref p-strings p-q))))
(if (logbitp csbp-bk *cast*)
(setf cast (strcat cast (aref lcp-strings p-k))))
(if (logbitp csbp-bq *cast*)
(setf cast (strcat cast (aref lcp-strings p-q))))))
cast))
(defun genstr-epsq ()
"Generate a string with the en passant target square"
(let* ((epsq ""))
(if (eql *epsq* sq-nil)
(setf epsq "-")
(setf epsq (aref sq-strings *epsq*)))
epsq))
(defun genstr-hmvc ()
"Generate a string with the halfmove count"
(format nil "~d" *hmvc*))
(defun genstr-fmvn ()
"Generate a string with the fullmove number"
(format nil "~d" *fmvn*))
(defun genstr-fen ()
"Generate a FEN string for the current position"
(let* ((fen ""))
(setf fen (strcat fen (genstr-ppd)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-actc)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-cast)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-epsq)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-hmvc)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-fmvn)))
fen))
;;; *** Position status routines
(defun in-check ()
"Determine if the active color is in check"
(if (eql *actc* c-w)
(not (equal (bit-and (aref *cpbbv* cp-wk) (aref *acbbv* c-b)) null-bb))
(not (equal (bit-and (aref *cpbbv* cp-bk) (aref *acbbv* c-w)) null-bb))))
(defun busted ()
"Determine if the passive color is in check"
(if (eql *pasc* c-w)
(not (equal (bit-and (aref *cpbbv* cp-wk) (aref *acbbv* c-b)) null-bb))
(not (equal (bit-and (aref *cpbbv* cp-bk) (aref *acbbv* c-w)) null-bb))))
(defun valid-position ()
"Determine if the position is valid"
(let*
((valid t)
(count-cpv (make-array rcp-limit :initial-element 0))
(count-cv (make-array rc-limit :initial-element 0))
(count-scpv (make-array `(,rc-limit ,rp-limit) :initial-element 0))
(extra-pawns (make-array rc-limit :initial-element 0)))
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref count-cpv cp) (count 1 (aref *cpbbv* cp))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref count-cv c) (count 1 (aref *c0bbv* c))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(dotimes (p rp-limit)
(declare (type fixnum p))
(setf (aref count-scpv c p)
(count 1 (aref *cpbbv* (aref mapv-cp c p))))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref extra-pawns c) (- 8 (aref count-scpv c p-p))))
(when valid
(if
(or
(< (aref count-cv c-w) 1) (> (aref count-cv c-w) 16)
(< (aref count-cv c-b) 1) (> (aref count-cv c-b) 16))
(setf valid nil)))
(when valid
(if
(or
(not (eql (aref count-cpv cp-wk) 1))
(not (eql (aref count-cpv cp-bk) 1))
(> (aref count-cpv cp-wp) 8)
(> (aref count-cpv cp-bp) 8))
(setf valid nil)))
(when valid
(if (not (equal
(bit-and
(bit-ior (aref *cpbbv* cp-wp) (aref *cpbbv* cp-bp))
(bit-ior (aref debbv dx-1) (aref debbv dx-3)))
null-bb))
(setf valid nil)))
(when valid
(dotimes (c rc-limit)
(if (> (aref count-scpv c p-n) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-n) 2)))
(if (> (aref count-scpv c p-b) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-b) 2)))
(if (> (aref count-scpv c p-r) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-r) 2)))
(if (> (aref count-scpv c p-q) 1)
(decf (aref extra-pawns c) (- (aref count-scpv c p-q) 1))))
(if (or (< (aref extra-pawns c-w) 0) (< (aref extra-pawns c-b) 0))
(setf valid nil)))
(when valid
(if (logbitp csbp-wk *cast*)
(if (or
(not (eql (aref *board* sq-e1) cp-wk))
(not (eql (aref *board* sq-h1) cp-wr)))
(setf valid nil))))
(when valid
(if (logbitp csbp-wq *cast*)
(if (or
(not (eql (aref *board* sq-e1) cp-wk))
(not (eql (aref *board* sq-a1) cp-wr)))
(setf valid nil))))
(when valid
(if (logbitp csbp-bk *cast*)
(if (or
(not (eql (aref *board* sq-e8) cp-bk))
(not (eql (aref *board* sq-h8) cp-br)))
(setf valid nil))))
(when valid
(if (logbitp csbp-bq *cast*)
(if (or
(not (eql (aref *board* sq-e8) cp-bk))
(not (eql (aref *board* sq-a8) cp-br)))
(setf valid nil))))
(when valid
(if (and (not (eql *epsq* sq-nil)) (eql *actc* c-w))
(if
(or
(not (eql (map-rank *epsq*) rank-6))
(not (eql (aref *board* *epsq*) cp-v0))
(not (eql (aref *board* (+ *epsq* dv-3)) cp-bp))
(not (eql (aref *board* (+ *epsq* dv-1)) cp-v0)))
(setf valid nil))))
(when valid
(if (and (not (eql *epsq* sq-nil)) (eql *actc* c-b))
(if
(or
(not (eql (map-rank *epsq*) rank-3))
(not (eql (aref *board* *epsq*) cp-v0))
(not (eql (aref *board* (+ *epsq* dv-1)) cp-wp))
(not (eql (aref *board* (+ *epsq* dv-3)) cp-v0)))
(setf valid nil))))
(when valid
(if (< *hmvc* 0) (setf valid nil)))
(when valid
(if (< *fmvn* 1) (setf valid nil)))
(when valid
(if (busted) (setf valid nil)))
valid))
(defun checkmated ()
"Determine if the active side is checkmated"
(and (in-check) (ms-no-moves)))
(defun stalemated ()
"Determine if the active side is stalemated"
(and (not (in-check)) (ms-no-moves)))
;;; *** Play/unplay routines (played move history access and internal state update)
(defun play-move (san)
"Play the given move (a SAN string) in the game"
(let* ((index (find-san-move san)))
(declare (type fixnum index))
(if (< index 0)
(error "Move not found")
(progn
(history-push)
(setf *mgs-current-local* index)
(execute)
(decf *ply*)
(clear-move-generation)
(generate)))))
(defun unplay-move ()
"Unplay the a move in the game"
(if (< *gmh-count* 1)
(error "Can't unplay non-existent move")
(history-pop)))
;;; *** Mapping functions for files, ranks, and squares
(declaim (inline map-file))
(defun map-file (sq)
"Map a square to its file"
(declare (type fixnum sq))
(the fixnum (logand sq 7)))
(declaim (inline map-rank))
(defun map-rank (sq)
"Map a square to its rank"
(declare (type fixnum sq))
(the fixnum (ash sq -3)))
(declaim (inline map-sq))
(defun map-sq (rank file)
"Map a rank and a file to a square"
(declare (type fixnum rank file))
(the fixnum (logior (the fixnum (ash rank 3)) file)))
;;; *** Routines for simple display output
(defun file-print-path ()
"Print the move path to the current position onto the filepath stream"
(dotimes (ply *ply*)
(if (not (eql ply 0))
(format *pathway-file-stream* " "))
(format *pathway-file-stream* "~a"
(genstr-san (aref *mgs* (aref *mgs-current* ply)))))
(format *pathway-file-stream* "~%")
(values))
(defun print-board ()
"Print the board (eight lines long)"
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(dotimes (file file-limit)
(declare (type fixnum file))
(let* ((sq (map-sq (- rank-8 rank) file)) (cp (aref *board* sq)))
(declare (type fixnum sq cp))
(if (eql cp cp-v0)
(if (eql (logand file 1) (logand rank 1))
(format t " ")
(format t "::"))
(format t "~a" (aref cp-strings cp)))))
(format t "~%"))
(values))
;;; *** Fixed depth pathway enumeration; used for testing
(defun pathway-enumerate (depth)
"Enumerate the pathways of the current position to the given ply depth"
(declare (type fixnum depth))
(let* ((sum 0) (limit 0))
(declare (type fixnum sum limit))
(if (eql depth 0)
(progn
(setf sum 1)
(if *pathway-file-stream*
(file-print-path)))
(progn
(generate-psuedolegal)
(setf limit (+ *mgs-base-local* *mgs-count-local*))
(do* ((index *mgs-base-local*)) ((eql index limit))
(declare (type fixnum index))
(setf *mgs-current-local* index)
(execute)
(if (not (busted))
(incf sum (pathway-enumerate (- depth 1))))
(retract)
(incf index))))
sum))
;;; *** Program function verification via pathway enumeration
(defun verify-enumeration (depth count)
"Enumerate pathways to the given depth and check the count"
(declare (type fixnum depth count))
(let* ((sum))
(declare (type fixnum sum))
(format t "Enumerating to depth ~R; please wait~%" depth)
(setf sum (pathway-enumerate depth))
(format t "Calculated count: ~d Expected count: ~d " sum count)
(if (eql sum count)
(format t "Operation verified~%")
(format t "Operation *failed*~%"))
(eql sum count)))
;;; *** Simple user interface routines
(defun ui-init ()
"Initialization; must be called before any other functions"
(initialize)
(values))
(defun ui-play (san)
"Play a SAN (string) move with update of the game history"
(play-move san)
(values))
(defun ui-unpl ()
"Unplay (reverse of ui-play) the previous played move"
(unplay-move)
(values))
(defun ui-cvsq (sq)
"Clear value: square"
(when (not (eql (aref *board* sq) cp-v0))
(square-clear sq)
(create))
(values))
(defun ui-cvcb ()
"Clear value: chessboard"
(dotimes (sq sq-limit)
(if (not (eql (aref *board* sq) cp-v0))
(square-clear sq)))
(setf *cast* 0)
(setf *epsq* sq-nil)
(create)
(values))
(defun ui-svsq (sq cp)
"Set value: square"
(when (not (eql (aref *board* sq) cp))
(if (not (eql (aref *board* sq) cp-v0))
(square-clear sq))
(square-set sq cp)
(create))
(values))
(defun ui-svac (c)
"Set value: active color"
(when (not (eql c *actc*))
(setf *actc* c)
(setf *pasc* (aref invc-v c))
(create))
(values))
(defun ui-svca (cast)
"Set value: castling availability"
(when (not (eql cast *cast*))
(setf *cast* cast)
(create))
(values))
(defun ui-svep (epsq)
"Set value: en passant target square"
(when (not (eql epsq *epsq*))
(setf *epsq* epsq)
(create))
(values))
(defun ui-svhc (hmvc)
"Set value: halfmove clock"
(when (not (eql hmvc *hmvc*))
(setf *hmvc* hmvc)
(create))
(values))
(defun ui-svfn (fmvn)
"Set value: fullmove number"
(when (not (eql fmvn *fmvn*))
(setf *fmvn* fmvn)
(create))
(values))
(defun ui-dvfe ()
"Display value: Forsyth-Edwards Notation"
(format t "~a~%" (genstr-fen))
(values))
(defun ui-dvcb ()
"Display value: chessboard"
(print-board)
(values))
(defun ui-dvms ()
"Display value: moveset"
(if (valid-position)
(let* ((movelist (copy-list (fetch-move-strings-at-base))))
(cond
((eql *mgs-count-local* 0)
(format t "There are no moves.~%")
(if (checkmated)
(format t "~a is checkmated.~%"
(aref player-strings *actc*))
(if (stalemated)
(format t "~a is stalemated.~%"
(aref player-strings *actc*)))))
((eql *mgs-count-local* 1)
(format t "There is one move: ~a~%" (car movelist)))
(t
(setf movelist (sort movelist #'string<))
(format t "There are ~R moves:" *mgs-count-local*)
(dolist (pmove movelist)
(format t " ~a" pmove))
(format t "~%"))))
(format t "Invalid position; there are no moves.~%"))
(values))
(defun ui-newg ()
"Set up a new game"
(new-game)
(values))
(defun ui-enum (n)
"Enumerate distinct pathways N plies deep"
(let* ((count 0))
(if (not (valid-position))
(format t "Can't enumerate from invalid position.~%")
(progn
(setf count (pathway-enumerate n))
(format t "Pathway count: ~R~%" count))))
(values))
(defun ui-test ()
"Perform simple program validity testing via pathway enumeration"
(new-game)
(verify-enumeration 0 1)
(verify-enumeration 1 20)
(verify-enumeration 2 400)
(verify-enumeration 3 8902)
(verify-enumeration 4 197281)
(verify-enumeration 5 4865609)
(values))
;;; *** Simple forced mate locator programming example: fms1
(defun fms1-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms1-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms1-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(execute)
(if (not (busted))
(setf result (not (fms1-search-defend (- n 1)))))
(retract)
(when (not result)
(incf *mgs-current-local*)
(incf index)))
result))
(defun fms1-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(execute)
(if (not (busted))
(setf result (not (fms1-search-attack n))))
(retract)
(when (not result)
(incf *mgs-current-local*)
(incf index)))))
result))
;;; *** Simple forced mate locator programming example: fms2
(defvar *fms2-killers* (make-array ply-limit))
(defun fms2-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *fms2-killers* index) (copy-move empty-move)))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms2-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms2-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(setf killer-index (ms-find-move (aref *fms2-killers* *ply*)))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(if (not (busted))
(setf result (not (fms2-search-defend (- n 1)))))
(retract))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms2-search-defend (- n 1)))))
(retract)
(if result
(setf (aref *fms2-killers* *ply*)
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))
result))
(defun fms2-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(setf killer-index (ms-find-move (aref *fms2-killers* *ply*)))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(if (not (busted))
(setf result (not (fms2-search-attack n))))
(retract))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms2-search-attack n))))
(retract)
(if result
(setf (aref *fms2-killers* *ply*)
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))))
result))
* * * Simple forced mate locator programming example : fms3
(defvar *fms3-killers* (make-array `(,rc-limit ,sq-limit ,sq-limit)))
(defun fms3-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(dotimes (c rc-limit)
(declare (type fixnum c))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref *fms3-killers* c sq0 sq1) (copy-move empty-move)))))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms3-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms3-prev-frsq ()
"Return the frsq of the previous move"
(move-frsq (aref *mgs* (aref *mgs-current* (- *ply* 1)))))
(defun fms3-prev-tosq ()
"Return the tosq of the previous move"
(move-tosq (aref *mgs* (aref *mgs-current* (- *ply* 1)))))
(defun fms3-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(when (> *ply* 0)
(setf killer-index (ms-find-move
(aref *fms3-killers*
*actc* (fms3-prev-frsq) (fms3-prev-tosq))))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(when (not (busted))
(setf result (not (fms3-search-defend (- n 1)))))
(retract)))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms3-search-defend (- n 1)))))
(retract)
(if (and result (> *ply* 0))
(setf (aref *fms3-killers* *actc* (fms3-prev-frsq) (fms3-prev-tosq))
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))
result))
(defun fms3-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(when (> *ply* 0)
(setf killer-index (ms-find-move
(aref *fms3-killers*
*actc* (fms3-prev-frsq) (fms3-prev-tosq))))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(when (not (busted))
(setf result (not (fms3-search-attack n))))
(retract)))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms3-search-attack n))))
(retract)
(if (and result (> *ply* 0))
(setf (aref *fms3-killers* *actc* (fms3-prev-frsq) (fms3-prev-tosq))
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))))
result))
cil.lsp : EOF
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/games/cil/cil.lisp | lisp | cil.lsp: Chess In Lisp foundation programming toolkit
toolkit. It contains the core processing functions needed to perform
research in the chess domain using Lisp.
Global optimization options
--- Constants -----------------------------------------------
Colors
white
black
vacant
extra
Pieces
pawn
knight
bishop
rook
queen
king
vacant
extra
white
white
white
white
white
white
black
black
black
black
black
black
vacant
extra
extra extra
extra extra extra
Edge limit
Ranks
first rank
eighth rank
Files
queen rook file
queen knight file
queen bishop file
queen file
king file
king bishop file
king knight file
Squares
east
north
west
south
northeast
northwest
southwest
southeast
east by northeast
north by northeast
north by northwest
west by northwest
west by southwest
south by southwest
south by southeast
east by southeast
Directional rank deltas
Directional file deltas
Directional offsets
Flanks
kingside
queenside
Castling status bit positions
Special case move indications
regular
castle kingside
castle queenside
en passant capture
pawn promotes to a knight
pawn promotes to a bishop
pawn promotes to a rook
pawn promotes to a queen
Move flag type bit positions
algebraic notation needs file disambiguation
algebraic notation needs rank disambiguation
illegal move
checking move, including checkmating
checkmating move
executed move
null move
searched move
stalemating move
Move structure
from square
to square
from color-piece
to color-piece
special case indication
move flags
The null move
The empty move
PGN Seven Tag Roster
PGN Site
game termination indicators
White wins
Black wins
drawn
unknown or not specified
Ply search depth limit
Game full move history limit (maximum full moves per game)
The null bitboard
Directional edge bitboard vector (dx0..dx7)
Directional scanning array of lists of squares
Sum of ray/knight distances for all squares and all directions
Squares along a ray/knight (indexed by ds-offsets)
Directional locator; gives direction from sq0 to sq1
On-board-next; check for continuing along a direction from a square
Interpath squares bitboard array
King moves bitboard vector (sq-a1..sq-h8)
Centipawn material evaluations (can be tuned)
pawn
knight
bishop
rook
queen
king
--- Variables -----------------------------------------------
active color
castling availability
en passant target square
full move number
PIV: Ply Indexed Variables
[PIV] The current ply, used as an index for several variables
[PIV] The move generation stack
start of moves for a ply )
local for this ply (direct index to *mgs*)
current move in ply )
local for this ply (direct index to *mgs*)
number of moves per ply )
local value for this ply
GHV: Game History Variables
the master index for the GHV set ( )
[GHV] Moves in history
[GHV] Active colors in history
[GHV] Castling availabilities in history
[GHV] En passant target squares in history
[GHV] Halfmove clocks in history
[GHV] Fullmove numbers in history
Counters
Files
--- Functions -----------------------------------------------
*** Attack bitboard database management functions
*** Square set/clear interface routines to the attack bitboard managament functions
*** Various reset routines for the internal database variables
*** Helper routines for board/square access
*** Various initialization routines; each called only once
*** Printing and string generation routines for bitboard items
*** Debugging output routines for bitboard items
*** Debugging output routines for various tests
*** Game history status routines
*** Move execution and retraction routines
*** Move generation routines
*** Move location routines
*** Move flags access routines
*** SAN (Standard Algebraic Notation) routines
*** Re-initialization routines (may be called more than once)
*** Position status routines
*** Play/unplay routines (played move history access and internal state update)
*** Mapping functions for files, ranks, and squares
*** Routines for simple display output
*** Fixed depth pathway enumeration; used for testing
*** Program function verification via pathway enumeration
*** Simple user interface routines
*** Simple forced mate locator programming example: fms1
*** Simple forced mate locator programming example: fms2 |
Revised : 1997.06.08
Send comments to : ( )
This source file is the foundation of the Chess In Lisp programming
(declaim
(optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)))
(defconstant c-limit 4)
(defconstant rc-limit 2)
(defconstant c-nil -1)
(defparameter c-strings
(make-array c-limit
:initial-contents '("w" "b" " " "?")))
(defparameter color-strings
(make-array rc-limit
:initial-contents '("white" "black")))
(defparameter player-strings
(make-array rc-limit
:initial-contents '("White" "Black")))
(defparameter invc-v
(make-array rc-limit
:element-type 'fixnum
:initial-contents `(,c-b ,c-w)))
(defconstant p-limit 8)
(defconstant rp-limit 6)
(defconstant p-nil -1)
(defparameter p-strings
(make-array p-limit
:initial-contents '("P" "N" "B" "R" "Q" "K" " " "?")))
(defparameter piece-strings
(make-array rp-limit
:initial-contents
'("pawn" "knight" "bishop" "rook" "queen" "king")))
(defparameter lcp-strings
(make-array p-limit
:initial-contents '("p" "n" "b" "r" "q" "k" " " "?")))
Color - pieces
(defconstant cp-limit 16)
(defconstant rcp-limit 12)
(defconstant cp-nil -1)
(defparameter cp-strings
(make-array cp-limit
:initial-contents
'("wP" "wN" "wB" "wR" "wQ" "wK"
"bP" "bN" "bB" "bR" "bQ" "bK"
" " "??" "?1" "?2")))
(defparameter mapv-c
(make-array cp-limit
:element-type 'fixnum
:initial-contents
`(,c-w ,c-w ,c-w ,c-w ,c-w ,c-w
,c-b ,c-b ,c-b ,c-b ,c-b ,c-b
,c-v ,c-x ,c-x ,c-x)))
(defparameter mapv-p
(make-array cp-limit
:element-type 'fixnum
:initial-contents
`(,p-p ,p-n ,p-b ,p-r ,p-q ,p-k
,p-p ,p-n ,p-b ,p-r ,p-q ,p-k
,p-v ,p-x ,p-x ,p-x)))
(defparameter mapv-cp
(make-array `(,rc-limit ,rp-limit)
:element-type 'fixnum
:initial-contents
`((,cp-wp ,cp-wn ,cp-wb ,cp-wr ,cp-wq ,cp-wk)
(,cp-bp ,cp-bn ,cp-bb ,cp-br ,cp-bq ,cp-bk))))
(defparameter sweeper-cp
(make-array rcp-limit
:element-type 'fixnum
:initial-contents
'(0 0 1 1 1 0 0 0 1 1 1 0)))
(defparameter edge-limit 8)
(defparameter rank-limit edge-limit)
(defconstant rank-nil -1)
second rank
third rank
fourth rank
fifth rank
sixth rank
seventh rank
(defparameter rank-strings
(make-array rank-limit
:initial-contents '("1" "2" "3" "4" "5" "6" "7" "8")))
(defparameter file-limit edge-limit)
(defconstant file-nil -1)
king rook file
(defparameter file-strings
(make-array file-limit
:initial-contents '("a" "b" "c" "d" "e" "f" "g" "h")))
(defparameter sq-limit (* rank-limit file-limit))
(defconstant sq-nil -1)
(defparameter sq-a1 (+ file-a (* rank-1 file-limit)))
(defparameter sq-b1 (+ file-b (* rank-1 file-limit)))
(defparameter sq-c1 (+ file-c (* rank-1 file-limit)))
(defparameter sq-d1 (+ file-d (* rank-1 file-limit)))
(defparameter sq-e1 (+ file-e (* rank-1 file-limit)))
(defparameter sq-f1 (+ file-f (* rank-1 file-limit)))
(defparameter sq-g1 (+ file-g (* rank-1 file-limit)))
(defparameter sq-h1 (+ file-h (* rank-1 file-limit)))
(defparameter sq-a2 (+ file-a (* rank-2 file-limit)))
(defparameter sq-b2 (+ file-b (* rank-2 file-limit)))
(defparameter sq-c2 (+ file-c (* rank-2 file-limit)))
(defparameter sq-d2 (+ file-d (* rank-2 file-limit)))
(defparameter sq-e2 (+ file-e (* rank-2 file-limit)))
(defparameter sq-f2 (+ file-f (* rank-2 file-limit)))
(defparameter sq-g2 (+ file-g (* rank-2 file-limit)))
(defparameter sq-h2 (+ file-h (* rank-2 file-limit)))
(defparameter sq-a3 (+ file-a (* rank-3 file-limit)))
(defparameter sq-b3 (+ file-b (* rank-3 file-limit)))
(defparameter sq-c3 (+ file-c (* rank-3 file-limit)))
(defparameter sq-d3 (+ file-d (* rank-3 file-limit)))
(defparameter sq-e3 (+ file-e (* rank-3 file-limit)))
(defparameter sq-f3 (+ file-f (* rank-3 file-limit)))
(defparameter sq-g3 (+ file-g (* rank-3 file-limit)))
(defparameter sq-h3 (+ file-h (* rank-3 file-limit)))
(defparameter sq-a4 (+ file-a (* rank-4 file-limit)))
(defparameter sq-b4 (+ file-b (* rank-4 file-limit)))
(defparameter sq-c4 (+ file-c (* rank-4 file-limit)))
(defparameter sq-d4 (+ file-d (* rank-4 file-limit)))
(defparameter sq-e4 (+ file-e (* rank-4 file-limit)))
(defparameter sq-f4 (+ file-f (* rank-4 file-limit)))
(defparameter sq-g4 (+ file-g (* rank-4 file-limit)))
(defparameter sq-h4 (+ file-h (* rank-4 file-limit)))
(defparameter sq-a5 (+ file-a (* rank-5 file-limit)))
(defparameter sq-b5 (+ file-b (* rank-5 file-limit)))
(defparameter sq-c5 (+ file-c (* rank-5 file-limit)))
(defparameter sq-d5 (+ file-d (* rank-5 file-limit)))
(defparameter sq-e5 (+ file-e (* rank-5 file-limit)))
(defparameter sq-f5 (+ file-f (* rank-5 file-limit)))
(defparameter sq-g5 (+ file-g (* rank-5 file-limit)))
(defparameter sq-h5 (+ file-h (* rank-5 file-limit)))
(defparameter sq-a6 (+ file-a (* rank-6 file-limit)))
(defparameter sq-b6 (+ file-b (* rank-6 file-limit)))
(defparameter sq-c6 (+ file-c (* rank-6 file-limit)))
(defparameter sq-d6 (+ file-d (* rank-6 file-limit)))
(defparameter sq-e6 (+ file-e (* rank-6 file-limit)))
(defparameter sq-f6 (+ file-f (* rank-6 file-limit)))
(defparameter sq-g6 (+ file-g (* rank-6 file-limit)))
(defparameter sq-h6 (+ file-h (* rank-6 file-limit)))
(defparameter sq-a7 (+ file-a (* rank-7 file-limit)))
(defparameter sq-b7 (+ file-b (* rank-7 file-limit)))
(defparameter sq-c7 (+ file-c (* rank-7 file-limit)))
(defparameter sq-d7 (+ file-d (* rank-7 file-limit)))
(defparameter sq-e7 (+ file-e (* rank-7 file-limit)))
(defparameter sq-f7 (+ file-f (* rank-7 file-limit)))
(defparameter sq-g7 (+ file-g (* rank-7 file-limit)))
(defparameter sq-h7 (+ file-h (* rank-7 file-limit)))
(defparameter sq-a8 (+ file-a (* rank-8 file-limit)))
(defparameter sq-b8 (+ file-b (* rank-8 file-limit)))
(defparameter sq-c8 (+ file-c (* rank-8 file-limit)))
(defparameter sq-d8 (+ file-d (* rank-8 file-limit)))
(defparameter sq-e8 (+ file-e (* rank-8 file-limit)))
(defparameter sq-f8 (+ file-f (* rank-8 file-limit)))
(defparameter sq-g8 (+ file-g (* rank-8 file-limit)))
(defparameter sq-h8 (+ file-h (* rank-8 file-limit)))
(defparameter sq-strings
(make-array sq-limit
:initial-contents
'(
"a1" "b1" "c1" "d1" "e1" "f1" "g1" "h1"
"a2" "b2" "c2" "d2" "e2" "f2" "g2" "h2"
"a3" "b3" "c3" "d3" "e3" "f3" "g3" "h3"
"a4" "b4" "c4" "d4" "e4" "f4" "g4" "h4"
"a5" "b5" "c5" "d5" "e5" "f5" "g5" "h5"
"a6" "b6" "c6" "d6" "e6" "f6" "g6" "h6"
"a7" "b7" "c7" "d7" "e7" "f7" "g7" "h7"
"a8" "b8" "c8" "d8" "e8" "f8" "g8" "h8")))
Directions : 4 orthogonal , 4 diagonal , 8 knight
(defconstant dx-limit 16)
(defconstant rdx-limit 8)
(defconstant dx-nil -1)
(defconstant dr-0 0)
(defconstant dr-1 1)
(defconstant dr-2 0)
(defconstant dr-3 -1)
(defconstant dr-4 1)
(defconstant dr-5 1)
(defconstant dr-6 -1)
(defconstant dr-7 -1)
(defconstant dr-8 1)
(defconstant dr-9 2)
(defconstant dr-a 2)
(defconstant dr-b 1)
(defconstant dr-c -1)
(defconstant dr-d -2)
(defconstant dr-e -2)
(defconstant dr-f -1)
(defparameter mapv-dr
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,dr-0 ,dr-1 ,dr-2 ,dr-3 ,dr-4 ,dr-5 ,dr-6 ,dr-7
,dr-8 ,dr-9 ,dr-a ,dr-b ,dr-c ,dr-d ,dr-e ,dr-f)))
(defconstant df-0 1)
(defconstant df-1 0)
(defconstant df-2 -1)
(defconstant df-3 0)
(defconstant df-4 1)
(defconstant df-5 -1)
(defconstant df-6 -1)
(defconstant df-7 1)
(defconstant df-8 2)
(defconstant df-9 1)
(defconstant df-a -1)
(defconstant df-b -2)
(defconstant df-c -2)
(defconstant df-d -1)
(defconstant df-e 1)
(defconstant df-f 2)
(defparameter mapv-df
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,df-0 ,df-1 ,df-2 ,df-3 ,df-4 ,df-5 ,df-6 ,df-7
,df-8 ,df-9 ,df-a ,df-b ,df-c ,df-d ,df-e ,df-f)))
(defparameter dv-0 (+ df-0 (* rank-limit dr-0)))
(defparameter dv-1 (+ df-1 (* rank-limit dr-1)))
(defparameter dv-2 (+ df-2 (* rank-limit dr-2)))
(defparameter dv-3 (+ df-3 (* rank-limit dr-3)))
(defparameter dv-4 (+ df-4 (* rank-limit dr-4)))
(defparameter dv-5 (+ df-5 (* rank-limit dr-5)))
(defparameter dv-6 (+ df-6 (* rank-limit dr-6)))
(defparameter dv-7 (+ df-7 (* rank-limit dr-7)))
(defparameter dv-8 (+ df-8 (* rank-limit dr-8)))
(defparameter dv-9 (+ df-9 (* rank-limit dr-9)))
(defparameter dv-a (+ df-a (* rank-limit dr-a)))
(defparameter dv-b (+ df-b (* rank-limit dr-b)))
(defparameter dv-c (+ df-c (* rank-limit dr-c)))
(defparameter dv-d (+ df-d (* rank-limit dr-d)))
(defparameter dv-e (+ df-e (* rank-limit dr-e)))
(defparameter dv-f (+ df-f (* rank-limit dr-f)))
(defparameter mapv-dv
(make-array dx-limit
:element-type 'fixnum
:initial-contents
`(,dv-0 ,dv-1 ,dv-2 ,dv-3 ,dv-4 ,dv-5 ,dv-6 ,dv-7
,dv-8 ,dv-9 ,dv-a ,dv-b ,dv-c ,dv-d ,dv-e ,dv-f)))
(defconstant flank-limit 2)
(defconstant flank-nil -1)
Flank castling strings
(defparameter fc-strings
(make-array flank-limit
:initial-contents '("O-O" "O-O-O")))
white KS castling
white QS castling
black KS castling
black QS castling
Castling bitfields
(defconstant cflg-wk (ash 1 csbp-wk))
(defconstant cflg-wq (ash 1 csbp-wq))
(defconstant cflg-bk (ash 1 csbp-bk))
(defconstant cflg-bq (ash 1 csbp-bq))
(defconstant scmv-limit 8)
(defconstant scmv-nil -1)
Move flag type bitfields
(defconstant mflg-anfd (ash 1 mfbp-anfd))
(defconstant mflg-anrd (ash 1 mfbp-anrd))
(defconstant mflg-bust (ash 1 mfbp-bust))
(defconstant mflg-chec (ash 1 mfbp-chec))
(defconstant mflg-chmt (ash 1 mfbp-chmt))
(defconstant mflg-exec (ash 1 mfbp-exec))
(defconstant mflg-null (ash 1 mfbp-null))
(defconstant mflg-srch (ash 1 mfbp-srch))
(defconstant mflg-stmt (ash 1 mfbp-stmt))
(defstruct move
)
(defvar null-move
(make-move :mflg mflg-null))
(defvar empty-move
(make-move))
the Seven Tag Roster
PGN Event
PGN Date
PGN Round
PGN White
PGN Black
PGN Result
(defparameter tag-name-strings
(make-array tag-name-limit
:initial-contents
`("Event" "Site" "Date" "Round" "White" "Black" "Result")))
(defconstant gtim-limit 4)
(defconstant gtim-nil -1)
(defparameter gtim-strings
(make-array gtim-limit
:initial-contents '("1-0" "0-1" "1/2-1/2" "*")))
Fifty move draw rule limit
(defconstant fmrfmv-limit 50)
(defconstant fmrhmv-limit (* fmrfmv-limit rc-limit))
(defconstant ply-limit 64)
(defconstant gfmh-limit 200)
Game half move history limit ( maximum half moves per game )
(defconstant ghmh-limit (* gfmh-limit rc-limit))
(defparameter null-bb
(make-array sq-limit
:element-type 'bit
:initial-element 0))
(defvar debbv
(make-array rdx-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
(defvar ds-offsets
(make-array `(,dx-limit ,sq-limit)
:element-type 'fixnum
:initial-element 0))
(defconstant ds-square-limit 2816)
(defvar ds-squares
(make-array ds-square-limit
:element-type 'fixnum
:initial-element 0))
(defvar dloc
(make-array `(,sq-limit ,sq-limit)
:element-type 'fixnum
:initial-element dx-nil))
(defvar obnext
(make-array `(,dx-limit ,sq-limit)
:element-type t
:initial-element nil))
(defvar ipbbv
(make-array `(,sq-limit ,sq-limit)
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
Knight moves bitboard vector ( sq - a1 .. sq - h8 )
(defvar nmbbv
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
(defvar kmbbv
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
(defparameter cpe-pv
(make-array rp-limit
:element-type 'fixnum
:initial-contents
`(,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k)))
(defparameter cpe-cpv
(make-array rcp-limit
:element-type 'fixnum
:initial-contents
`(,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k
,cpe-p ,cpe-n ,cpe-b ,cpe-r ,cpe-q ,cpe-k)))
IDV : Internal Database Variables ( must keep mutually synchronized )
[ IDV ] The board
(declaim (type (simple-array fixnum 64) *board*))
(defvar *board*
(make-array sq-limit
:element-type 'fixnum
:initial-element cp-v0))
[ IDV ] Current status items ( included in Forsyth - Edwards Notation )
(declaim (type fixnum *actc*))
(declaim (type fixnum *pasc*))
(declaim (type fixnum *cast*))
(declaim (type fixnum *epsq*))
(declaim (type fixnum *hmvc*))
(declaim (type fixnum *fmvn*))
passive color ( not used in FEN )
half move clock
[ IDV ] Color - piece occupancy bitboard vector ( cp - wp .. cp - bk )
(defvar *cpbbv*
(make-array rcp-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Color occupancy bitboard vector ( unions of * cpbbv * by color )
(defvar *c0bbv*
(make-array rc-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] All men merged ( union of * c0bbv * )
(defvar *ammbb*
(make-array sq-limit
:element-type 'bit
:initial-element 0))
[ IDV ] Attack to by color bitboard vector ( c - w .. c - b )
(defvar *acbbv*
(make-array rc-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Attack to by ( sq - a1 .. sq - h8 )
(defvar *atbbv*
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
[ IDV ] Attack from by ( sq - a1 .. sq - h8 )
(defvar *afbbv*
(make-array sq-limit
:element-type `(simple-bit-vector ,sq-limit)
:initial-element null-bb))
(declaim (type fixnum *ply*))
(defvar *ply* 0)
average of 64 moves per ply
(defvar *mgs* (make-array mgs-limit :element-type 'move))
(declaim (type fixnum *mgs-base-local*))
(defvar *mgs-base*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
(declaim (type fixnum *mgs-current-local*))
(defvar *mgs-current*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
(declaim (type fixnum *mgs-count-local*))
(defvar *mgs-count*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS castling ( indicates castling status at ply )
(defvar *mgs-cast*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS ep targets ( indicates ep target at ply )
(defvar *mgs-epsq*
(make-array ply-limit
:element-type 'fixnum
:initial-element sq-nil))
[ PIV ] The MGS halfmove clocks ( indicates hmvc at ply )
(defvar *mgs-hmvc*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
[ PIV ] The MGS fullmove numbers ( indicates fmvn at ply )
(defvar *mgs-fmvn*
(make-array ply-limit
:element-type 'fixnum
:initial-element 0))
(declaim (type fixnum *gmh-count*))
(defvar *gmh-count* 0)
(defvar *gmh-move* (make-array ghmh-limit :element-type 'move))
[ GHV ] Boards in history
(defvar *gmh-board* (make-array ghmh-limit))
(defvar *gmh-actc* (make-array ghmh-limit :element-type 'fixnum))
(defvar *gmh-cast* (make-array ghmh-limit :element-type 'fixnum))
(defvar *gmh-epsq* (make-array ghmh-limit :element-type 'fixnum))
(defvar *gmh-hmvc* (make-array ghmh-limit :element-type 'fixnum))
(defvar *gmh-fmvn* (make-array ghmh-limit :element-type 'fixnum))
(defvar *count-execute* 0)
(defvar *pathway-file-stream* nil)
(defun attack-add (sq)
"Add attacks for a square; piece already on board"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq))
(c (aref mapv-c cp))
(p (aref mapv-p cp))
(bb (copy-seq null-bb)))
(declare (type fixnum cp c p))
(cond
((eql p p-p)
(if (eql c c-w)
(progn
(if (aref obnext dx-4 sq)
(setf (sbit bb (+ sq dv-4)) 1))
(if (aref obnext dx-5 sq)
(setf (sbit bb (+ sq dv-5)) 1)))
(progn
(if (aref obnext dx-6 sq)
(setf (sbit bb (+ sq dv-6)) 1))
(if (aref obnext dx-7 sq)
(setf (sbit bb (+ sq dv-7)) 1)))))
((eql p p-n)
(setf bb (copy-seq (aref nmbbv sq))))
((eql p p-b)
(do* ((dx dx-4)) ((eql dx dx-8))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-r)
(do* ((dx dx-0)) ((eql dx dx-4))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-q)
(do* ((dx dx-0)) ((eql dx dx-8))
(declare (type fixnum dx))
(let* ((sqdex (aref ds-offsets dx sq)) (rsq (aref ds-squares sqdex)))
(declare (type fixnum sqdex rsq))
(do ()
((or
(eql rsq sq-nil)
(not (eql (aref *board* rsq) cp-v0))))
(setf (sbit bb rsq) 1)
(incf sqdex)
(setf rsq (aref ds-squares sqdex)))
(if (not (eql rsq sq-nil))
(setf (sbit bb rsq) 1)))
(incf dx)))
((eql p p-k)
(setf bb (copy-seq (aref kmbbv sq)))))
(setf (aref *afbbv* sq) (copy-seq bb))
(bit-ior (aref *acbbv* c) bb t)
(do* ((rsq)) ((equal bb null-bb))
(declare (type fixnum rsq))
(setf rsq (position 1 bb))
(setf (sbit (aref *atbbv* rsq) sq) 1)
(setf (sbit bb rsq) 0))))
(defun attack-del (sq)
"Delete attacks for an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq))
(c (aref mapv-c cp))
(bb (copy-seq (aref *afbbv* sq))))
(declare (type fixnum cp c))
(setf (aref *afbbv* sq) (copy-seq null-bb))
(do* ((rsq)) ((equal bb null-bb))
(declare (type fixnum rsq))
(setf rsq (position 1 bb))
(setf (sbit bb rsq) 0)
(setf (sbit (aref *atbbv* rsq) sq) 0)
(if (equal
(bit-and (aref *atbbv* rsq) (aref *c0bbv* c)) null-bb)
(setf (sbit (aref *acbbv* c) rsq) 0)))))
(defun attack-pro (sq)
"Propagate attacks through an empty square"
(declare (type fixnum sq))
(let* ((bb (copy-seq (aref *atbbv* sq))))
(do* ((asq)) ((equal bb null-bb))
(declare (type fixnum asq))
(setf asq (position 1 bb))
(setf (sbit bb asq) 0)
(let* ((acp (aref *board* asq)))
(declare (type fixnum acp))
(when (eql (aref sweeper-cp acp) 1)
(let*
((dx (aref dloc asq sq))
(debb (copy-seq (aref debbv dx))))
(declare (type fixnum dx))
(if (eql (sbit debb sq) 0)
(let*
((ac (aref mapv-c acp))
(axbb (copy-seq null-bb))
(bsbb (bit-ior debb *ammbb*))
(dv (aref mapv-dv dx))
(rsq sq))
(declare (type fixnum ac dv rsq))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 1)
(setf (sbit axbb rsq) 1)
(do () ((eql (sbit bsbb rsq) 1))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 1)
(setf (sbit axbb rsq) 1))
(bit-ior (aref *afbbv* asq) axbb t)
(bit-ior (aref *acbbv* ac) axbb t)))))))))
(defun attack-cut (sq)
"Cut attacks through an empty square"
(declare (type fixnum sq))
(let* ((bb (copy-seq (aref *atbbv* sq))))
(do* ((asq)) ((equal bb null-bb))
(declare (type fixnum asq))
(setf asq (position 1 bb))
(setf (sbit bb asq) 0)
(let* ((acp (aref *board* asq)))
(declare (type fixnum acp))
(when (eql (aref sweeper-cp acp) 1)
(let*
((dx (aref dloc asq sq))
(debb (copy-seq (aref debbv dx))))
(declare (type fixnum dx))
(if (eql (sbit debb sq) 0)
(let*
((ac (aref mapv-c acp))
(c0bb (copy-seq (aref *c0bbv* ac)))
(bsbb (bit-ior debb *ammbb*))
(dv (aref mapv-dv dx))
(rsq sq))
(declare (type fixnum ac dv rsq))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 0)
(setf (sbit (aref *afbbv* asq) rsq) 0)
(when (equal
(bit-and (aref *atbbv* rsq) c0bb)
null-bb)
(setf (sbit (aref *acbbv* ac) rsq) 0))
(do () ((eql (sbit bsbb rsq) 1))
(incf rsq dv)
(setf (sbit (aref *atbbv* rsq) asq) 0)
(setf (sbit (aref *afbbv* asq) rsq) 0)
(when (equal
(bit-and (aref *atbbv* rsq) c0bb)
null-bb)
(setf (sbit (aref *acbbv* ac) rsq) 0)))))))))))
(defun square-clear (sq)
"Clear the contents of an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq)))
(declare (type fixnum cp))
(setf (sbit *ammbb* sq) 0)
(setf (sbit (aref *c0bbv* (aref mapv-c cp)) sq) 0)
(setf (sbit (aref *cpbbv* cp) sq) 0))
(attack-del sq)
(setf (aref *board* sq) cp-v0)
(attack-pro sq))
(defun square-set (sq cp)
"Set the contents of a vacant square"
(declare (type fixnum sq cp))
(attack-cut sq)
(setf (aref *board* sq) cp)
(attack-add sq)
(setf (sbit *ammbb* sq) 1)
(setf (sbit (aref *c0bbv* (aref mapv-c cp)) sq) 1)
(setf (sbit (aref *cpbbv* cp) sq) 1))
(defun clear-bitboard-sets ()
"Clear all the bitboard items for the current position"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *afbbv* sq) (copy-seq null-bb))
(setf (aref *atbbv* sq) (copy-seq null-bb)))
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref *cpbbv* cp) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *c0bbv* c) (copy-seq null-bb))
(setf (aref *acbbv* c) (copy-seq null-bb)))
(setf *ammbb* (copy-seq null-bb)))
(defun clear-position-scalars ()
"Clear the basic position scalars"
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* 0)
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1))
(defun clear-board ()
"Clear the board array"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *board* sq) cp-v0)))
(defun clear-position ()
"Clear the current position"
(clear-position-scalars)
(clear-board)
(clear-bitboard-sets))
(declaim (inline on-board-next))
(defun on-board-next (dx sq)
"Determine if the next square along a direction is really on the board"
(declare (type fixnum dx sq))
(let*
((new-file (the fixnum (+ (map-file sq) (aref mapv-df dx))))
(new-rank (the fixnum (+ (map-rank sq) (aref mapv-dr dx)))))
(declare (type fixnum new-rank new-file))
(and
(>= new-file file-a) (<= new-file file-h)
(>= new-rank rank-1) (<= new-rank rank-8))))
(defun initialize-obnext ()
"Initialize the on-board-next array"
(dotimes (dx dx-limit)
(declare (type fixnum dx))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref obnext dx sq) (on-board-next dx sq)))))
(defun initialize-knight-move-bitboards ()
"Initialize the knight moves bitboard vector"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref nmbbv sq) (copy-seq null-bb))
(do* ((dx rdx-limit)) ((eql dx dx-limit))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(setf (sbit (aref nmbbv sq) (+ sq (aref mapv-dv dx))) 1))
(incf dx))))
(defun initialize-king-move-bitboards ()
"Initialize the king moves bitboard vector"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref kmbbv sq) (copy-seq null-bb))
(dotimes (dx rdx-limit)
(declare (type fixnum dx))
(if (aref obnext dx sq)
(setf (sbit (aref kmbbv sq) (+ sq (aref mapv-dv dx))) 1)))))
(defun initialize-directional-edge-bitboards ()
"Initialize the directional edge bitboards"
(dotimes (dx dx-4)
(declare (type fixnum dx))
(setf (aref debbv dx) (copy-seq null-bb)))
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(setf (sbit (aref debbv dx-0) (map-sq rank file-h)) 1)
(setf (sbit (aref debbv dx-2) (map-sq rank file-a)) 1))
(dotimes (file file-limit)
(declare (type fixnum file))
(setf (sbit (aref debbv dx-1) (map-sq rank-8 file)) 1)
(setf (sbit (aref debbv dx-3) (map-sq rank-1 file)) 1))
(setf (aref debbv dx-4) (bit-ior (aref debbv dx-0) (aref debbv dx-1)))
(setf (aref debbv dx-5) (bit-ior (aref debbv dx-1) (aref debbv dx-2)))
(setf (aref debbv dx-6) (bit-ior (aref debbv dx-2) (aref debbv dx-3)))
(setf (aref debbv dx-7) (bit-ior (aref debbv dx-3) (aref debbv dx-0))))
(defun initialize-directional-scanning-array ()
"Initialize the direction scanning items: offsets and squares"
(let* ((sqdex 0))
(declare (type fixnum sqdex))
(dotimes (dx rdx-limit)
(declare (type fixnum dx))
(let* ((delta (aref mapv-dv dx)) (edge (copy-seq (aref debbv dx))))
(declare (type fixnum delta))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref ds-offsets dx sq) sqdex)
(let* ((rsq sq))
(declare (type fixnum rsq))
(do* () ((eql (sbit edge rsq) 1))
(incf rsq delta)
(setf (aref ds-squares sqdex) rsq)
(incf sqdex))
(setf (aref ds-squares sqdex) sq-nil)
(incf sqdex)))))
(do* ((dx rdx-limit)) ((eql dx dx-limit))
(declare (type fixnum dx))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref ds-offsets dx sq) sqdex)
(when (aref obnext dx sq)
(setf (aref ds-squares sqdex) (+ sq (aref mapv-dv dx)))
(incf sqdex))
(setf (aref ds-squares sqdex) sq-nil)
(incf sqdex))
(incf dx))))
(defun initialize-directional-locator-array ()
"Intiailize the directional locator array"
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref dloc sq0 sq1) dx-nil)))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (dx dx-limit)
(declare (type fixnum dx))
(do* ((sqdex (aref ds-offsets dx sq0))) ((eql (aref ds-squares sqdex) sq-nil))
(declare (type fixnum sqdex))
(setf (aref dloc sq0 (aref ds-squares sqdex)) dx)
(incf sqdex)))))
(defun initialize-intersquare-pathway-bitboards ()
"Initialize the intersquare pathway bitboard vector"
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref ipbbv sq0 sq1) (copy-seq null-bb))))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(let* ((dx (aref dloc sq0 sq1)))
(declare (type fixnum dx))
(if (and (>= dx dx-0) (<= dx dx-7))
(do* ((rsq (+ sq0 (aref mapv-dv dx)))) ((eql rsq sq1))
(declare (type fixnum rsq))
(setf (sbit (aref ipbbv sq0 sq1) rsq) 1)
(incf rsq (aref mapv-dv dx))))))))
(defun initialize-constants ()
"Perform initialization of constant values"
(initialize-obnext)
(initialize-directional-edge-bitboards)
(initialize-directional-scanning-array)
(initialize-directional-locator-array)
(initialize-intersquare-pathway-bitboards)
(initialize-knight-move-bitboards)
(initialize-king-move-bitboards))
(defun initialize-variables ()
"Perform initialization of variable values"
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *board* sq) cp-v0))
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* (logior cflg-wk cflg-wq cflg-bk cflg-bq))
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1)
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref *cpbbv* cp) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *c0bbv* c) (copy-seq null-bb)))
(setf *ammbb* (copy-seq null-bb))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *afbbv* sq) (copy-seq null-bb)))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(setf (aref *atbbv* sq) (copy-seq null-bb)))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref *acbbv* c) (copy-seq null-bb)))
(setf *ply* 0)
(dotimes (index mgs-limit)
(declare (type fixnum index))
(setf (aref *mgs* index) (make-move)))
(setf *mgs-base-local* 0)
(setf *mgs-current-local* 0)
(setf *mgs-count-local* 0)
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *mgs-base* index) 0)
(setf (aref *mgs-current* index) 0)
(setf (aref *mgs-count* index) 0))
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *mgs-cast* index) 0)
(setf (aref *mgs-epsq* index) sq-nil)
(setf (aref *mgs-hmvc* index) 0)
(setf (aref *mgs-fmvn* index) 0))
(setf *gmh-count* 0)
(dotimes (index ghmh-limit)
(declare (type fixnum index))
(setf (aref *gmh-move* index) (make-move))
(setf (aref *gmh-board* index) (copy-seq *board*))
(setf (aref *gmh-cast* index) 0)
(setf (aref *gmh-epsq* index) sq-nil)
(setf (aref *gmh-hmvc* index) 0)
(setf (aref *gmh-fmvn* index) 0))
(setf *count-execute* 0)
(new-game))
(defun initialize ()
"Perform one time initialization"
(initialize-constants)
(initialize-variables)
(format t "~%Ready~%")
(values))
(defun print-bitboard (bb)
"Print a bitboard character string (eight lines long)"
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(dotimes (file file-limit)
(declare (type fixnum file))
(format t " ~d" (sbit bb (map-sq (- rank-8 rank) file))))
(format t "~%"))
(values))
(defun genstr-square-set (bb)
"Generate a square set string from a bitboard"
(let* ((s "[") (flag nil))
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(when (eql (sbit bb sq) 1)
(if flag
(setf s (strcat s " "))
(setf flag t))
(setf s (strcat s (aref sq-strings sq)))))
(setf s (strcat s "]"))
s))
(defun print-square-set (bb)
"Print a square set string from a bitboard"
(format t "~a" (genstr-square-set bb))
(values))
(defun pbaf (sq)
"Print bitboard: afbbv[sq]"
(print-bitboard (aref *afbbv* sq)))
(defun pbat (sq)
"Print bitboard: atbbv[sq]"
(print-bitboard (aref *atbbv* sq)))
(defun pbac (c)
"Print bitboard: acbbv[c]"
(print-bitboard (aref *acbbv* c)))
(defun pbcp (cp)
"Print bitboard: cpbbv[cp]"
(print-bitboard (aref *cpbbv* cp)))
(defun pbc0 (c)
"Print bitboard: c0bbv[c]"
(print-bitboard (aref *c0bbv* c)))
(defun pe (n)
(pathway-enumerate n))
(defun regenerate-bitboards ()
"Regenerate the bitboard environment from the board"
(let* ((board (copy-seq *board*)))
(clear-bitboard-sets)
(clear-board)
(dotimes (sq sq-limit)
(declare (type fixnum sq))
(if (not (eql (aref board sq) cp-v0))
(square-set sq (aref board sq))))))
(defun history-clear ()
"Clear the history for a new game or set-up position"
(setf *gmh-count* 0))
(defun history-push ()
"Push the current status items on to the history stack"
(setf (aref *gmh-move* *gmh-count*)
(copy-move (aref *mgs* *mgs-current-local*)))
(setf (aref *gmh-board* *gmh-count*) (copy-seq *board*))
(setf (aref *gmh-actc* *gmh-count*) *actc*)
(setf (aref *gmh-cast* *gmh-count*) *cast*)
(setf (aref *gmh-epsq* *gmh-count*) *epsq*)
(setf (aref *gmh-hmvc* *gmh-count*) *hmvc*)
(setf (aref *gmh-fmvn* *gmh-count*) *fmvn*)
(incf *gmh-count*))
(defun history-pop ()
"Pop the current status items off from the history stack"
(decf *gmh-count*)
(setf *board* (copy-seq (aref *gmh-board* *gmh-count*)))
(setf *actc* (aref *gmh-actc* *gmh-count*))
(setf *pasc* (aref invc-v *actc*))
(setf *cast* (aref *gmh-cast* *gmh-count*))
(setf *epsq* (aref *gmh-epsq* *gmh-count*))
(setf *hmvc* (aref *gmh-hmvc* *gmh-count*))
(setf *fmvn* (aref *gmh-fmvn* *gmh-count*))
(clear-move-generation)
(regenerate-bitboards)
(generate)
(setf *mgs-current-local* (ms-find-move (aref *gmh-move* *gmh-count*))))
(defun create ()
"Create/recreate the environment at ply zero"
(history-clear)
(clear-move-generation)
(if (valid-position)
(generate)
(format t "Warning: invalid position~%")))
(defun execute ()
"Execute the current move in the internal environment"
(incf *count-execute*)
(let* ((move (aref *mgs* *mgs-current-local*)) (scmv (move-scmv move)))
(cond
((eql scmv scmv-reg)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) (move-frcp move))))
((eql scmv scmv-cks)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-e1)
(square-set sq-g1 cp-wk)
(square-clear sq-h1)
(square-set sq-f1 cp-wr))
(progn
(square-clear sq-e8)
(square-set sq-g8 cp-bk)
(square-clear sq-h8)
(square-set sq-f8 cp-br))))
((eql scmv scmv-cqs)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-e1)
(square-set sq-c1 cp-wk)
(square-clear sq-a1)
(square-set sq-d1 cp-wr))
(progn
(square-clear sq-e8)
(square-set sq-c8 cp-bk)
(square-clear sq-a8)
(square-set sq-d8 cp-br))))
((eql scmv scmv-epc)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (+ (move-tosq move) dv-3))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wp))
(progn
(square-clear (+ (move-tosq move) dv-1))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bp))))
((eql scmv scmv-ppn)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wn))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bn))))
((eql scmv scmv-ppb)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wb))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bb))))
((eql scmv scmv-ppr)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wr))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-br))))
((eql scmv scmv-ppq)
(if (eql (move-frcp move) cp-wp)
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-wq))
(progn
(if (not (eql (move-tocp move) cp-v0))
(square-clear (move-tosq move)))
(square-clear (move-frsq move))
(square-set (move-tosq move) cp-bq)))))
(setf *actc* (aref invc-v *actc*))
(setf *pasc* (aref invc-v *pasc*))
(setf (aref *mgs-cast* *ply*) *cast*)
(setf (aref *mgs-epsq* *ply*) *epsq*)
(setf (aref *mgs-hmvc* *ply*) *hmvc*)
(setf (aref *mgs-fmvn* *ply*) *fmvn*)
(mf-set mfbp-exec)
(if (in-check)
(mf-set mfbp-chec))
(if (busted)
(mf-set mfbp-bust))
(when (not (eql *cast* 0))
(if
(and
(logbitp csbp-wk *cast*)
(or
(eql (move-frsq move) sq-e1)
(eql (move-frsq move) sq-h1)
(eql (move-tosq move) sq-h1)))
(setf *cast* (logxor *cast* cflg-wk)))
(if
(and
(logbitp csbp-wq *cast*)
(or
(eql (move-frsq move) sq-e1)
(eql (move-frsq move) sq-a1)
(eql (move-tosq move) sq-a1)))
(setf *cast* (logxor *cast* cflg-wq)))
(if
(and
(logbitp csbp-bk *cast*)
(or
(eql (move-frsq move) sq-e8)
(eql (move-frsq move) sq-h8)
(eql (move-tosq move) sq-h8)))
(setf *cast* (logxor *cast* cflg-bk)))
(if
(and
(logbitp csbp-bq *cast*)
(or
(eql (move-frsq move) sq-e8)
(eql (move-frsq move) sq-a8)
(eql (move-tosq move) sq-a8)))
(setf *cast* (logxor *cast* cflg-bq))))
(setf *epsq* sq-nil)
(if
(and
(eql (move-frcp move) cp-wp)
(eql (map-rank (move-frsq move)) rank-2)
(eql (map-rank (move-tosq move)) rank-4))
(setf *epsq* (+ (move-frsq move) dv-1)))
(if
(and
(eql (move-frcp move) cp-bp)
(eql (map-rank (move-frsq move)) rank-7)
(eql (map-rank (move-tosq move)) rank-5))
(setf *epsq* (+ (move-frsq move) dv-3)))
(if (or (eql (aref mapv-p (move-frcp move)) p-p) (not (eql (move-tocp move) cp-v0)))
(setf *hmvc* 0)
(incf *hmvc*))
(if (eql (aref mapv-c (move-frcp move)) c-b)
(incf *fmvn*)))
(setf (aref *mgs-base* *ply*) *mgs-base-local*)
(setf (aref *mgs-current* *ply*) *mgs-current-local*)
(setf (aref *mgs-count* *ply*) *mgs-count-local*)
(setf *mgs-base-local* (+ *mgs-base-local* *mgs-count-local*))
(setf *mgs-current-local* *mgs-base-local*)
(setf *mgs-count-local* 0)
(incf *ply*))
(defun retract ()
"Retract the previously executed move in the internal environment"
(decf *ply*)
(setf *mgs-base-local* (aref *mgs-base* *ply*))
(setf *mgs-current-local* (aref *mgs-current* *ply*))
(setf *mgs-count-local* (aref *mgs-count* *ply*))
(setf *actc* (aref invc-v *actc*))
(setf *pasc* (aref invc-v *pasc*))
(setf *cast* (aref *mgs-cast* *ply*))
(setf *epsq* (aref *mgs-epsq* *ply*))
(setf *hmvc* (aref *mgs-hmvc* *ply*))
(setf *fmvn* (aref *mgs-fmvn* *ply*))
(let* ((move (aref *mgs* *mgs-current-local*)) (scmv (move-scmv move)))
(cond
((eql scmv scmv-reg)
(progn
(square-clear (move-tosq move))
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move)))
(square-set (move-frsq move) (move-frcp move))))
((eql scmv scmv-cks)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-g1)
(square-set sq-e1 cp-wk)
(square-clear sq-f1)
(square-set sq-h1 cp-wr))
(progn
(square-clear sq-g8)
(square-set sq-e8 cp-bk)
(square-clear sq-f8)
(square-set sq-h8 cp-br))))
((eql scmv scmv-cqs)
(if (eql (move-frcp move) cp-wk)
(progn
(square-clear sq-c1)
(square-set sq-e1 cp-wk)
(square-clear sq-d1)
(square-set sq-a1 cp-wr))
(progn
(square-clear sq-c8)
(square-set sq-e8 cp-bk)
(square-clear sq-d8)
(square-set sq-a8 cp-br))))
((eql scmv scmv-epc)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(square-set (+ (move-tosq move) dv-3) cp-bp))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(square-set (+ (move-tosq move) dv-1) cp-wp))))
((eql scmv scmv-ppn)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppb)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppr)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))))
((eql scmv scmv-ppq)
(if (eql (move-frcp move) cp-wp)
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-wp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move))))
(progn
(square-clear (move-tosq move))
(square-set (move-frsq move) cp-bp)
(if (not (eql (move-tocp move) cp-v0))
(square-set (move-tosq move) (move-tocp move)))))))))
* * * PGN routines
(defun genstr-tag-pair (tag-name tag-value)
"Generate a tag pair string"
(format nil "[~a \"~a\"]" tag-name tag-value))
(defun print-tag-pair (tag-name tag-value)
"Print a tag pair string on a line"
(format t "~a~%" (genstr-tag-pair tag-name tag-value)))
(defun strcat (s0 s1)
"Return the concatenation of two strings"
(let* ((len0 (length s0)) (len1 (length s1))
(s2 (make-string (+ len0 len1))))
(dotimes (i len0)
(setf (schar s2 i) (schar s0 i)))
(dotimes (i len1)
(setf (schar s2 (+ len0 i)) (schar s1 i)))
s2))
(defun generate-psuedolegal-frsq-wp (sq)
"Generate psuedolegal moves for a white pawn"
(declare (type fixnum sq))
(let* ((gmove (make-move)))
(when (eql (aref *board* (+ sq dv-1)) cp-v0)
(if (not (eql (map-rank sq) rank-7))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-1))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(when
(and
(eql (map-rank sq) rank-2)
(eql (aref *board* (+ sq (* dv-1 2))) cp-v0))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq (* dv-1 2)))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-1))
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))
(dolist (dx `(,dx-4 ,dx-5))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(let*
((tosq (+ sq (aref mapv-dv dx)))
(tocp (aref *board* tosq)))
(declare (type fixnum tosq tocp))
(when (eql (aref mapv-c tocp) c-b)
(if (not (eql (map-rank sq) rank-7))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(progn
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))))))
(dolist (dx `(,dx-4 ,dx-5))
(declare (type fixnum dx))
(when
(and
(not (eql *epsq* sq-nil))
(eql (map-rank sq) rank-5)
(aref obnext dx sq)
(eql *epsq* (+ sq (aref mapv-dv dx))))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) *epsq*)
(setf (move-frcp gmove) cp-wp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-epc)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))))
(defun generate-psuedolegal-frsq-bp (sq)
"Generate psuedolegal moves for a black pawn"
(declare (type fixnum sq))
(let* ((gmove (make-move)))
(when (eql (aref *board* (+ sq dv-3)) cp-v0)
(if (not (eql (map-rank sq) rank-2))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-3))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(when
(and
(eql (map-rank sq) rank-7)
(eql (aref *board* (+ sq (* dv-3 2))) cp-v0))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq (* dv-3 2)))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) (+ sq dv-3))
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))
(dolist (dx `(,dx-6 ,dx-7))
(declare (type fixnum dx))
(if (aref obnext dx sq)
(let*
((tosq (+ sq (aref mapv-dv dx)))
(tocp (aref *board* tosq)))
(declare (type fixnum tosq tocp))
(when (eql (aref mapv-c tocp) c-w)
(if (not (eql (map-rank sq) rank-2))
(progn
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(progn
(do* ((scmv scmv-ppn)) ((eql scmv scmv-limit))
(declare (type fixnum scmv))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) tocp)
(setf (move-scmv gmove) scmv)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)
(incf scmv))))))))
(dolist (dx `(,dx-6 ,dx-7))
(declare (type fixnum dx))
(when
(and
(not (eql *epsq* sq-nil))
(eql (map-rank sq) rank-4)
(aref obnext dx sq)
(eql *epsq* (+ sq (aref mapv-dv dx))))
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) *epsq*)
(setf (move-frcp gmove) cp-bp)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-epc)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*)))))
(defun generate-psuedolegal-frsq-wk (sq)
"Generate psuedolegal moves for a white king"
(declare (type fixnum sq))
(let*
((bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c-w))))
(gmove (make-move)))
(setf bb (bit-and bb (bit-not (aref *acbbv* c-b))))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-wk *cast*)
(eql (aref *board* sq-f1) cp-v0)
(eql (aref *board* sq-g1) cp-v0)
(eql (sbit (aref *acbbv* c-b) sq-e1) 0)
(eql (sbit (aref *acbbv* c-b) sq-f1) 0)
(eql (sbit (aref *acbbv* c-b) sq-g1) 0))
(setf (move-frsq gmove) sq-e1)
(setf (move-tosq gmove) sq-g1)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cks)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-wq *cast*)
(eql (aref *board* sq-d1) cp-v0)
(eql (aref *board* sq-c1) cp-v0)
(eql (aref *board* sq-b1) cp-v0)
(eql (sbit (aref *acbbv* c-b) sq-e1) 0)
(eql (sbit (aref *acbbv* c-b) sq-d1) 0)
(eql (sbit (aref *acbbv* c-b) sq-c1) 0))
(setf (move-frsq gmove) sq-e1)
(setf (move-tosq gmove) sq-c1)
(setf (move-frcp gmove) cp-wk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cqs)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq-bk (sq)
"Generate psuedolegal moves for a black king"
(declare (type fixnum sq))
(let*
((bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c-b))))
(gmove (make-move)))
(setf bb (bit-and bb (bit-not (aref *acbbv* c-w))))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-bk *cast*)
(eql (aref *board* sq-f8) cp-v0)
(eql (aref *board* sq-g8) cp-v0)
(eql (sbit (aref *acbbv* c-w) sq-e8) 0)
(eql (sbit (aref *acbbv* c-w) sq-f8) 0)
(eql (sbit (aref *acbbv* c-w) sq-g8) 0))
(setf (move-frsq gmove) sq-e8)
(setf (move-tosq gmove) sq-g8)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cks)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))
(when
(and
(logbitp csbp-bq *cast*)
(eql (aref *board* sq-d8) cp-v0)
(eql (aref *board* sq-c8) cp-v0)
(eql (aref *board* sq-b8) cp-v0)
(eql (sbit (aref *acbbv* c-w) sq-e8) 0)
(eql (sbit (aref *acbbv* c-w) sq-d8) 0)
(eql (sbit (aref *acbbv* c-w) sq-c8) 0))
(setf (move-frsq gmove) sq-e8)
(setf (move-tosq gmove) sq-c8)
(setf (move-frcp gmove) cp-bk)
(setf (move-tocp gmove) cp-v0)
(setf (move-scmv gmove) scmv-cqs)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq-regular (sq)
"Generate psuedolegal moves for a knight, bishop, rook, or queen"
(declare (type fixnum sq))
(let*
((cp (aref *board* sq))
(c (aref mapv-c cp))
(bb (bit-and (aref *afbbv* sq) (bit-not (aref *c0bbv* c))))
(gmove (make-move)))
(declare (type fixnum cp c))
(do* ((tosq)) ((equal bb null-bb))
(declare (type fixnum tosq))
(setf tosq (position 1 bb))
(setf (sbit bb tosq) 0)
(setf (move-frsq gmove) sq)
(setf (move-tosq gmove) tosq)
(setf (move-frcp gmove) cp)
(setf (move-tocp gmove) (aref *board* tosq))
(setf (move-scmv gmove) scmv-reg)
(setf (move-mflg gmove) 0)
(setf (aref *mgs* *mgs-current-local*) (copy-move gmove))
(incf *mgs-count-local*)
(incf *mgs-current-local*))))
(defun generate-psuedolegal-frsq (sq)
"Generate psuedolegal moves for from an occupied square"
(declare (type fixnum sq))
(let* ((cp (aref *board* sq)) (p (aref mapv-p cp)) (c (aref mapv-c cp)))
(declare (type fixnum cp p c))
(cond
((eql p p-p)
(if (eql c c-w)
(generate-psuedolegal-frsq-wp sq)
(generate-psuedolegal-frsq-bp sq)))
((eql p p-k)
(if (eql c c-w)
(generate-psuedolegal-frsq-wk sq)
(generate-psuedolegal-frsq-bk sq)))
(t
(generate-psuedolegal-frsq-regular sq)))))
(defun generate-psuedolegal ()
"Generate psuedolegal moves for the current position at the current ply"
(setf *mgs-current-local* *mgs-base-local*)
(setf *mgs-count-local* 0)
(let ((bb (copy-seq (aref *c0bbv* *actc*))))
(do* ((frsq)) ((equal bb null-bb))
(declare (type fixnum frsq))
(setf frsq (position 1 bb))
(setf (sbit bb frsq) 0)
(generate-psuedolegal-frsq frsq))))
(defun generate-legal ()
"Generate legal moves for the current position at the current ply"
(generate-psuedolegal)
(ms-execute)
(ms-compact))
(defun generate ()
"Generate legal moves with full notation"
(generate-legal)
(ms-matescan)
(ms-disambiguate))
(defun clear-move-generation ()
"Clear the move generation variables for ply zero"
(setf *mgs-base-local* 0)
(setf *mgs-current-local* 0)
(setf *mgs-count-local* 0))
(defun fetch-move-strings (base count)
"Return a list of move strings for the indicated bounds"
(let* ((sl nil) (index base) (limit (+ base count)))
(do () ((eql index limit))
(setf sl (cons (genstr-san (aref *mgs* index)) sl))
(incf index))
(reverse sl)))
(defun fetch-move-strings-at-ply (ply)
"Return a list of move strings for the indicated ply"
(if (eql ply *ply*)
(fetch-move-strings *mgs-base-local* *mgs-count-local*)
(fetch-move-strings (aref *mgs-base* *ply*) (aref *mgs-count* *ply*))))
(defun fetch-move-strings-at-current ()
"Return a list of move strings for the current level"
(fetch-move-strings-at-ply *ply*))
(defun fetch-move-strings-at-base ()
"Return a list of move strings for the base level"
(fetch-move-strings-at-ply 0))
* * * * Moveset manipulation routines
(defun ms-execute-print ()
"Execute and retract each move in the current set with diagnostic output"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(format t "Move: ~a~%" (genstr-san (aref *mgs* *mgs-current-local*)))
(execute)
(format t "FEN: ~a~%" (genstr-fen))
(retract)
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)
limit))
(defun ms-execute ()
"Execute and retract each move in the current set (move flags: exec/bust)"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(declare (type fixnum save-index limit))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(declare (type fixnum index))
(execute)
(retract)
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)
limit))
(defun ms-compact ()
"Compact current moveset by eliminating illegal moves"
(let* ((limit *mgs-count-local*) (busted 0) (dst 0))
(declare (type fixnum limit busted dst))
(dotimes (src limit)
(declare (type fixnum src))
(setf *mgs-current-local* (+ src *mgs-base-local*))
(if (mf-test mfbp-bust)
(incf busted)
(progn
(if (not (eql src dst))
(setf (aref *mgs* (+ *mgs-base-local* dst))
(aref *mgs* (+ *mgs-base-local* src))))
(incf dst))))
(decf *mgs-count-local* busted)
(setf *mgs-current-local* *mgs-base-local*)
*mgs-count-local*))
(defun ms-no-moves ()
"Determine if no moves exist for the current position"
(let* ((no-moves t))
(generate-psuedolegal)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0)) ((or (not no-moves) (eql index *mgs-count-local*)))
(declare (type fixnum index))
(execute)
(retract)
(if (not (mf-test mfbp-bust))
(setf no-moves nil))
(incf index)
(incf *mgs-current-local*))
no-moves))
(defun ms-matescan ()
"Scan for mates and set checkmate and stalemate flags"
(let* ((limit *mgs-count-local*) (save-current *mgs-current-local*))
(declare (type fixnum limit save-current))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (index limit)
(declare (type fixnum index))
(let* ((no-moves-flag))
(when (not (mf-test mfbp-bust))
(execute)
(setf no-moves-flag (ms-no-moves))
(retract)
(if no-moves-flag
(if (mf-test mfbp-chec)
(mf-set mfbp-chmt)
(mf-set mfbp-stmt))))
(incf *mgs-current-local*)))
(setf *mgs-current-local* save-current)))
(defun ms-disambiguate ()
"Assign rank and file disambiguation flags in the current moveset"
(let* ((save-index *mgs-current-local*) (limit *mgs-count-local*))
(declare (type fixnum save-index limit))
(setf *mgs-current-local* *mgs-base-local*)
(dotimes (i limit)
(declare (type fixnum i))
(let* (
(move0 (aref *mgs* *mgs-current-local*))
(frcp0 (move-frcp move0))
(frp0 (aref mapv-p frcp0)))
(declare (type fixnum frcp0 frp0))
(when (and (not (eql frp0 p-p)) (not (eql frp0 p-k)))
(let*
((frsq0 (move-frsq move0))
(tosq0 (move-tosq move0))
(frr0 (map-rank frsq0))
(frf0 (map-file frsq0))
(pun-frr 0)
(pun-frf 0)
(pun-tosq 0))
(declare (type fixnum frsq0 tosq0 frr0 frf0 pun-frr pun-frf pun-tosq))
(dotimes (j limit)
(declare (type fixnum j))
(let*
((move1 (aref *mgs* (+ j *mgs-base-local*)))
(frcp1 (move-frcp move1))
(frsq1 (move-frsq move1))
(tosq1 (move-tosq move1)))
(declare (type fixnum frcp1 frsq1 tosq1))
(when (and
(eql frcp0 frcp1)
(eql tosq0 tosq1)
(not (eql i j)))
(incf pun-tosq)
(if (eql frr0 (map-rank frsq1))
(incf pun-frr))
(if (eql frf0 (map-file frsq1))
(incf pun-frf)))))
(when (> pun-tosq 0)
(if (or (> pun-frr 0) (and (eql pun-frr 0) (eql pun-frf 0)))
(mf-set mfbp-anfd))
(if (> pun-frf 0)
(mf-set mfbp-anrd))))))
(incf *mgs-current-local*))
(setf *mgs-current-local* save-index)))
(defun find-san-move (san)
"Return the move stack index of the SAN move in the current set"
(let*
((found nil)
(save-index *mgs-current-local*)
(limit *mgs-count-local*)
(index 0)
(result -1))
(declare (type fixnum save-index limit index result))
(setf *mgs-current-local* *mgs-base-local*)
(do () ((or (eql index limit) found))
(if (string= san (genstr-san (aref *mgs* *mgs-current-local*)))
(setf found t)
(progn
(incf index)
(incf *mgs-current-local*))))
(setf *mgs-current-local* save-index)
(if found
(setf result (+ index *mgs-base-local*)))
result))
(defun ms-find-move (move)
"Return the move stack index of the move in the current set"
(let* ((found nil) (limit *mgs-count-local*) (index 0) (result -1))
(declare (type fixnum limit index result))
(do ((tmove)) ((or (eql index limit) found))
(setf tmove (aref *mgs* (+ index *mgs-base-local*)))
(if
(and
(eql (move-tosq tmove) (move-tosq move))
(eql (move-frcp tmove) (move-frcp move))
(eql (move-frsq tmove) (move-frsq move))
(eql (move-scmv tmove) (move-scmv move))
(eql (move-tocp tmove) (move-tocp move)))
(setf found t)
(incf index)))
(if found
(setf result (+ index *mgs-base-local*)))
result))
(defun ms-find-move2 (frsq tosq)
"Return the move stack index of the first matching move in the current set"
(let*
((found nil)
(limit *mgs-count-local*)
(index 0)
(result -1))
(declare (type fixnum limit index result))
(do ((tmove)) ((or (eql index limit) found))
(setf tmove (aref *mgs* (+ index *mgs-base-local*)))
(if
(and
(eql (move-tosq tmove) tosq)
(eql (move-frsq tmove) frsq))
(setf found t)
(incf index)))
(if found
(setf result (+ index *mgs-base-local*)))
result))
(declaim (inline mf-set))
(defun mf-set (bitpos)
"Set the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logior flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-clear))
(defun mf-clear (bitpos)
"Clear the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logandc2 flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-toggle))
(defun mf-toggle (bitpos)
"Toggle the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(let* ((flags (move-mflg (aref *mgs* *mgs-current-local*))))
(declare (type fixnum flags))
(setf flags (logxor flags (ash 1 bitpos)))
(setf (move-mflg (aref *mgs* *mgs-current-local*)) flags)))
(declaim (inline mf-test))
(defun mf-test (bitpos)
"Test the indicated move flag (bit position) for the current move"
(declare (type fixnum bitpos))
(logbitp bitpos (move-mflg (aref *mgs* *mgs-current-local*))))
(defun genstr-san (move)
"Return the SAN (Standard Algebraic Notation) string for a move"
(let*
((san "")
(frsq (move-frsq move))
(tosq (move-tosq move))
(frcp (move-frcp move))
(tocp (move-tocp move))
(scmv (move-scmv move))
(mflg (move-mflg move))
(frfile (map-file frsq))
(frrank (map-rank frsq))
(torank (map-rank tosq)))
(if (logbitp mfbp-bust mflg)
(setf san (strcat san "*")))
(cond
((eql scmv scmv-reg)
(if (eql (aref mapv-p frcp) p-p)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq))))))
(progn
(setf san (strcat san (aref p-strings (aref mapv-p frcp))))
(if (logbitp mfbp-anfd mflg)
(setf san (strcat san (aref file-strings frfile))))
(if (logbitp mfbp-anrd mflg)
(setf san (strcat san (aref rank-strings frrank))))
(if (not (eql tocp cp-v0))
(setf san (strcat san "x")))
(setf san (strcat san (aref sq-strings tosq))))))
((eql scmv scmv-cks)
(setf san (strcat san (aref fc-strings flank-k))))
((eql scmv scmv-cqs)
(setf san (strcat san (aref fc-strings flank-q))))
((eql scmv scmv-epc)
(progn
(setf san (strcat san (aref file-strings frfile)))
(setf san (strcat san "x")))
(setf san (strcat san (aref sq-strings tosq))))
((eql scmv scmv-ppn)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-n)))))
((eql scmv scmv-ppb)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-b)))))
((eql scmv scmv-ppr)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-r)))))
((eql scmv scmv-ppq)
(progn
(setf san (strcat san (aref file-strings frfile)))
(if (eql tocp cp-v0)
(setf san (strcat san (aref rank-strings torank)))
(progn
(setf san (strcat san "x"))
(setf san (strcat san (aref sq-strings tosq)))))
(setf san (strcat san "="))
(setf san (strcat san (aref p-strings p-q))))))
(if (logbitp mfbp-chec mflg)
(if (logbitp mfbp-chmt mflg)
(setf san (strcat san "#"))
(setf san (strcat san "+"))))
san))
(defun new-game ()
"Initialize for a new game"
(clear-position)
(setf *actc* c-w)
(setf *pasc* c-b)
(setf *cast* (logior cflg-wk cflg-wq cflg-bk cflg-bq))
(setf *epsq* sq-nil)
(setf *hmvc* 0)
(setf *fmvn* 1)
(square-set sq-a1 cp-wr)
(square-set sq-b1 cp-wn)
(square-set sq-c1 cp-wb)
(square-set sq-d1 cp-wq)
(square-set sq-e1 cp-wk)
(square-set sq-f1 cp-wb)
(square-set sq-g1 cp-wn)
(square-set sq-h1 cp-wr)
(square-set sq-a2 cp-wp)
(square-set sq-b2 cp-wp)
(square-set sq-c2 cp-wp)
(square-set sq-d2 cp-wp)
(square-set sq-e2 cp-wp)
(square-set sq-f2 cp-wp)
(square-set sq-g2 cp-wp)
(square-set sq-h2 cp-wp)
(square-set sq-a7 cp-bp)
(square-set sq-b7 cp-bp)
(square-set sq-c7 cp-bp)
(square-set sq-d7 cp-bp)
(square-set sq-e7 cp-bp)
(square-set sq-f7 cp-bp)
(square-set sq-g7 cp-bp)
(square-set sq-h7 cp-bp)
(square-set sq-a8 cp-br)
(square-set sq-b8 cp-bn)
(square-set sq-c8 cp-bb)
(square-set sq-d8 cp-bq)
(square-set sq-e8 cp-bk)
(square-set sq-f8 cp-bb)
(square-set sq-g8 cp-bn)
(square-set sq-h8 cp-br)
(create))
* * * FEN / EPD ( Forsyth - Edwards Notation / Expanded Position Description ) routines
(defun genstr-ppd ()
"Generate a piece position description string"
(let* ((ppd ""))
(dotimes (aux-rank rank-limit)
(declare (type fixnum aux-rank))
(let* ((rank (- rank-8 aux-rank)) (s 0))
(declare (type fixnum rank s))
(dotimes (file file-limit)
(let* ((sq (map-sq rank file)) (cp (aref *board* sq)))
(declare (type fixnum sq cp))
(if (eql cp cp-v0)
(incf s)
(progn
(if (> s 0)
(progn
(setf ppd (strcat ppd (format nil "~d" s)))
(setf s 0)))
(if (eql (aref mapv-c cp) c-w)
(setf ppd (strcat ppd (aref p-strings (aref mapv-p cp))))
(setf ppd (strcat ppd (aref lcp-strings (aref mapv-p cp)))))))))
(if (> s 0)
(setf ppd (strcat ppd (format nil "~d" s))))
(if (> rank rank-1)
(setf ppd (strcat ppd "/")))))
ppd))
(defun genstr-actc ()
"Generate a string with the active color"
(aref c-strings *actc*))
(defun genstr-cast ()
"Generate a string with the castling availability"
(let* ((cast ""))
(if (eql *cast* 0)
(setf cast (strcat cast "-"))
(progn
(if (logbitp csbp-wk *cast*)
(setf cast (strcat cast (aref p-strings p-k))))
(if (logbitp csbp-wq *cast*)
(setf cast (strcat cast (aref p-strings p-q))))
(if (logbitp csbp-bk *cast*)
(setf cast (strcat cast (aref lcp-strings p-k))))
(if (logbitp csbp-bq *cast*)
(setf cast (strcat cast (aref lcp-strings p-q))))))
cast))
(defun genstr-epsq ()
"Generate a string with the en passant target square"
(let* ((epsq ""))
(if (eql *epsq* sq-nil)
(setf epsq "-")
(setf epsq (aref sq-strings *epsq*)))
epsq))
(defun genstr-hmvc ()
"Generate a string with the halfmove count"
(format nil "~d" *hmvc*))
(defun genstr-fmvn ()
"Generate a string with the fullmove number"
(format nil "~d" *fmvn*))
(defun genstr-fen ()
"Generate a FEN string for the current position"
(let* ((fen ""))
(setf fen (strcat fen (genstr-ppd)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-actc)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-cast)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-epsq)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-hmvc)))
(setf fen (strcat fen " "))
(setf fen (strcat fen (genstr-fmvn)))
fen))
(defun in-check ()
"Determine if the active color is in check"
(if (eql *actc* c-w)
(not (equal (bit-and (aref *cpbbv* cp-wk) (aref *acbbv* c-b)) null-bb))
(not (equal (bit-and (aref *cpbbv* cp-bk) (aref *acbbv* c-w)) null-bb))))
(defun busted ()
"Determine if the passive color is in check"
(if (eql *pasc* c-w)
(not (equal (bit-and (aref *cpbbv* cp-wk) (aref *acbbv* c-b)) null-bb))
(not (equal (bit-and (aref *cpbbv* cp-bk) (aref *acbbv* c-w)) null-bb))))
(defun valid-position ()
"Determine if the position is valid"
(let*
((valid t)
(count-cpv (make-array rcp-limit :initial-element 0))
(count-cv (make-array rc-limit :initial-element 0))
(count-scpv (make-array `(,rc-limit ,rp-limit) :initial-element 0))
(extra-pawns (make-array rc-limit :initial-element 0)))
(dotimes (cp rcp-limit)
(declare (type fixnum cp))
(setf (aref count-cpv cp) (count 1 (aref *cpbbv* cp))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref count-cv c) (count 1 (aref *c0bbv* c))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(dotimes (p rp-limit)
(declare (type fixnum p))
(setf (aref count-scpv c p)
(count 1 (aref *cpbbv* (aref mapv-cp c p))))))
(dotimes (c rc-limit)
(declare (type fixnum c))
(setf (aref extra-pawns c) (- 8 (aref count-scpv c p-p))))
(when valid
(if
(or
(< (aref count-cv c-w) 1) (> (aref count-cv c-w) 16)
(< (aref count-cv c-b) 1) (> (aref count-cv c-b) 16))
(setf valid nil)))
(when valid
(if
(or
(not (eql (aref count-cpv cp-wk) 1))
(not (eql (aref count-cpv cp-bk) 1))
(> (aref count-cpv cp-wp) 8)
(> (aref count-cpv cp-bp) 8))
(setf valid nil)))
(when valid
(if (not (equal
(bit-and
(bit-ior (aref *cpbbv* cp-wp) (aref *cpbbv* cp-bp))
(bit-ior (aref debbv dx-1) (aref debbv dx-3)))
null-bb))
(setf valid nil)))
(when valid
(dotimes (c rc-limit)
(if (> (aref count-scpv c p-n) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-n) 2)))
(if (> (aref count-scpv c p-b) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-b) 2)))
(if (> (aref count-scpv c p-r) 2)
(decf (aref extra-pawns c) (- (aref count-scpv c p-r) 2)))
(if (> (aref count-scpv c p-q) 1)
(decf (aref extra-pawns c) (- (aref count-scpv c p-q) 1))))
(if (or (< (aref extra-pawns c-w) 0) (< (aref extra-pawns c-b) 0))
(setf valid nil)))
(when valid
(if (logbitp csbp-wk *cast*)
(if (or
(not (eql (aref *board* sq-e1) cp-wk))
(not (eql (aref *board* sq-h1) cp-wr)))
(setf valid nil))))
(when valid
(if (logbitp csbp-wq *cast*)
(if (or
(not (eql (aref *board* sq-e1) cp-wk))
(not (eql (aref *board* sq-a1) cp-wr)))
(setf valid nil))))
(when valid
(if (logbitp csbp-bk *cast*)
(if (or
(not (eql (aref *board* sq-e8) cp-bk))
(not (eql (aref *board* sq-h8) cp-br)))
(setf valid nil))))
(when valid
(if (logbitp csbp-bq *cast*)
(if (or
(not (eql (aref *board* sq-e8) cp-bk))
(not (eql (aref *board* sq-a8) cp-br)))
(setf valid nil))))
(when valid
(if (and (not (eql *epsq* sq-nil)) (eql *actc* c-w))
(if
(or
(not (eql (map-rank *epsq*) rank-6))
(not (eql (aref *board* *epsq*) cp-v0))
(not (eql (aref *board* (+ *epsq* dv-3)) cp-bp))
(not (eql (aref *board* (+ *epsq* dv-1)) cp-v0)))
(setf valid nil))))
(when valid
(if (and (not (eql *epsq* sq-nil)) (eql *actc* c-b))
(if
(or
(not (eql (map-rank *epsq*) rank-3))
(not (eql (aref *board* *epsq*) cp-v0))
(not (eql (aref *board* (+ *epsq* dv-1)) cp-wp))
(not (eql (aref *board* (+ *epsq* dv-3)) cp-v0)))
(setf valid nil))))
(when valid
(if (< *hmvc* 0) (setf valid nil)))
(when valid
(if (< *fmvn* 1) (setf valid nil)))
(when valid
(if (busted) (setf valid nil)))
valid))
(defun checkmated ()
"Determine if the active side is checkmated"
(and (in-check) (ms-no-moves)))
(defun stalemated ()
"Determine if the active side is stalemated"
(and (not (in-check)) (ms-no-moves)))
(defun play-move (san)
"Play the given move (a SAN string) in the game"
(let* ((index (find-san-move san)))
(declare (type fixnum index))
(if (< index 0)
(error "Move not found")
(progn
(history-push)
(setf *mgs-current-local* index)
(execute)
(decf *ply*)
(clear-move-generation)
(generate)))))
(defun unplay-move ()
"Unplay the a move in the game"
(if (< *gmh-count* 1)
(error "Can't unplay non-existent move")
(history-pop)))
(declaim (inline map-file))
(defun map-file (sq)
"Map a square to its file"
(declare (type fixnum sq))
(the fixnum (logand sq 7)))
(declaim (inline map-rank))
(defun map-rank (sq)
"Map a square to its rank"
(declare (type fixnum sq))
(the fixnum (ash sq -3)))
(declaim (inline map-sq))
(defun map-sq (rank file)
"Map a rank and a file to a square"
(declare (type fixnum rank file))
(the fixnum (logior (the fixnum (ash rank 3)) file)))
(defun file-print-path ()
"Print the move path to the current position onto the filepath stream"
(dotimes (ply *ply*)
(if (not (eql ply 0))
(format *pathway-file-stream* " "))
(format *pathway-file-stream* "~a"
(genstr-san (aref *mgs* (aref *mgs-current* ply)))))
(format *pathway-file-stream* "~%")
(values))
(defun print-board ()
"Print the board (eight lines long)"
(dotimes (rank rank-limit)
(declare (type fixnum rank))
(dotimes (file file-limit)
(declare (type fixnum file))
(let* ((sq (map-sq (- rank-8 rank) file)) (cp (aref *board* sq)))
(declare (type fixnum sq cp))
(if (eql cp cp-v0)
(if (eql (logand file 1) (logand rank 1))
(format t " ")
(format t "::"))
(format t "~a" (aref cp-strings cp)))))
(format t "~%"))
(values))
(defun pathway-enumerate (depth)
"Enumerate the pathways of the current position to the given ply depth"
(declare (type fixnum depth))
(let* ((sum 0) (limit 0))
(declare (type fixnum sum limit))
(if (eql depth 0)
(progn
(setf sum 1)
(if *pathway-file-stream*
(file-print-path)))
(progn
(generate-psuedolegal)
(setf limit (+ *mgs-base-local* *mgs-count-local*))
(do* ((index *mgs-base-local*)) ((eql index limit))
(declare (type fixnum index))
(setf *mgs-current-local* index)
(execute)
(if (not (busted))
(incf sum (pathway-enumerate (- depth 1))))
(retract)
(incf index))))
sum))
(defun verify-enumeration (depth count)
"Enumerate pathways to the given depth and check the count"
(declare (type fixnum depth count))
(let* ((sum))
(declare (type fixnum sum))
(format t "Enumerating to depth ~R; please wait~%" depth)
(setf sum (pathway-enumerate depth))
(format t "Calculated count: ~d Expected count: ~d " sum count)
(if (eql sum count)
(format t "Operation verified~%")
(format t "Operation *failed*~%"))
(eql sum count)))
(defun ui-init ()
"Initialization; must be called before any other functions"
(initialize)
(values))
(defun ui-play (san)
"Play a SAN (string) move with update of the game history"
(play-move san)
(values))
(defun ui-unpl ()
"Unplay (reverse of ui-play) the previous played move"
(unplay-move)
(values))
(defun ui-cvsq (sq)
"Clear value: square"
(when (not (eql (aref *board* sq) cp-v0))
(square-clear sq)
(create))
(values))
(defun ui-cvcb ()
"Clear value: chessboard"
(dotimes (sq sq-limit)
(if (not (eql (aref *board* sq) cp-v0))
(square-clear sq)))
(setf *cast* 0)
(setf *epsq* sq-nil)
(create)
(values))
(defun ui-svsq (sq cp)
"Set value: square"
(when (not (eql (aref *board* sq) cp))
(if (not (eql (aref *board* sq) cp-v0))
(square-clear sq))
(square-set sq cp)
(create))
(values))
(defun ui-svac (c)
"Set value: active color"
(when (not (eql c *actc*))
(setf *actc* c)
(setf *pasc* (aref invc-v c))
(create))
(values))
(defun ui-svca (cast)
"Set value: castling availability"
(when (not (eql cast *cast*))
(setf *cast* cast)
(create))
(values))
(defun ui-svep (epsq)
"Set value: en passant target square"
(when (not (eql epsq *epsq*))
(setf *epsq* epsq)
(create))
(values))
(defun ui-svhc (hmvc)
"Set value: halfmove clock"
(when (not (eql hmvc *hmvc*))
(setf *hmvc* hmvc)
(create))
(values))
(defun ui-svfn (fmvn)
"Set value: fullmove number"
(when (not (eql fmvn *fmvn*))
(setf *fmvn* fmvn)
(create))
(values))
(defun ui-dvfe ()
"Display value: Forsyth-Edwards Notation"
(format t "~a~%" (genstr-fen))
(values))
(defun ui-dvcb ()
"Display value: chessboard"
(print-board)
(values))
(defun ui-dvms ()
"Display value: moveset"
(if (valid-position)
(let* ((movelist (copy-list (fetch-move-strings-at-base))))
(cond
((eql *mgs-count-local* 0)
(format t "There are no moves.~%")
(if (checkmated)
(format t "~a is checkmated.~%"
(aref player-strings *actc*))
(if (stalemated)
(format t "~a is stalemated.~%"
(aref player-strings *actc*)))))
((eql *mgs-count-local* 1)
(format t "There is one move: ~a~%" (car movelist)))
(t
(setf movelist (sort movelist #'string<))
(format t "There are ~R moves:" *mgs-count-local*)
(dolist (pmove movelist)
(format t " ~a" pmove))
(format t "~%"))))
(format t "Invalid position; there are no moves.~%"))
(values))
(defun ui-newg ()
"Set up a new game"
(new-game)
(values))
(defun ui-enum (n)
"Enumerate distinct pathways N plies deep"
(let* ((count 0))
(if (not (valid-position))
(format t "Can't enumerate from invalid position.~%")
(progn
(setf count (pathway-enumerate n))
(format t "Pathway count: ~R~%" count))))
(values))
(defun ui-test ()
"Perform simple program validity testing via pathway enumeration"
(new-game)
(verify-enumeration 0 1)
(verify-enumeration 1 20)
(verify-enumeration 2 400)
(verify-enumeration 3 8902)
(verify-enumeration 4 197281)
(verify-enumeration 5 4865609)
(values))
(defun fms1-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms1-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms1-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(execute)
(if (not (busted))
(setf result (not (fms1-search-defend (- n 1)))))
(retract)
(when (not result)
(incf *mgs-current-local*)
(incf index)))
result))
(defun fms1-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(execute)
(if (not (busted))
(setf result (not (fms1-search-attack n))))
(retract)
(when (not result)
(incf *mgs-current-local*)
(incf index)))))
result))
(defvar *fms2-killers* (make-array ply-limit))
(defun fms2-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(dotimes (index ply-limit)
(declare (type fixnum index))
(setf (aref *fms2-killers* index) (copy-move empty-move)))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms2-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms2-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(setf killer-index (ms-find-move (aref *fms2-killers* *ply*)))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(if (not (busted))
(setf result (not (fms2-search-defend (- n 1)))))
(retract))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms2-search-defend (- n 1)))))
(retract)
(if result
(setf (aref *fms2-killers* *ply*)
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))
result))
(defun fms2-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(setf killer-index (ms-find-move (aref *fms2-killers* *ply*)))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(if (not (busted))
(setf result (not (fms2-search-attack n))))
(retract))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms2-search-attack n))))
(retract)
(if result
(setf (aref *fms2-killers* *ply*)
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))))
result))
* * * Simple forced mate locator programming example : fms3
(defvar *fms3-killers* (make-array `(,rc-limit ,sq-limit ,sq-limit)))
(defun fms3-search (n)
"Attempt to locate a key move for a forced mate in -n- moves"
(declare (type fixnum n))
(dotimes (c rc-limit)
(declare (type fixnum c))
(dotimes (sq0 sq-limit)
(declare (type fixnum sq0))
(dotimes (sq1 sq-limit)
(declare (type fixnum sq1))
(setf (aref *fms3-killers* c sq0 sq1) (copy-move empty-move)))))
(let* ((result nil) (key-move empty-move) (count *count-execute*))
(declare (type fixnum count))
(setf result (fms3-search-attack n))
(setf count (- *count-execute* count))
(if result
(progn
(setf key-move (copy-move (aref *mgs* *mgs-current-local*)))
(format t "Mate in ~R key move located: ~a~%" n (genstr-san key-move)))
(format t "No forced mate in ~R located.~%" n))
(format t "Move count: ~R~%" count)
result))
(defun fms3-prev-frsq ()
"Return the frsq of the previous move"
(move-frsq (aref *mgs* (aref *mgs-current* (- *ply* 1)))))
(defun fms3-prev-tosq ()
"Return the tosq of the previous move"
(move-tosq (aref *mgs* (aref *mgs-current* (- *ply* 1)))))
(defun fms3-search-attack (n)
"Attempt to force mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (not (eql *ply* 0))
(generate-psuedolegal))
(when (> *ply* 0)
(setf killer-index (ms-find-move
(aref *fms3-killers*
*actc* (fms3-prev-frsq) (fms3-prev-tosq))))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(when (not (busted))
(setf result (not (fms3-search-defend (- n 1)))))
(retract)))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms3-search-defend (- n 1)))))
(retract)
(if (and result (> *ply* 0))
(setf (aref *fms3-killers* *actc* (fms3-prev-frsq) (fms3-prev-tosq))
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))
result))
(defun fms3-search-defend (n)
"Attempt to defend mate in -n- moves; return t if success, else nil"
(declare (type fixnum n))
(let* ((result nil) (killer-index -1))
(declare (type fixnum killer-index))
(if (eql n 0)
(setf result (not (checkmated)))
(progn
(generate-psuedolegal)
(when (> *ply* 0)
(setf killer-index (ms-find-move
(aref *fms3-killers*
*actc* (fms3-prev-frsq) (fms3-prev-tosq))))
(when (>= killer-index 0)
(setf *mgs-current-local* killer-index)
(execute)
(when (not (busted))
(setf result (not (fms3-search-attack n))))
(retract)))
(when (not result)
(setf *mgs-current-local* *mgs-base-local*)
(do* ((index 0) (limit *mgs-count-local*)) ((or result (eql index limit)))
(declare (type fixnum index limit))
(when (not (eql *mgs-current-local* killer-index))
(execute)
(if (not (busted))
(setf result (not (fms3-search-attack n))))
(retract)
(if (and result (> *ply* 0))
(setf (aref *fms3-killers* *actc* (fms3-prev-frsq) (fms3-prev-tosq))
(copy-move (aref *mgs* *mgs-current-local*)))))
(when (not result)
(incf *mgs-current-local*)
(incf index))))))
result))
cil.lsp : EOF
|
4643de172c075522ba116b9c16a1f4680d3533f458a7e44a402049b9c6b48109 | Metaxal/rascas | extended-euclidean-algorithm.rkt | #lang racket/base
This file has been changed from its original dharmatech / mpl version .
(provide extended-euclidean-algorithm)
(require "arithmetic.rkt"
"leading-coefficient-gpe.rkt"
"algebraic-expand.rkt"
"polynomial-division.rkt")
(define (extended-euclidean-algorithm u v x)
(if (and (equal? u 0)
(equal? v 0))
(list 0 0 0)
(let loop ((u u)
(v v)
(App 1)
(Ap 0)
(A #f)
(Bpp 0)
(Bp 1)
(B #f))
(if (equal? v 0)
(let ((c (leading-coefficient-gpe u x)))
(list (algebraic-expand (/ u c))
(algebraic-expand (/ App c))
(algebraic-expand (/ Bpp c))))
(let ((q (quotient u v x))
(r (remainder u v x)))
(let ((A (- App (* q Ap)))
(B (- Bpp (* q Bp))))
(loop v r Ap A A Bp B B))))))) | null | https://raw.githubusercontent.com/Metaxal/rascas/540530c28689de50c526abf36079c07fd0436edb/extended-euclidean-algorithm.rkt | racket | #lang racket/base
This file has been changed from its original dharmatech / mpl version .
(provide extended-euclidean-algorithm)
(require "arithmetic.rkt"
"leading-coefficient-gpe.rkt"
"algebraic-expand.rkt"
"polynomial-division.rkt")
(define (extended-euclidean-algorithm u v x)
(if (and (equal? u 0)
(equal? v 0))
(list 0 0 0)
(let loop ((u u)
(v v)
(App 1)
(Ap 0)
(A #f)
(Bpp 0)
(Bp 1)
(B #f))
(if (equal? v 0)
(let ((c (leading-coefficient-gpe u x)))
(list (algebraic-expand (/ u c))
(algebraic-expand (/ App c))
(algebraic-expand (/ Bpp c))))
(let ((q (quotient u v x))
(r (remainder u v x)))
(let ((A (- App (* q Ap)))
(B (- Bpp (* q Bp))))
(loop v r Ap A A Bp B B))))))) | |
8a6ae42cede911add15793bcf016ca9b47e8f443623ee07e0b00b9b96e9592d0 | 3b/parenscript | printer.lisp | (in-package #:parenscript)
(in-readtable :parenscript)
(defvar *ps-print-pretty* t)
(defvar *indent-num-spaces* 4)
(defvar *js-string-delimiter* #\'
"Specifies which character should be used for delimiting strings.
This variable is used when you want to embed the resulting JavaScript
in an html attribute delimited by #\\\" as opposed to #\\', or
vice-versa.")
(defvar *max-column-width* 78)
(defvar *indent-level*)
(defvar *column*)
(defvar *break-indent* nil)
(defvar *in-line-break?* nil)
(defvar *psw-stream*)
(defvar %printer-toplevel?)
(defun parenscript-print (form immediate?)
(declare (special immediate?))
(let ((*indent-level* 0)
(*column* 0)
(*psw-stream* (if immediate?
*psw-stream*
(make-string-output-stream)))
(%psw-accumulator ())
(%printer-toplevel? t))
(declare (special %psw-accumulator))
(with-standard-io-syntax
(if (and (listp form) (eq 'ps-js:block (car form))) ; ignore top-level block
(loop for (statement . remaining) on (cdr form) do
(ps-print statement) (psw #\;) (when remaining (psw #\Newline)))
(ps-print form)))
(unless immediate?
(reverse (cons (get-output-stream-string *psw-stream*)
%psw-accumulator)))))
(defun psw (&rest objs)
(dolist (obj objs)
(declare (special %psw-accumulator immediate?))
(typecase obj
(string
(incf *column* (length obj))
(write-string obj *psw-stream*))
(character
(if (eql obj #\Newline)
(setf *column* 0)
(incf *column*))
(write-char obj *psw-stream*))
(otherwise
(if immediate?
(let ((str (eval obj)))
(incf *column* (length str))
(write-string str *psw-stream*))
(progn
(when *in-line-break?*
;; this doesn't preserve *column* or *indent-level*
(throw 'stop-breaking 'stop-breaking))
(setf %psw-accumulator
(list* obj
(get-output-stream-string *psw-stream*)
%psw-accumulator))))))))
(defgeneric ps-print (form))
(defgeneric ps-print% (js-primitive args))
(defmethod ps-print :after (form)
(declare (ignore form))
(setf %printer-toplevel? nil))
(defmacro defprinter (js-primitive args &body body)
(if (listp js-primitive)
(cons 'progn (mapcar (lambda (p)
`(defprinter ,p ,args ,@body))
js-primitive))
(let ((pargs (gensym)))
`(defmethod ps-print% ((op (eql ',js-primitive)) ,pargs)
(declare (ignorable op))
(destructuring-bind ,args
,pargs
,@(loop for x in body collect
(if (or (characterp x)
(stringp x))
(list 'psw x)
x)))))))
(defmethod ps-print ((x null))
(psw "null"))
(defmethod ps-print ((x (eql t)))
(psw "true"))
(defmethod ps-print ((x (eql 'ps-js:f)))
(psw "false"))
(defmethod ps-print ((s symbol))
(if (keywordp s)
(ps-print (string-downcase s))
(psw (symbol-to-js-string s))))
(defmethod ps-print ((compiled-form cons))
(ps-print% (car compiled-form) (cdr compiled-form)))
(defun newline-and-indent ()
(if *ps-print-pretty*
(progn (psw #\Newline)
(loop repeat (if *break-indent*
*break-indent*
(* *indent-level* *indent-num-spaces*))
do (psw #\Space)))
(psw #\Space)))
(defmacro with-breakable-line (&body body)
`(progn (setf *break-indent* *column*)
,@body
(setf *break-indent* nil)))
(defmacro maybe-break-line (&body print-forms)
`(if (and *ps-print-pretty* *break-indent*)
(if (eq 'stop-breaking
(catch 'stop-breaking
(let ((result-str (let ((*indent-level* 0)
(*column* 0)
(*break-indent* nil)
(*in-line-break?* t))
(with-output-to-string (*psw-stream*)
,@print-forms))))
(if (> (+ *column* (length result-str)) *max-column-width*)
(progn (psw #\Newline)
(loop repeat *break-indent* do (psw #\Space))
(psw result-str))
(psw result-str)))))
(progn ,@print-forms nil)
t)
(progn ,@print-forms nil)))
(defun print-comment (comment-str)
(when *ps-print-pretty*
(let ((lines (cl-ppcre:split #\Newline comment-str)))
(if (cdr lines)
(progn (psw "/**") (newline-and-indent)
(dolist (x lines) (psw " * " x) (newline-and-indent))
(psw " */"))
(psw "/** " comment-str " */"))
(newline-and-indent))))
(defparameter *js-lisp-escaped-chars*
'((#\' . #\')
(#\\ . #\\)
(#\b . #\Backspace)
(#\f . #.(code-char 12))
(#\n . #\Newline)
(#\r . #\Return)
(#\t . #\Tab)))
(defmethod ps-print ((char character))
(ps-print (string char)))
(defmethod ps-print ((string string))
(flet ((lisp-special-char-to-js (lisp-char)
(car (rassoc lisp-char *js-lisp-escaped-chars*))))
(psw *js-string-delimiter*)
(loop for char across string
for code = (char-code char)
for special = (lisp-special-char-to-js char)
do (cond (special (psw #\\) (psw special))
((or (<= code #x1f) (>= code #x80))
(format *psw-stream* "\\u~:@(~4,'0x~)" code))
(t (psw char))))
(psw *js-string-delimiter*)))
(defmethod ps-print ((number number))
(format *psw-stream* (if (integerp number) "~D" "~F") number))
(defvar %equality-ops '(ps-js:== ps-js:!= ps-js:=== ps-js:!==))
(let ((precedence-table (make-hash-table :test 'eq)))
(loop for level in `((ps-js:getprop ps-js:aref ps-js:funcall)
(ps-js:new)
you wo n't find this in JS books
(ps-js:++ ps-js:-- ps-js:post++ ps-js:post--)
(ps-js:! ps-js:~ ps-js:negate ps-js:typeof ps-js:delete)
(ps-js:* ps-js:/ ps-js:%)
(ps-js:- ps-js:+)
(ps-js:<< ps-js:>> ps-js:>>>)
(ps-js:< ps-js:> ps-js:<= ps-js:>= ps-js:instanceof ps-js:in)
,%equality-ops
(ps-js:&)
(ps-js:^)
(ps-js:\|)
(ps-js:&&)
(ps-js:\|\|)
(ps-js:?)
(ps-js:= ps-js:*= ps-js:/= ps-js:%= ps-js:+= ps-js:-= ps-js:<<= ps-js:>>= ps-js:>>>= ps-js:&= ps-js:^= ps-js:\|=)
(ps-js:return ps-js:throw)
(ps-js:|,|))
for i from 0
do (mapc (lambda (symbol)
(setf (gethash symbol precedence-table) i))
level))
(defun precedence (op)
(gethash op precedence-table -1)))
(defun associative? (op)
(member op '(ps-js:* ps-js:& ps-js:&& ps-js:\| ps-js:\|\|
these are n't really associative , but RPN
(defun parenthesize-print (x)
(psw #\() (if (functionp x) (funcall x) (ps-print x)) (psw #\)))
(defun parenthesize-at-toplevel (x)
(if %printer-toplevel?
(parenthesize-print x)
(funcall x)))
(defun print-op-argument (op argument)
(setf %printer-toplevel? nil)
(let ((arg-op (when (listp argument) (car argument))))
(if (or (< (precedence op) (precedence arg-op))
(and (= (precedence op) (precedence arg-op))
(or (not (associative? op)) (not (associative? arg-op)))))
(parenthesize-print argument)
(ps-print argument))))
(defun print-op (op)
(psw (string-downcase op)))
(defprinter (ps-js:! ps-js:~ ps-js:++ ps-js:--) (x)
(print-op op) (print-op-argument op x))
(defprinter ps-js:negate (x)
"-"(print-op-argument op x))
(defprinter (ps-js:delete ps-js:typeof ps-js:new ps-js:throw) (x)
(print-op op)" "(print-op-argument op x))
(defprinter (ps-js:return) (&optional (x nil x?))
(print-op op)
(when x?
(psw " ") (print-op-argument op x)))
(defprinter ps-js:post++ (x)
(ps-print x)"++")
(defprinter ps-js:post-- (x)
(ps-print x)"--")
(defprinter (ps-js:+ ps-js:- ps-js:* ps-js:/ ps-js:% ps-js:&& ps-js:\|\| ps-js:& ps-js:\| ps-js:-= ps-js:+= ps-js:*= ps-js:/= ps-js:%= ps-js:^ ps-js:<< ps-js:>> ps-js:&= ps-js:^= ps-js:\|= ps-js:= ps-js:in ps-js:> ps-js:>= ps-js:< ps-js:<=)
(&rest args)
(loop for (arg . remaining) on args do
(maybe-break-line (print-op-argument op arg))
(when remaining (format *psw-stream* " ~(~A~) " op))))
(defprinter (ps-js:== ps-js:!= ps-js:=== ps-js:!==) (x y)
(flet ((parenthesize-equality (form)
(if (and (consp form) (member (car form) %equality-ops))
(parenthesize-print form)
(print-op-argument op form))))
(parenthesize-equality x)
(format *psw-stream* " ~A " op)
(maybe-break-line (parenthesize-equality y))))
(defprinter ps-js:aref (array &rest indices)
(print-op-argument 'ps-js:aref array)
(dolist (idx indices)
(psw #\[) (ps-print idx) (psw #\])))
(defun print-comma-delimited-list (ps-forms)
(loop for (form . remaining) on ps-forms do
(maybe-break-line (print-op-argument 'ps-js:|,| form))
(when remaining (psw ", "))))
(defprinter ps-js:array (&rest initial-contents)
"["(print-comma-delimited-list initial-contents)"]")
(defprinter (ps-js:|,|) (&rest expressions)
(with-breakable-line (print-comma-delimited-list expressions)))
(defprinter ps-js:funcall (fun-designator &rest args)
(print-op-argument op fun-designator)"("(print-comma-delimited-list args)")")
(defprinter ps-js:block (&rest statements)
"{" (incf *indent-level*)
(dolist (statement statements)
(newline-and-indent) (ps-print statement) (psw #\;))
(decf *indent-level*) (newline-and-indent)
"}")
(defprinter ps-js:lambda (args body-block)
(parenthesize-at-toplevel
(lambda () (print-fun-def nil args body-block))))
(defprinter ps-js:defun (name args docstring body-block)
(when docstring (print-comment docstring))
(print-fun-def name args body-block))
(defun print-fun-def (name args body)
(format *psw-stream* "function ~:[~;~A~](" name (symbol-to-js-string name))
(loop for (arg . remaining) on args do
(psw (symbol-to-js-string arg)) (when remaining (psw ", ")))
(psw ") ")
(ps-print body))
(defprinter ps-js:object (&rest slot-defs)
(parenthesize-at-toplevel
(lambda ()
(psw "{ ")
(with-breakable-line
(loop for ((slot-name . slot-value) . remaining) on slot-defs do
(maybe-break-line
(ps-print slot-name) (psw " : ")
(if (and (consp slot-value) (eq 'ps-js:|,| (car slot-value)))
(parenthesize-print slot-value)
(ps-print slot-value)))
(when remaining (psw ", "))))
(psw " }"))))
(defprinter ps-js:getprop (obj slot)
(print-op-argument op obj)"."(psw (symbol-to-js-string slot)))
(defprinter ps-js:if (test consequent &rest clauses)
"if (" (with-breakable-line (ps-print test)) ") "
(ps-print consequent)
(loop while clauses do
(ecase (car clauses)
(:else-if (psw " else if (") (ps-print (cadr clauses)) (psw ") ")
(ps-print (caddr clauses))
(setf clauses (cdddr clauses)))
(:else (psw " else ")
(ps-print (cadr clauses))
(return)))))
(defprinter ps-js:? (test then else)
(print-op-argument op test) " ? "
(print-op-argument op then) " : "
(print-op-argument op else))
(defprinter ps-js:var (var-name &optional (value (values) value?) docstring)
(when docstring (print-comment docstring))
"var "(psw (symbol-to-js-string var-name))
(when value? (psw " = ") (print-op-argument 'ps-js:= value)))
(defprinter ps-js:label (label statement)
(psw (symbol-to-js-string label))": "(ps-print statement))
(defprinter (ps-js:continue ps-js:break) (&optional label)
(print-op op) (when label
(psw " " (symbol-to-js-string label))))
;;; iteration
(defprinter ps-js:for (vars tests steps body-block)
(psw "for (")
(with-breakable-line
(loop for ((var-name . var-init) . remaining) on vars
for decl = "var " then "" do
(psw decl (symbol-to-js-string var-name) " = ") (ps-print var-init)
(when remaining (psw ", ")))
(psw "; ")
(let ((broken?
(maybe-break-line
(loop for (test . remaining) on tests do
(ps-print test) (when remaining (psw ", "))))))
(psw ";")
(if broken? (newline-and-indent) (psw " "))
(loop for (step . remaining) on steps do
(ps-print step) (when remaining (psw ", "))))
(psw ") "))
(ps-print body-block))
(defprinter ps-js:for-in (var object body-block)
"for (var "(ps-print var)" in "(ps-print object)") "
(ps-print body-block))
(defprinter (ps-js:with ps-js:while) (expression body-block)
(print-op op)" ("(ps-print expression)") "
(ps-print body-block))
(defprinter ps-js:switch (test &rest clauses)
"switch ("(ps-print test)") {"
(flet ((print-body-statements (body-statements)
(incf *indent-level*)
(loop for statement in body-statements do
(progn (newline-and-indent)
(ps-print statement)
(psw #\;)))
(decf *indent-level*)))
(loop for (val . statements) in clauses
do (progn (newline-and-indent)
(if (eq val 'ps-js:default)
(progn (psw "default:")
(print-body-statements statements))
(progn (psw "case ") (ps-print val) (psw #\:)
(print-body-statements statements))))))
(newline-and-indent)
"}")
(defprinter ps-js:try (body-block &key catch finally)
"try "(ps-print body-block)
(when catch
(psw " catch ("(symbol-to-js-string (first catch))") ")
(ps-print (second catch)))
(when finally
(psw " finally ") (ps-print finally)))
(defprinter ps-js:regex (regex)
(let ((slash (unless (and (> (length regex) 0) (char= (char regex 0) #\/)) "/")))
(psw (concatenate 'string slash regex slash))))
(defprinter ps-js:instanceof (value type)
"("(print-op-argument op value)" instanceof "(print-op-argument op type)")")
(defprinter ps-js:escape (literal-js)
;; literal-js should be a form that evaluates to a string containing
valid JavaScript
(psw literal-js))
| null | https://raw.githubusercontent.com/3b/parenscript/cb4a605ef0ac4fcea1e0ccec23d5748cee613cc3/src/printer.lisp | lisp | ignore top-level block
) (when remaining (psw #\Newline)))
this doesn't preserve *column* or *indent-level*
))
iteration
)))
literal-js should be a form that evaluates to a string containing | (in-package #:parenscript)
(in-readtable :parenscript)
(defvar *ps-print-pretty* t)
(defvar *indent-num-spaces* 4)
(defvar *js-string-delimiter* #\'
"Specifies which character should be used for delimiting strings.
This variable is used when you want to embed the resulting JavaScript
in an html attribute delimited by #\\\" as opposed to #\\', or
vice-versa.")
(defvar *max-column-width* 78)
(defvar *indent-level*)
(defvar *column*)
(defvar *break-indent* nil)
(defvar *in-line-break?* nil)
(defvar *psw-stream*)
(defvar %printer-toplevel?)
(defun parenscript-print (form immediate?)
(declare (special immediate?))
(let ((*indent-level* 0)
(*column* 0)
(*psw-stream* (if immediate?
*psw-stream*
(make-string-output-stream)))
(%psw-accumulator ())
(%printer-toplevel? t))
(declare (special %psw-accumulator))
(with-standard-io-syntax
(loop for (statement . remaining) on (cdr form) do
(ps-print form)))
(unless immediate?
(reverse (cons (get-output-stream-string *psw-stream*)
%psw-accumulator)))))
(defun psw (&rest objs)
(dolist (obj objs)
(declare (special %psw-accumulator immediate?))
(typecase obj
(string
(incf *column* (length obj))
(write-string obj *psw-stream*))
(character
(if (eql obj #\Newline)
(setf *column* 0)
(incf *column*))
(write-char obj *psw-stream*))
(otherwise
(if immediate?
(let ((str (eval obj)))
(incf *column* (length str))
(write-string str *psw-stream*))
(progn
(when *in-line-break?*
(throw 'stop-breaking 'stop-breaking))
(setf %psw-accumulator
(list* obj
(get-output-stream-string *psw-stream*)
%psw-accumulator))))))))
(defgeneric ps-print (form))
(defgeneric ps-print% (js-primitive args))
(defmethod ps-print :after (form)
(declare (ignore form))
(setf %printer-toplevel? nil))
(defmacro defprinter (js-primitive args &body body)
(if (listp js-primitive)
(cons 'progn (mapcar (lambda (p)
`(defprinter ,p ,args ,@body))
js-primitive))
(let ((pargs (gensym)))
`(defmethod ps-print% ((op (eql ',js-primitive)) ,pargs)
(declare (ignorable op))
(destructuring-bind ,args
,pargs
,@(loop for x in body collect
(if (or (characterp x)
(stringp x))
(list 'psw x)
x)))))))
(defmethod ps-print ((x null))
(psw "null"))
(defmethod ps-print ((x (eql t)))
(psw "true"))
(defmethod ps-print ((x (eql 'ps-js:f)))
(psw "false"))
(defmethod ps-print ((s symbol))
(if (keywordp s)
(ps-print (string-downcase s))
(psw (symbol-to-js-string s))))
(defmethod ps-print ((compiled-form cons))
(ps-print% (car compiled-form) (cdr compiled-form)))
(defun newline-and-indent ()
(if *ps-print-pretty*
(progn (psw #\Newline)
(loop repeat (if *break-indent*
*break-indent*
(* *indent-level* *indent-num-spaces*))
do (psw #\Space)))
(psw #\Space)))
(defmacro with-breakable-line (&body body)
`(progn (setf *break-indent* *column*)
,@body
(setf *break-indent* nil)))
(defmacro maybe-break-line (&body print-forms)
`(if (and *ps-print-pretty* *break-indent*)
(if (eq 'stop-breaking
(catch 'stop-breaking
(let ((result-str (let ((*indent-level* 0)
(*column* 0)
(*break-indent* nil)
(*in-line-break?* t))
(with-output-to-string (*psw-stream*)
,@print-forms))))
(if (> (+ *column* (length result-str)) *max-column-width*)
(progn (psw #\Newline)
(loop repeat *break-indent* do (psw #\Space))
(psw result-str))
(psw result-str)))))
(progn ,@print-forms nil)
t)
(progn ,@print-forms nil)))
(defun print-comment (comment-str)
(when *ps-print-pretty*
(let ((lines (cl-ppcre:split #\Newline comment-str)))
(if (cdr lines)
(progn (psw "/**") (newline-and-indent)
(dolist (x lines) (psw " * " x) (newline-and-indent))
(psw " */"))
(psw "/** " comment-str " */"))
(newline-and-indent))))
(defparameter *js-lisp-escaped-chars*
'((#\' . #\')
(#\\ . #\\)
(#\b . #\Backspace)
(#\f . #.(code-char 12))
(#\n . #\Newline)
(#\r . #\Return)
(#\t . #\Tab)))
(defmethod ps-print ((char character))
(ps-print (string char)))
(defmethod ps-print ((string string))
(flet ((lisp-special-char-to-js (lisp-char)
(car (rassoc lisp-char *js-lisp-escaped-chars*))))
(psw *js-string-delimiter*)
(loop for char across string
for code = (char-code char)
for special = (lisp-special-char-to-js char)
do (cond (special (psw #\\) (psw special))
((or (<= code #x1f) (>= code #x80))
(format *psw-stream* "\\u~:@(~4,'0x~)" code))
(t (psw char))))
(psw *js-string-delimiter*)))
(defmethod ps-print ((number number))
(format *psw-stream* (if (integerp number) "~D" "~F") number))
(defvar %equality-ops '(ps-js:== ps-js:!= ps-js:=== ps-js:!==))
(let ((precedence-table (make-hash-table :test 'eq)))
(loop for level in `((ps-js:getprop ps-js:aref ps-js:funcall)
(ps-js:new)
you wo n't find this in JS books
(ps-js:++ ps-js:-- ps-js:post++ ps-js:post--)
(ps-js:! ps-js:~ ps-js:negate ps-js:typeof ps-js:delete)
(ps-js:* ps-js:/ ps-js:%)
(ps-js:- ps-js:+)
(ps-js:<< ps-js:>> ps-js:>>>)
(ps-js:< ps-js:> ps-js:<= ps-js:>= ps-js:instanceof ps-js:in)
,%equality-ops
(ps-js:&)
(ps-js:^)
(ps-js:\|)
(ps-js:&&)
(ps-js:\|\|)
(ps-js:?)
(ps-js:= ps-js:*= ps-js:/= ps-js:%= ps-js:+= ps-js:-= ps-js:<<= ps-js:>>= ps-js:>>>= ps-js:&= ps-js:^= ps-js:\|=)
(ps-js:return ps-js:throw)
(ps-js:|,|))
for i from 0
do (mapc (lambda (symbol)
(setf (gethash symbol precedence-table) i))
level))
(defun precedence (op)
(gethash op precedence-table -1)))
(defun associative? (op)
(member op '(ps-js:* ps-js:& ps-js:&& ps-js:\| ps-js:\|\|
these are n't really associative , but RPN
(defun parenthesize-print (x)
(psw #\() (if (functionp x) (funcall x) (ps-print x)) (psw #\)))
(defun parenthesize-at-toplevel (x)
(if %printer-toplevel?
(parenthesize-print x)
(funcall x)))
(defun print-op-argument (op argument)
(setf %printer-toplevel? nil)
(let ((arg-op (when (listp argument) (car argument))))
(if (or (< (precedence op) (precedence arg-op))
(and (= (precedence op) (precedence arg-op))
(or (not (associative? op)) (not (associative? arg-op)))))
(parenthesize-print argument)
(ps-print argument))))
(defun print-op (op)
(psw (string-downcase op)))
(defprinter (ps-js:! ps-js:~ ps-js:++ ps-js:--) (x)
(print-op op) (print-op-argument op x))
(defprinter ps-js:negate (x)
"-"(print-op-argument op x))
(defprinter (ps-js:delete ps-js:typeof ps-js:new ps-js:throw) (x)
(print-op op)" "(print-op-argument op x))
(defprinter (ps-js:return) (&optional (x nil x?))
(print-op op)
(when x?
(psw " ") (print-op-argument op x)))
(defprinter ps-js:post++ (x)
(ps-print x)"++")
(defprinter ps-js:post-- (x)
(ps-print x)"--")
(defprinter (ps-js:+ ps-js:- ps-js:* ps-js:/ ps-js:% ps-js:&& ps-js:\|\| ps-js:& ps-js:\| ps-js:-= ps-js:+= ps-js:*= ps-js:/= ps-js:%= ps-js:^ ps-js:<< ps-js:>> ps-js:&= ps-js:^= ps-js:\|= ps-js:= ps-js:in ps-js:> ps-js:>= ps-js:< ps-js:<=)
(&rest args)
(loop for (arg . remaining) on args do
(maybe-break-line (print-op-argument op arg))
(when remaining (format *psw-stream* " ~(~A~) " op))))
(defprinter (ps-js:== ps-js:!= ps-js:=== ps-js:!==) (x y)
(flet ((parenthesize-equality (form)
(if (and (consp form) (member (car form) %equality-ops))
(parenthesize-print form)
(print-op-argument op form))))
(parenthesize-equality x)
(format *psw-stream* " ~A " op)
(maybe-break-line (parenthesize-equality y))))
(defprinter ps-js:aref (array &rest indices)
(print-op-argument 'ps-js:aref array)
(dolist (idx indices)
(psw #\[) (ps-print idx) (psw #\])))
(defun print-comma-delimited-list (ps-forms)
(loop for (form . remaining) on ps-forms do
(maybe-break-line (print-op-argument 'ps-js:|,| form))
(when remaining (psw ", "))))
(defprinter ps-js:array (&rest initial-contents)
"["(print-comma-delimited-list initial-contents)"]")
(defprinter (ps-js:|,|) (&rest expressions)
(with-breakable-line (print-comma-delimited-list expressions)))
(defprinter ps-js:funcall (fun-designator &rest args)
(print-op-argument op fun-designator)"("(print-comma-delimited-list args)")")
(defprinter ps-js:block (&rest statements)
"{" (incf *indent-level*)
(dolist (statement statements)
(decf *indent-level*) (newline-and-indent)
"}")
(defprinter ps-js:lambda (args body-block)
(parenthesize-at-toplevel
(lambda () (print-fun-def nil args body-block))))
(defprinter ps-js:defun (name args docstring body-block)
(when docstring (print-comment docstring))
(print-fun-def name args body-block))
(defun print-fun-def (name args body)
(format *psw-stream* "function ~:[~;~A~](" name (symbol-to-js-string name))
(loop for (arg . remaining) on args do
(psw (symbol-to-js-string arg)) (when remaining (psw ", ")))
(psw ") ")
(ps-print body))
(defprinter ps-js:object (&rest slot-defs)
(parenthesize-at-toplevel
(lambda ()
(psw "{ ")
(with-breakable-line
(loop for ((slot-name . slot-value) . remaining) on slot-defs do
(maybe-break-line
(ps-print slot-name) (psw " : ")
(if (and (consp slot-value) (eq 'ps-js:|,| (car slot-value)))
(parenthesize-print slot-value)
(ps-print slot-value)))
(when remaining (psw ", "))))
(psw " }"))))
(defprinter ps-js:getprop (obj slot)
(print-op-argument op obj)"."(psw (symbol-to-js-string slot)))
(defprinter ps-js:if (test consequent &rest clauses)
"if (" (with-breakable-line (ps-print test)) ") "
(ps-print consequent)
(loop while clauses do
(ecase (car clauses)
(:else-if (psw " else if (") (ps-print (cadr clauses)) (psw ") ")
(ps-print (caddr clauses))
(setf clauses (cdddr clauses)))
(:else (psw " else ")
(ps-print (cadr clauses))
(return)))))
(defprinter ps-js:? (test then else)
(print-op-argument op test) " ? "
(print-op-argument op then) " : "
(print-op-argument op else))
(defprinter ps-js:var (var-name &optional (value (values) value?) docstring)
(when docstring (print-comment docstring))
"var "(psw (symbol-to-js-string var-name))
(when value? (psw " = ") (print-op-argument 'ps-js:= value)))
(defprinter ps-js:label (label statement)
(psw (symbol-to-js-string label))": "(ps-print statement))
(defprinter (ps-js:continue ps-js:break) (&optional label)
(print-op op) (when label
(psw " " (symbol-to-js-string label))))
(defprinter ps-js:for (vars tests steps body-block)
(psw "for (")
(with-breakable-line
(loop for ((var-name . var-init) . remaining) on vars
for decl = "var " then "" do
(psw decl (symbol-to-js-string var-name) " = ") (ps-print var-init)
(when remaining (psw ", ")))
(psw "; ")
(let ((broken?
(maybe-break-line
(loop for (test . remaining) on tests do
(ps-print test) (when remaining (psw ", "))))))
(psw ";")
(if broken? (newline-and-indent) (psw " "))
(loop for (step . remaining) on steps do
(ps-print step) (when remaining (psw ", "))))
(psw ") "))
(ps-print body-block))
(defprinter ps-js:for-in (var object body-block)
"for (var "(ps-print var)" in "(ps-print object)") "
(ps-print body-block))
(defprinter (ps-js:with ps-js:while) (expression body-block)
(print-op op)" ("(ps-print expression)") "
(ps-print body-block))
(defprinter ps-js:switch (test &rest clauses)
"switch ("(ps-print test)") {"
(flet ((print-body-statements (body-statements)
(incf *indent-level*)
(loop for statement in body-statements do
(progn (newline-and-indent)
(ps-print statement)
(decf *indent-level*)))
(loop for (val . statements) in clauses
do (progn (newline-and-indent)
(if (eq val 'ps-js:default)
(progn (psw "default:")
(print-body-statements statements))
(progn (psw "case ") (ps-print val) (psw #\:)
(print-body-statements statements))))))
(newline-and-indent)
"}")
(defprinter ps-js:try (body-block &key catch finally)
"try "(ps-print body-block)
(when catch
(psw " catch ("(symbol-to-js-string (first catch))") ")
(ps-print (second catch)))
(when finally
(psw " finally ") (ps-print finally)))
(defprinter ps-js:regex (regex)
(let ((slash (unless (and (> (length regex) 0) (char= (char regex 0) #\/)) "/")))
(psw (concatenate 'string slash regex slash))))
(defprinter ps-js:instanceof (value type)
"("(print-op-argument op value)" instanceof "(print-op-argument op type)")")
(defprinter ps-js:escape (literal-js)
valid JavaScript
(psw literal-js))
|
cf36bb4119ceade7c8475cbc9cc6393c6005a3809e8ade27a769c49f93d54221 | openbadgefactory/salava | helper.cljs | (ns salava.translator.ui.helper
(:require [salava.core.i18n :refer [t t+]]
[reagent.session :as session]))
(defn translate [lang key]
(if (session/get :user)
(t key)
(t+ lang key)))
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/cljs/salava/translator/ui/helper.cljs | clojure | (ns salava.translator.ui.helper
(:require [salava.core.i18n :refer [t t+]]
[reagent.session :as session]))
(defn translate [lang key]
(if (session/get :user)
(t key)
(t+ lang key)))
| |
4551b681183dd098d680e45241e5ce26dd50549d926f3073e440d72a8daea3ce | namin/biohacker | adj.lisp | (in-package :ecocyc)
Copyright ( C ) 1993 - 2004 by SRI International . All rights reserved .
; This file contains functions that convert the representation of molecules
used in the CompoundKB into an adjacency - list representation that is much
; more convenient to use for certain computations.
; ======================================================= adj-list
; A shorthand for calling make-adj-list
(defun adj-list (compound)
(make-adj-list
(get-slot-values compound 'structure-atoms)
(get-slot-values compound 'structure-bonds)
(get-slot-values compound 'atom-charges)
) )
; ======================================================= make-adj-list
; Creates an adj-list describing a chemical structure. The list has
one element per atom in the structure . The CAR of each element is
; the name of an atom, and the CDR is a bond list; the CAR of each
; element of that bond list is the index in the adj-list of the bonded
atom , and the CDR is the type of bond . We use an index origin of 1
; for consistency with structure-atoms. An atom charge of +2 is encoded
; as a bond of (+ 2)
;
; Example for carbon dioxide:
;
( ( C ( 3 2 ) ( 2 2 ) )
( O ( 1 2 ) )
( O ( 1 2 ) ) )
(defun make-adj-list (atom-list bond-list &optional charge-list)
(let ((adj-list nil))
(setq adj-list (list (list (first atom-list))))
(dolist (atom (cdr atom-list))
(nconc adj-list (list (list atom))) )
(dolist (bond bond-list)
(rplacd (adj-i adj-list (car bond))
(cons (list (cadr bond)
(caddr bond))
(cdr (adj-i adj-list (car bond))))
)
(rplacd (adj-i adj-list (cadr bond))
(cons (list (car bond)
(caddr bond))
(cdr (adj-i adj-list (cadr bond))))
)
)
(dolist (charge charge-list)
(rplacd (adj-i adj-list (car charge))
(cons (list (if (> (cadr charge) 0)
'+
'-)
(abs (cadr charge)))
(cdr (adj-i adj-list (car charge))))))
adj-list
))
; ================================================== adj-compute-weight
(defun adj-compute-weight (adjlist)
(let ((weight 0.0))
(dolist (adj adjlist)
(setq weight (+ weight
(or
(when (and adj ; kr97-07-28: inserted this test to become NIL-tolerant
kr98 - 05 - 20 : added this test as well , to
;; tolerate weird elements
(coercible-to-frame-p (first adj)) )
(gfp:get-slot-value (first adj) 'atomic-weight) )
0.0) ))
)
weight
))
; ======================================================= compute-formula-from-adj
;; Compute the empirical formula of an adj-list. This function does not
;; hydrogenate the adj-list, therefore the resulting formula may omit
;; hydrogens if the original adj-list does.
(defun compute-formula-from-adj (adjlist)
(let ((formula nil)
atom f)
(dolist (adj adjlist)
(setq atom (first adj))
(if (setq f (assoc atom formula))
(rplaca (cdr f)
(1+ (second f)))
(push (list atom 1)
formula) )
)
(order-formula formula)
) )
(defun entry-adj-list (entry)
(make-adj-list (get-slot-values entry 'structure-atoms)
(get-slot-values entry 'structure-bonds)
(get-slot-values entry 'atom-charges))
)
(defun adj-i (adj-list i)
(nth (1- i) adj-list)
)
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/metabolizer/adj.lisp | lisp | This file contains functions that convert the representation of molecules
more convenient to use for certain computations.
======================================================= adj-list
A shorthand for calling make-adj-list
======================================================= make-adj-list
Creates an adj-list describing a chemical structure. The list has
the name of an atom, and the CDR is a bond list; the CAR of each
element of that bond list is the index in the adj-list of the bonded
for consistency with structure-atoms. An atom charge of +2 is encoded
as a bond of (+ 2)
Example for carbon dioxide:
================================================== adj-compute-weight
kr97-07-28: inserted this test to become NIL-tolerant
tolerate weird elements
======================================================= compute-formula-from-adj
Compute the empirical formula of an adj-list. This function does not
hydrogenate the adj-list, therefore the resulting formula may omit
hydrogens if the original adj-list does. | (in-package :ecocyc)
Copyright ( C ) 1993 - 2004 by SRI International . All rights reserved .
used in the CompoundKB into an adjacency - list representation that is much
(defun adj-list (compound)
(make-adj-list
(get-slot-values compound 'structure-atoms)
(get-slot-values compound 'structure-bonds)
(get-slot-values compound 'atom-charges)
) )
one element per atom in the structure . The CAR of each element is
atom , and the CDR is the type of bond . We use an index origin of 1
( ( C ( 3 2 ) ( 2 2 ) )
( O ( 1 2 ) )
( O ( 1 2 ) ) )
(defun make-adj-list (atom-list bond-list &optional charge-list)
(let ((adj-list nil))
(setq adj-list (list (list (first atom-list))))
(dolist (atom (cdr atom-list))
(nconc adj-list (list (list atom))) )
(dolist (bond bond-list)
(rplacd (adj-i adj-list (car bond))
(cons (list (cadr bond)
(caddr bond))
(cdr (adj-i adj-list (car bond))))
)
(rplacd (adj-i adj-list (cadr bond))
(cons (list (car bond)
(caddr bond))
(cdr (adj-i adj-list (cadr bond))))
)
)
(dolist (charge charge-list)
(rplacd (adj-i adj-list (car charge))
(cons (list (if (> (cadr charge) 0)
'+
'-)
(abs (cadr charge)))
(cdr (adj-i adj-list (car charge))))))
adj-list
))
(defun adj-compute-weight (adjlist)
(let ((weight 0.0))
(dolist (adj adjlist)
(setq weight (+ weight
(or
kr98 - 05 - 20 : added this test as well , to
(coercible-to-frame-p (first adj)) )
(gfp:get-slot-value (first adj) 'atomic-weight) )
0.0) ))
)
weight
))
(defun compute-formula-from-adj (adjlist)
(let ((formula nil)
atom f)
(dolist (adj adjlist)
(setq atom (first adj))
(if (setq f (assoc atom formula))
(rplaca (cdr f)
(1+ (second f)))
(push (list atom 1)
formula) )
)
(order-formula formula)
) )
(defun entry-adj-list (entry)
(make-adj-list (get-slot-values entry 'structure-atoms)
(get-slot-values entry 'structure-bonds)
(get-slot-values entry 'atom-charges))
)
(defun adj-i (adj-list i)
(nth (1- i) adj-list)
)
|
bcd8ab868799f99ed0c6a8aaf69833864d6a3de5c86d264e3a6e685b628e4088 | Lovesan/doors | memory.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
Copyright ( C ) 2010 - 2011 , < >
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE
(in-package #:doors)
(define-enum (memory-protection-flags
(:base-type dword)
(:list t)
(:conc-name page-))
(:execute #x10)
(:execute-read #x20)
(:execute-read-write #x40)
(:execute-read-write-copy #x80)
(:no-access #x1)
(:read-only #x02)
(:read-write #x04)
(:write-copy #x08)
(:guard #x100)
(:no-cache #x200)
(:write-combine #x400))
| null | https://raw.githubusercontent.com/Lovesan/doors/12a2fe2fd8d6c42ae314bd6d02a1d2332f12499e/system/memory.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE |
Copyright ( C ) 2010 - 2011 , < >
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:doors)
(define-enum (memory-protection-flags
(:base-type dword)
(:list t)
(:conc-name page-))
(:execute #x10)
(:execute-read #x20)
(:execute-read-write #x40)
(:execute-read-write-copy #x80)
(:no-access #x1)
(:read-only #x02)
(:read-write #x04)
(:write-copy #x08)
(:guard #x100)
(:no-cache #x200)
(:write-combine #x400))
|
d102d029c98e4a89717854838af7f15d8546526479d2a4e442fa329d31617c7a | robx/puzzle-draw | Code.hs | module Data.Code where
import Data.Grid
import Data.GridShape
import Data.Map.Strict (Map)
type Code = [CodePart]
data CodePart
= -- | Rows of cells, counted from the bottom.
Rows' [Int]
| -- | Cols of cells, counted from the left.
Cols [Int]
| -- | Rows of nodes, counted from the bottom.
RowsN' [Int]
| -- | Cols of nodes, counted from the left.
ColsN [Int]
| Nodes , labeld by letters .
LabelsN (Grid N (Maybe Char))
| -- | Rows of cells, counted from the bottom.
LRows' (Map Char Int)
| -- | Cols of cells, counted from the left.
LCols (Map Char Int)
| -- | Rows of nodes, counted from the bottom.
LRowsN' (Map Char Int)
| -- | Cols of nodes, counted from the left.
LColsN (Map Char Int)
| null | https://raw.githubusercontent.com/robx/puzzle-draw/936f4c9bf8ff576fb657b7c05067504734adae14/src/Data/Code.hs | haskell | | Rows of cells, counted from the bottom.
| Cols of cells, counted from the left.
| Rows of nodes, counted from the bottom.
| Cols of nodes, counted from the left.
| Rows of cells, counted from the bottom.
| Cols of cells, counted from the left.
| Rows of nodes, counted from the bottom.
| Cols of nodes, counted from the left. | module Data.Code where
import Data.Grid
import Data.GridShape
import Data.Map.Strict (Map)
type Code = [CodePart]
data CodePart
Rows' [Int]
Cols [Int]
RowsN' [Int]
ColsN [Int]
| Nodes , labeld by letters .
LabelsN (Grid N (Maybe Char))
LRows' (Map Char Int)
LCols (Map Char Int)
LRowsN' (Map Char Int)
LColsN (Map Char Int)
|
a6a16758849eda0fc569f90c2249a96dc2ce2ad43671af6c79c782518b68ff28 | dbuenzli/brr | pkg.ml | #!/usr/bin/env ocaml
#use "topfind"
#require "topkg"
open Topkg
let () =
Pkg.describe "brr" @@ fun c ->
Ok [ Pkg.mllib "src/brr.mllib";
Pkg.mllib "src/note/brr_note.mllib" ~dst_dir:"note/";
Pkg.mllib "src/ocaml_poke/brr_ocaml_poke.mllib" ~dst_dir:"ocaml_poke/";
Pkg.mllib "src/ocaml_poke_ui/brr_ocaml_poke_ui.mllib" ~dst_dir:"ocaml_poke_ui/";
Pkg.mllib "src/poke/brr_poke.mllib" ~dst_dir:"poke/";
Pkg.mllib "src/poked/brr_poked.mllib" ~dst_dir:"poked/";
Pkg.share "src/console/devtools.html" ~dst:"console/";
Pkg.share "src/console/devtools.js" ~dst:"console/";
Pkg.share "src/console/highlight.pack.js" ~dst:"console/";
Pkg.share "src/console/manifest.json" ~dst:"console/";
Pkg.share "src/console/ocaml.png" ~dst:"console/";
Pkg.share "src/console/ocaml_console.css" ~dst:"console/";
Pkg.share "src/console/ocaml_console.html" ~dst:"console/";
Pkg.share "src/console/ocaml_console.js" ~dst:"console/";
(* Samples *)
Pkg.doc "test/poke.ml";
(* Doc *)
Pkg.doc "doc/index.mld" ~dst:"odoc-pages/index.mld";
Pkg.doc "doc/ffi_manual.mld" ~dst:"odoc-pages/ffi_manual.mld";
Pkg.doc "doc/ffi_cookbook.mld" ~dst:"odoc-pages/ffi_cookbook.mld";
Pkg.doc "doc/ocaml_console.mld" ~dst:"odoc-pages/ocaml_console.mld";
Pkg.doc "doc/web_page_howto.mld" ~dst:"odoc-pages/web_page_howto.mld";
Pkg.doc ~built:false "doc/note_ui_sample.png" ~dst:"odoc-assets/";
Pkg.doc ~built:false "doc/ocaml_console.png" ~dst:"odoc-assets/";
]
| null | https://raw.githubusercontent.com/dbuenzli/brr/3d1a0edd964a1ddfbf2be515fc3a3803d27ad707/pkg/pkg.ml | ocaml | Samples
Doc | #!/usr/bin/env ocaml
#use "topfind"
#require "topkg"
open Topkg
let () =
Pkg.describe "brr" @@ fun c ->
Ok [ Pkg.mllib "src/brr.mllib";
Pkg.mllib "src/note/brr_note.mllib" ~dst_dir:"note/";
Pkg.mllib "src/ocaml_poke/brr_ocaml_poke.mllib" ~dst_dir:"ocaml_poke/";
Pkg.mllib "src/ocaml_poke_ui/brr_ocaml_poke_ui.mllib" ~dst_dir:"ocaml_poke_ui/";
Pkg.mllib "src/poke/brr_poke.mllib" ~dst_dir:"poke/";
Pkg.mllib "src/poked/brr_poked.mllib" ~dst_dir:"poked/";
Pkg.share "src/console/devtools.html" ~dst:"console/";
Pkg.share "src/console/devtools.js" ~dst:"console/";
Pkg.share "src/console/highlight.pack.js" ~dst:"console/";
Pkg.share "src/console/manifest.json" ~dst:"console/";
Pkg.share "src/console/ocaml.png" ~dst:"console/";
Pkg.share "src/console/ocaml_console.css" ~dst:"console/";
Pkg.share "src/console/ocaml_console.html" ~dst:"console/";
Pkg.share "src/console/ocaml_console.js" ~dst:"console/";
Pkg.doc "test/poke.ml";
Pkg.doc "doc/index.mld" ~dst:"odoc-pages/index.mld";
Pkg.doc "doc/ffi_manual.mld" ~dst:"odoc-pages/ffi_manual.mld";
Pkg.doc "doc/ffi_cookbook.mld" ~dst:"odoc-pages/ffi_cookbook.mld";
Pkg.doc "doc/ocaml_console.mld" ~dst:"odoc-pages/ocaml_console.mld";
Pkg.doc "doc/web_page_howto.mld" ~dst:"odoc-pages/web_page_howto.mld";
Pkg.doc ~built:false "doc/note_ui_sample.png" ~dst:"odoc-assets/";
Pkg.doc ~built:false "doc/ocaml_console.png" ~dst:"odoc-assets/";
]
|
b31e6919227bede1ce8ff38db1fbe78b22b948e2cedc52f51fc3eb0df5a1a7ba | audreyt/openafp | AV.hs | module OpenAFP.Records.T.AV where
import OpenAFP.Types
import OpenAFP.Internals
data T_AV = T_AV {
t_av_Type :: !N1
,t_av :: !AStr
} deriving (Show, Typeable)
| null | https://raw.githubusercontent.com/audreyt/openafp/178e0dd427479ac7b8b461e05c263e52dd614b73/src/OpenAFP/Records/T/AV.hs | haskell | module OpenAFP.Records.T.AV where
import OpenAFP.Types
import OpenAFP.Internals
data T_AV = T_AV {
t_av_Type :: !N1
,t_av :: !AStr
} deriving (Show, Typeable)
| |
6405d9da9c7ade78be64f8063bdf24a43b97004feb90234cba0ed717980cc4c6 | input-output-hk/ouroboros-network | Conway.hs | {-# LANGUAGE EmptyDataDeriving #-}
-- TODO DUPLICATE? -- as-if adapted? from: cardano-node/src/Cardano/Node/Protocol/Conway.hs
module Cardano.Node.Protocol.Conway (
ConwayProtocolInstantiationError
-- * Reusable parts
, readGenesis
, validateGenesis
) where
import Cardano.Prelude
import qualified Cardano.Ledger.Conway.Genesis as Conway
import qualified Cardano.Ledger.Crypto as Crypto
import Cardano.Node.Protocol.Shelley (GenesisReadError,
readGenesisAny)
import Cardano.Node.Types
--
Conway genesis
--
readGenesis :: Crypto.Crypto c
=> GenesisFile
-> Maybe GenesisHash
-> ExceptT GenesisReadError IO
(Conway.ConwayGenesis c, GenesisHash)
readGenesis = readGenesisAny
validateGenesis :: Conway.ConwayGenesis c
-> ExceptT ConwayProtocolInstantiationError IO ()
: do the validation
data ConwayProtocolInstantiationError
TODO
= InvalidCostModelError ! FilePath
| CostModelExtractionError ! FilePath
| ConwayCostModelFileError ! ( FileError ( ) )
| ConwayCostModelDecodeError ! FilePath ! String
= InvalidCostModelError !FilePath
| CostModelExtractionError !FilePath
| ConwayCostModelFileError !(FileError ())
| ConwayCostModelDecodeError !FilePath !String
-}
deriving Show
TODO
instance Error ConwayProtocolInstantiationError where
displayError ( InvalidCostModelError fp ) =
" Invalid cost model : " < > show fp
displayError ( CostModelExtractionError fp ) =
" Error extracting the cost model at : " < > show fp
displayError ( ConwayCostModelFileError err ) =
displayError err
displayError ( ConwayCostModelDecodeError fp err ) =
" Error decoding cost model at : " < > show fp < > " Error : " < > err
instance Error ConwayProtocolInstantiationError where
displayError (InvalidCostModelError fp) =
"Invalid cost model: " <> show fp
displayError (CostModelExtractionError fp) =
"Error extracting the cost model at: " <> show fp
displayError (ConwayCostModelFileError err) =
displayError err
displayError (ConwayCostModelDecodeError fp err) =
"Error decoding cost model at: " <> show fp <> " Error: " <> err
-}
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/162c2b426ca66047f92a7d073036c13a434bf026/ouroboros-consensus-cardano-tools/src/Cardano/Node/Protocol/Conway.hs | haskell | # LANGUAGE EmptyDataDeriving #
TODO DUPLICATE? -- as-if adapted? from: cardano-node/src/Cardano/Node/Protocol/Conway.hs
* Reusable parts
|
module Cardano.Node.Protocol.Conway (
ConwayProtocolInstantiationError
, readGenesis
, validateGenesis
) where
import Cardano.Prelude
import qualified Cardano.Ledger.Conway.Genesis as Conway
import qualified Cardano.Ledger.Crypto as Crypto
import Cardano.Node.Protocol.Shelley (GenesisReadError,
readGenesisAny)
import Cardano.Node.Types
Conway genesis
readGenesis :: Crypto.Crypto c
=> GenesisFile
-> Maybe GenesisHash
-> ExceptT GenesisReadError IO
(Conway.ConwayGenesis c, GenesisHash)
readGenesis = readGenesisAny
validateGenesis :: Conway.ConwayGenesis c
-> ExceptT ConwayProtocolInstantiationError IO ()
: do the validation
data ConwayProtocolInstantiationError
TODO
= InvalidCostModelError ! FilePath
| CostModelExtractionError ! FilePath
| ConwayCostModelFileError ! ( FileError ( ) )
| ConwayCostModelDecodeError ! FilePath ! String
= InvalidCostModelError !FilePath
| CostModelExtractionError !FilePath
| ConwayCostModelFileError !(FileError ())
| ConwayCostModelDecodeError !FilePath !String
-}
deriving Show
TODO
instance Error ConwayProtocolInstantiationError where
displayError ( InvalidCostModelError fp ) =
" Invalid cost model : " < > show fp
displayError ( CostModelExtractionError fp ) =
" Error extracting the cost model at : " < > show fp
displayError ( ConwayCostModelFileError err ) =
displayError err
displayError ( ConwayCostModelDecodeError fp err ) =
" Error decoding cost model at : " < > show fp < > " Error : " < > err
instance Error ConwayProtocolInstantiationError where
displayError (InvalidCostModelError fp) =
"Invalid cost model: " <> show fp
displayError (CostModelExtractionError fp) =
"Error extracting the cost model at: " <> show fp
displayError (ConwayCostModelFileError err) =
displayError err
displayError (ConwayCostModelDecodeError fp err) =
"Error decoding cost model at: " <> show fp <> " Error: " <> err
-}
|
476a9bfacbf4a229d2f0f8f9c05ba550d82fed9263e1ad70c8bb2ceea23de0a7 | silkapp/rest | Post.hs | # LANGUAGE
DeriveDataTypeable
, NoImplicitPrelude
#
DeriveDataTypeable
, NoImplicitPrelude
#-}
module Api.Post
( Identifier (..)
, WithPost
, resource
, postFromIdentifier
) where
import Prelude.Compat
import Control.Concurrent.STM (STM, TVar, atomically, modifyTVar, readTVar)
import Control.Monad (unless)
import Control.Monad.Error.Class
import Control.Monad.Reader (ReaderT, asks)
import Control.Monad.Trans (lift, liftIO)
import Control.Monad.Trans.Except (ExceptT)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Set (Set)
import Data.Time
import Data.Typeable
import Safe
import qualified Data.Foldable as F
import qualified Data.Set as Set
import qualified Data.Text as T
import Rest
import Rest.Info
import Rest.ShowUrl
import qualified Rest.Resource as R
import ApiTypes
import Type.CreatePost (CreatePost)
import Type.Post (Post (Post))
import Type.PostError (PostError (..))
import Type.User (User)
import Type.UserPost (UserPost (UserPost))
import qualified Type.CreatePost as CreatePost
import qualified Type.Post as Post
import qualified Type.User as User
data Identifier
= Latest
| ById Int
deriving (Eq, Show, Read, Typeable)
instance Info Identifier where
describe _ = "identifier"
instance ShowUrl Identifier where
showUrl Latest = "latest"
showUrl (ById i) = show i
| Post extends the root of the API with a reader containing the ways to identify a Post in our URLs .
-- Currently only by the title of the post.
type WithPost = ReaderT Identifier BlogApi
-- | Defines the /post api end-point.
resource :: Resource BlogApi WithPost Identifier () Void
resource = mkResourceReader
{ R.name = "post" -- Name of the HTTP path segment.
, R.schema = withListing () $ named [("id", singleRead ById), ("latest", single Latest)]
list is requested by GET /post which gives a listing of posts .
PUT /post to create a new Post .
, R.get = Just get
, R.remove = Just remove
}
postFromIdentifier :: Identifier -> TVar (Set Post) -> STM (Maybe Post)
postFromIdentifier i pv = finder <$> readTVar pv
where
finder = case i of
ById ident -> F.find ((== ident) . Post.id) . Set.toList
Latest -> headMay . sortBy (flip $ comparing Post.createdTime) . Set.toList
get :: Handler WithPost
get = mkIdHandler xmlJsonO handler
where
handler :: () -> Identifier -> ExceptT Reason_ WithPost Post
handler _ i = do
mpost <- liftIO . atomically . postFromIdentifier i =<< (lift . lift) (asks posts)
case mpost of
Nothing -> throwError NotFound
Just a -> return a
| List Posts with the most recent posts first .
list :: ListHandler BlogApi
list = mkListing xmlJsonO handler
where
handler :: Range -> ExceptT Reason_ BlogApi [Post]
handler r = do
psts <- liftIO . atomically . readTVar =<< asks posts
return . take (count r) . drop (offset r) . sortBy (flip $ comparing Post.createdTime) . Set.toList $ psts
create :: Handler BlogApi
create = mkInputHandler (xmlJsonE . xmlJson) handler
where
handler :: UserPost -> ExceptT (Reason PostError) BlogApi Post
handler (UserPost usr pst) = do
-- Make sure the credentials are valid
checkLogin usr
pstsVar <- asks posts
psts <- liftIO . atomically . readTVar $ pstsVar
post <- liftIO $ toPost (Set.size psts + 1) usr pst
Validate and save the post in the same transaction .
merr <- liftIO . atomically $ do
let vt = validTitle pst psts
if not vt
then return . Just $ domainReason InvalidTitle
else if not (validContent pst)
then return . Just $ domainReason InvalidContent
else modifyTVar pstsVar (Set.insert post) >> return Nothing
maybe (return post) throwError merr
remove :: Handler WithPost
remove = mkIdHandler id handler
where
handler :: () -> Identifier -> ExceptT Reason_ WithPost ()
handler _ i = do
pstsVar <- lift . lift $ asks posts
merr <- liftIO . atomically $ do
mpost <- postFromIdentifier i pstsVar
case mpost of
Nothing -> return . Just $ NotFound
Just post -> modifyTVar pstsVar (Set.delete post) >> return Nothing
maybe (return ()) throwError merr
| Convert a User and CreatePost into a Post that can be saved .
toPost :: Int -> User -> CreatePost -> IO Post
toPost i u p = do
t <- getCurrentTime
return Post
{ Post.id = i
, Post.author = User.name u
, Post.createdTime = t
, Post.title = CreatePost.title p
, Post.content = CreatePost.content p
}
| A Post 's title must be unique and non - empty .
validTitle :: CreatePost -> Set Post -> Bool
validTitle p psts =
let pt = CreatePost.title p
nonEmpty = (>= 1) . T.length $ pt
available = F.all ((pt /=) . Post.title) psts
in available && nonEmpty
| A Post 's content must be non - empty .
validContent :: CreatePost -> Bool
validContent = (>= 1) . T.length . CreatePost.content
-- | Throw an error if the user isn't logged in.
checkLogin :: User -> ExceptT (Reason e) BlogApi ()
checkLogin usr = do
usrs <- liftIO . atomically . readTVar =<< asks users
unless (usr `F.elem` usrs) $ throwError NotAllowed
| null | https://raw.githubusercontent.com/silkapp/rest/f0462fc36709407f236f57064d8e37c77bdf8a79/rest-example/example-api/Api/Post.hs | haskell | Currently only by the title of the post.
| Defines the /post api end-point.
Name of the HTTP path segment.
Make sure the credentials are valid
| Throw an error if the user isn't logged in. | # LANGUAGE
DeriveDataTypeable
, NoImplicitPrelude
#
DeriveDataTypeable
, NoImplicitPrelude
#-}
module Api.Post
( Identifier (..)
, WithPost
, resource
, postFromIdentifier
) where
import Prelude.Compat
import Control.Concurrent.STM (STM, TVar, atomically, modifyTVar, readTVar)
import Control.Monad (unless)
import Control.Monad.Error.Class
import Control.Monad.Reader (ReaderT, asks)
import Control.Monad.Trans (lift, liftIO)
import Control.Monad.Trans.Except (ExceptT)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Set (Set)
import Data.Time
import Data.Typeable
import Safe
import qualified Data.Foldable as F
import qualified Data.Set as Set
import qualified Data.Text as T
import Rest
import Rest.Info
import Rest.ShowUrl
import qualified Rest.Resource as R
import ApiTypes
import Type.CreatePost (CreatePost)
import Type.Post (Post (Post))
import Type.PostError (PostError (..))
import Type.User (User)
import Type.UserPost (UserPost (UserPost))
import qualified Type.CreatePost as CreatePost
import qualified Type.Post as Post
import qualified Type.User as User
data Identifier
= Latest
| ById Int
deriving (Eq, Show, Read, Typeable)
instance Info Identifier where
describe _ = "identifier"
instance ShowUrl Identifier where
showUrl Latest = "latest"
showUrl (ById i) = show i
| Post extends the root of the API with a reader containing the ways to identify a Post in our URLs .
type WithPost = ReaderT Identifier BlogApi
resource :: Resource BlogApi WithPost Identifier () Void
resource = mkResourceReader
, R.schema = withListing () $ named [("id", singleRead ById), ("latest", single Latest)]
list is requested by GET /post which gives a listing of posts .
PUT /post to create a new Post .
, R.get = Just get
, R.remove = Just remove
}
postFromIdentifier :: Identifier -> TVar (Set Post) -> STM (Maybe Post)
postFromIdentifier i pv = finder <$> readTVar pv
where
finder = case i of
ById ident -> F.find ((== ident) . Post.id) . Set.toList
Latest -> headMay . sortBy (flip $ comparing Post.createdTime) . Set.toList
get :: Handler WithPost
get = mkIdHandler xmlJsonO handler
where
handler :: () -> Identifier -> ExceptT Reason_ WithPost Post
handler _ i = do
mpost <- liftIO . atomically . postFromIdentifier i =<< (lift . lift) (asks posts)
case mpost of
Nothing -> throwError NotFound
Just a -> return a
| List Posts with the most recent posts first .
list :: ListHandler BlogApi
list = mkListing xmlJsonO handler
where
handler :: Range -> ExceptT Reason_ BlogApi [Post]
handler r = do
psts <- liftIO . atomically . readTVar =<< asks posts
return . take (count r) . drop (offset r) . sortBy (flip $ comparing Post.createdTime) . Set.toList $ psts
create :: Handler BlogApi
create = mkInputHandler (xmlJsonE . xmlJson) handler
where
handler :: UserPost -> ExceptT (Reason PostError) BlogApi Post
handler (UserPost usr pst) = do
checkLogin usr
pstsVar <- asks posts
psts <- liftIO . atomically . readTVar $ pstsVar
post <- liftIO $ toPost (Set.size psts + 1) usr pst
Validate and save the post in the same transaction .
merr <- liftIO . atomically $ do
let vt = validTitle pst psts
if not vt
then return . Just $ domainReason InvalidTitle
else if not (validContent pst)
then return . Just $ domainReason InvalidContent
else modifyTVar pstsVar (Set.insert post) >> return Nothing
maybe (return post) throwError merr
remove :: Handler WithPost
remove = mkIdHandler id handler
where
handler :: () -> Identifier -> ExceptT Reason_ WithPost ()
handler _ i = do
pstsVar <- lift . lift $ asks posts
merr <- liftIO . atomically $ do
mpost <- postFromIdentifier i pstsVar
case mpost of
Nothing -> return . Just $ NotFound
Just post -> modifyTVar pstsVar (Set.delete post) >> return Nothing
maybe (return ()) throwError merr
| Convert a User and CreatePost into a Post that can be saved .
toPost :: Int -> User -> CreatePost -> IO Post
toPost i u p = do
t <- getCurrentTime
return Post
{ Post.id = i
, Post.author = User.name u
, Post.createdTime = t
, Post.title = CreatePost.title p
, Post.content = CreatePost.content p
}
| A Post 's title must be unique and non - empty .
validTitle :: CreatePost -> Set Post -> Bool
validTitle p psts =
let pt = CreatePost.title p
nonEmpty = (>= 1) . T.length $ pt
available = F.all ((pt /=) . Post.title) psts
in available && nonEmpty
| A Post 's content must be non - empty .
validContent :: CreatePost -> Bool
validContent = (>= 1) . T.length . CreatePost.content
checkLogin :: User -> ExceptT (Reason e) BlogApi ()
checkLogin usr = do
usrs <- liftIO . atomically . readTVar =<< asks users
unless (usr `F.elem` usrs) $ throwError NotAllowed
|
211b978a419b954572ad6c5febcbf80cb3369042f15f9efebd053099a3ca495d | BitGameEN/bitgamex | erlcloud_sns_tests.erl | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
-module(erlcloud_sns_tests).
-include_lib("eunit/include/eunit.hrl").
% -include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
Unit tests for sns .
These tests work by using meck to mock httpc . There are two classes of test : input and output .
%%
%% Input tests verify that different function args produce the desired JSON request.
%% An input test list provides a list of funs and the JSON that is expected to result.
%%
%% Output tests verify that the http response produces the correct return from the fun.
%% An output test lists provides a list of response bodies and the expected return.
%% The _ddb_test macro provides line number annotation to a test, similar to _test, but doesn't wrap in a fun
-define(_sns_test(T), {?LINE, T}).
%% The _f macro is a terse way to wrap code in a fun. Similar to _test but doesn't annotate with a line number
-define(_f(F), fun() -> F end).
%%%===================================================================
%%% Test entry points
%%%===================================================================
sns_api_test_() ->
{foreach,
fun start/0,
fun stop/1,
[fun defaults_to_http/1,
fun supports_explicit_http/1,
fun supports_https/1,
fun is_case_insensitive/1,
fun doesnt_support_gopher/1,
fun doesnt_accept_non_strings/1,
fun create_topic_input_tests/1,
fun create_topic_output_tests/1,
fun delete_topic_input_tests/1,
fun subscribe_input_tests/1,
fun subscribe_output_tests/1,
fun set_topic_attributes_input_tests/1,
fun set_topic_attributes_output_tests/1,
fun list_topics_input_tests/1,
fun list_topics_output_tests/1,
fun list_subscriptions_by_topic_input_tests/1,
fun list_subscriptions_by_topic_output_tests/1
]}.
start() ->
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)),
meck:new(erlcloud_httpc),
meck:expect(erlcloud_httpc, request,
fun(_,_,_,_,_,_) -> mock_httpc_response() end),
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)).
stop(_) ->
meck:unload(erlcloud_httpc).
%%%===================================================================
%%% Input test helpers
%%%===================================================================
%% common_params returns the list of parameters that are not validated by these tests.
%% They should be checked by lower level unit tests.
-spec common_params() -> [string()].
common_params() ->
["AWSAccessKeyId",
"SignatureMethod",
"SignatureVersion",
"Timestamp",
"Version",
"Signature"].
%% validate_param checks that the query parameter is either a common param or expected
%% by the test case. If expected, returns expected with the param deleted to be used in
%% subsequent calls.
-type expected_param() :: {string(), string()}.
-spec validate_param(string(), [expected_param()]) -> [expected_param()].
validate_param(Param, Expected) ->
[Key, Value] = case string:tokens(Param, "=") of
[K, V] ->
[K, V];
[K] ->
[K, ""]
end,
case lists:member(Key, common_params()) of
true ->
Expected;
false ->
Expected1 = lists:delete({Key, Value}, Expected),
case length(Expected) - 1 =:= length(Expected1) of
true -> ok;
false ->
?debugFmt("Parameter not expected: ~p", [{Key, Value}])
end,
?assertEqual(length(Expected) - 1, length(Expected1)),
Expected1
end.
%% verifies that the parameters in the body match the expected parameters
-spec validate_params(binary(), [expected_param()]) -> ok.
validate_params(Body, Expected) ->
ParamList = string:tokens(binary_to_list(Body), "&"),
Remain = lists:foldl(fun validate_param/2, Expected, ParamList),
io:format("Remain: ~p", [Remain]),
?assertEqual([], Remain).
returns the mock of the httpc function input tests expect to be called .
%% Validates the query body and responds with the provided response.
-spec input_expect(string(), [expected_param()]) -> fun().
input_expect(Response, Expected) ->
fun(_Url, post, _Headers, Body, _Timeout, _Config) ->
validate_params(Body, Expected),
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
%% input_test converts an input_test specifier into an eunit test generator
-type input_test_spec() :: {pos_integer(), {fun(), [expected_param()]} | {string(), fun(), [expected_param()]}}.
-spec input_test(string(), input_test_spec()) -> tuple().
input_test(Response, {Line, {Description, Fun, Params}}) when
is_list(Description) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, input_expect(Response, Params)),
%% Configure to make sure there is a key. Would like to do this in start, but
%% that isn't called in the same process
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Fun()
end}}.
%% input_test(Response, {Line, {Fun, Params}}) ->
input_test(Response , { Line , { " " , Fun , Params } } ) .
%% input_tests converts a list of input_test specifiers into an eunit test generator
-spec input_tests(string(), [input_test_spec()]) -> [tuple()].
input_tests(Response, Tests) ->
[input_test(Response, Test) || Test <- Tests].
%%%===================================================================
%%% Output test helpers
%%%===================================================================
returns the mock of the httpc function output tests expect to be called .
-spec output_expect(string()) -> fun().
output_expect(Response) ->
fun(_Url, post, _Headers, _Body, _Timeout, _Config) ->
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
%% output_test converts an output_test specifier into an eunit test generator
-type output_test_spec() :: {pos_integer(), {string(), term()} | {string(), string(), term()}}.
-spec output_test(fun(), output_test_spec()) -> tuple().
output_test(Fun, {Line, {Description, Response, Result}}) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, output_expect(Response)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Actual = Fun(),
?assertEqual(Result, Actual)
end}}.
%% output_tests converts a list of output_test specifiers into an eunit test generator
-spec output_tests(fun(), [output_test_spec()]) -> [term()].
output_tests(Fun, Tests) ->
[output_test(Fun, Test) || Test <- Tests].
CreateTopic test based on the API examples :
%%
create_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test creates a topic in a region.",
?_f(erlcloud_sns:create_topic("test_topic")),
[
{"Name", "test_topic"},
{"Action", "CreateTopic"}
]})
],
Response = "
<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:test_topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
input_tests(Response, Tests).
create_topic_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
"arn:aws:sns:us-east-1:123456789012:My-Topic"})
],
output_tests(?_f(erlcloud_sns:create_topic("My-Topic")), Tests).
DeleteTopic test based on the API examples :
%%
delete_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test deletes a topic in a region.",
?_f(erlcloud_sns:delete_topic("My-Topic")),
[
{"TopicArn", "My-Topic"},
{"Action", "DeleteTopic"}
]})
],
Response = "
<DeleteTopicResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>f3aa9ac9-3c3d-11df-8235-9dab105e9c32</RequestId>
</ResponseMetadata>
</DeleteTopicResponse>",
input_tests(Response, Tests).
%% Subscribe test based on the API examples:
%%
subscribe_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to prepares to subscribe an endpoint.",
?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "Subscribe"},
{"Endpoint", "arn%3Aaws%3Asqs%3Aus-west-2%3A123456789012%3AMyQueue"},
{"Protocol", "sqs"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
input_tests(Response, Tests).
subscribe_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
"arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286"})
],
output_tests(?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
%% Set topic attributes test based on the API examples:
%%
set_topic_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets topic's attribute.",
?_f(erlcloud_sns:set_topic_attributes("DisplayName", "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "SetTopicAttributes"},
{"AttributeName", "DisplayName"},
{"AttributeValue", "MyTopicName"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse> ",
input_tests(Response, Tests).
set_topic_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets topic's attribute.",
"<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_topic_attributes("DisplayName", "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
%% List topics test based on the API example:
%%
list_topics_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists topics.",
?_f(erlcloud_sns:list_topics()),
[
{"Action", "ListTopics"}
]}),
?_sns_test(
{"Test lists topics with token.",
?_f(erlcloud_sns:list_topics("token")),
[
{"Action", "ListTopics"},
{"NextToken", "token"}
]}),
?_sns_test(
{"Test lists topics all.",
?_f(erlcloud_sns:list_topics_all()),
[
{"Action", "ListTopics"}
]})
],
Response = "<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
input_tests(Response, Tests).
list_topics_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_topics()),
[?_sns_test(
{"Test lists topics.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists topics with token.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
<NextToken>token</NextToken>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_topics_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]})
]).
%% List Subscriptions By Topic test based on the API example:
%%
list_subscriptions_by_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]}),
?_sns_test(
{"Test lists Subscriptions toke.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn", "Token")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_by_topic_all("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]})
],
Response = "<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
input_tests(Response, Tests).
list_subscriptions_by_topic_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subsriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subsriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic_all("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
defaults_to_http(_) ->
Config = erlcloud_aws:default_config(),
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_explicit_http(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="http://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_https(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="https://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
is_case_insensitive(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="HTTPS://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
doesnt_support_gopher(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="gopher://"},
?_assertError({sns_error, {unsupported_scheme,"gopher://"}},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
doesnt_accept_non_strings(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme=https},
?_assertError({sns_error, badarg},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
% ==================
Internal functions
% ==================
get_values_from_history(Plist) ->
[Call1] = [ Params || {_, {erlcloud_httpc, request, Params}, _} <- Plist ],
list_to_tuple(Call1).
request_params() ->
get_values_from_history(meck:history(erlcloud_httpc)).
mock_httpc_response() ->
{ok, {{200, "ok"}, [], response_body()}}.
response_body() ->
<<"<PublishResponse xmlns='-03-31/'>
<PublishResult>
<MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>
</PublishResult>
<ResponseMetadata>
<RequestId>f187a3c1-376f-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</PublishResponse>">>.
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/erlcloud/test/erlcloud_sns_tests.erl | erlang | -include("erlcloud.hrl").
Input tests verify that different function args produce the desired JSON request.
An input test list provides a list of funs and the JSON that is expected to result.
Output tests verify that the http response produces the correct return from the fun.
An output test lists provides a list of response bodies and the expected return.
The _ddb_test macro provides line number annotation to a test, similar to _test, but doesn't wrap in a fun
The _f macro is a terse way to wrap code in a fun. Similar to _test but doesn't annotate with a line number
===================================================================
Test entry points
===================================================================
===================================================================
Input test helpers
===================================================================
common_params returns the list of parameters that are not validated by these tests.
They should be checked by lower level unit tests.
validate_param checks that the query parameter is either a common param or expected
by the test case. If expected, returns expected with the param deleted to be used in
subsequent calls.
verifies that the parameters in the body match the expected parameters
Validates the query body and responds with the provided response.
input_test converts an input_test specifier into an eunit test generator
Configure to make sure there is a key. Would like to do this in start, but
that isn't called in the same process
input_test(Response, {Line, {Fun, Params}}) ->
input_tests converts a list of input_test specifiers into an eunit test generator
===================================================================
Output test helpers
===================================================================
output_test converts an output_test specifier into an eunit test generator
output_tests converts a list of output_test specifiers into an eunit test generator
Subscribe test based on the API examples:
Set topic attributes test based on the API examples:
List topics test based on the API example:
List Subscriptions By Topic test based on the API example:
==================
================== | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
-module(erlcloud_sns_tests).
-include_lib("eunit/include/eunit.hrl").
-include("erlcloud_aws.hrl").
Unit tests for sns .
These tests work by using meck to mock httpc . There are two classes of test : input and output .
-define(_sns_test(T), {?LINE, T}).
-define(_f(F), fun() -> F end).
sns_api_test_() ->
{foreach,
fun start/0,
fun stop/1,
[fun defaults_to_http/1,
fun supports_explicit_http/1,
fun supports_https/1,
fun is_case_insensitive/1,
fun doesnt_support_gopher/1,
fun doesnt_accept_non_strings/1,
fun create_topic_input_tests/1,
fun create_topic_output_tests/1,
fun delete_topic_input_tests/1,
fun subscribe_input_tests/1,
fun subscribe_output_tests/1,
fun set_topic_attributes_input_tests/1,
fun set_topic_attributes_output_tests/1,
fun list_topics_input_tests/1,
fun list_topics_output_tests/1,
fun list_subscriptions_by_topic_input_tests/1,
fun list_subscriptions_by_topic_output_tests/1
]}.
start() ->
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)),
meck:new(erlcloud_httpc),
meck:expect(erlcloud_httpc, request,
fun(_,_,_,_,_,_) -> mock_httpc_response() end),
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)).
stop(_) ->
meck:unload(erlcloud_httpc).
-spec common_params() -> [string()].
common_params() ->
["AWSAccessKeyId",
"SignatureMethod",
"SignatureVersion",
"Timestamp",
"Version",
"Signature"].
-type expected_param() :: {string(), string()}.
-spec validate_param(string(), [expected_param()]) -> [expected_param()].
validate_param(Param, Expected) ->
[Key, Value] = case string:tokens(Param, "=") of
[K, V] ->
[K, V];
[K] ->
[K, ""]
end,
case lists:member(Key, common_params()) of
true ->
Expected;
false ->
Expected1 = lists:delete({Key, Value}, Expected),
case length(Expected) - 1 =:= length(Expected1) of
true -> ok;
false ->
?debugFmt("Parameter not expected: ~p", [{Key, Value}])
end,
?assertEqual(length(Expected) - 1, length(Expected1)),
Expected1
end.
-spec validate_params(binary(), [expected_param()]) -> ok.
validate_params(Body, Expected) ->
ParamList = string:tokens(binary_to_list(Body), "&"),
Remain = lists:foldl(fun validate_param/2, Expected, ParamList),
io:format("Remain: ~p", [Remain]),
?assertEqual([], Remain).
returns the mock of the httpc function input tests expect to be called .
-spec input_expect(string(), [expected_param()]) -> fun().
input_expect(Response, Expected) ->
fun(_Url, post, _Headers, Body, _Timeout, _Config) ->
validate_params(Body, Expected),
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
-type input_test_spec() :: {pos_integer(), {fun(), [expected_param()]} | {string(), fun(), [expected_param()]}}.
-spec input_test(string(), input_test_spec()) -> tuple().
input_test(Response, {Line, {Description, Fun, Params}}) when
is_list(Description) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, input_expect(Response, Params)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Fun()
end}}.
input_test(Response , { Line , { " " , Fun , Params } } ) .
-spec input_tests(string(), [input_test_spec()]) -> [tuple()].
input_tests(Response, Tests) ->
[input_test(Response, Test) || Test <- Tests].
returns the mock of the httpc function output tests expect to be called .
-spec output_expect(string()) -> fun().
output_expect(Response) ->
fun(_Url, post, _Headers, _Body, _Timeout, _Config) ->
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
-type output_test_spec() :: {pos_integer(), {string(), term()} | {string(), string(), term()}}.
-spec output_test(fun(), output_test_spec()) -> tuple().
output_test(Fun, {Line, {Description, Response, Result}}) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, output_expect(Response)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Actual = Fun(),
?assertEqual(Result, Actual)
end}}.
-spec output_tests(fun(), [output_test_spec()]) -> [term()].
output_tests(Fun, Tests) ->
[output_test(Fun, Test) || Test <- Tests].
CreateTopic test based on the API examples :
create_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test creates a topic in a region.",
?_f(erlcloud_sns:create_topic("test_topic")),
[
{"Name", "test_topic"},
{"Action", "CreateTopic"}
]})
],
Response = "
<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:test_topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
input_tests(Response, Tests).
create_topic_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
"arn:aws:sns:us-east-1:123456789012:My-Topic"})
],
output_tests(?_f(erlcloud_sns:create_topic("My-Topic")), Tests).
DeleteTopic test based on the API examples :
delete_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test deletes a topic in a region.",
?_f(erlcloud_sns:delete_topic("My-Topic")),
[
{"TopicArn", "My-Topic"},
{"Action", "DeleteTopic"}
]})
],
Response = "
<DeleteTopicResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>f3aa9ac9-3c3d-11df-8235-9dab105e9c32</RequestId>
</ResponseMetadata>
</DeleteTopicResponse>",
input_tests(Response, Tests).
subscribe_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to prepares to subscribe an endpoint.",
?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "Subscribe"},
{"Endpoint", "arn%3Aaws%3Asqs%3Aus-west-2%3A123456789012%3AMyQueue"},
{"Protocol", "sqs"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
input_tests(Response, Tests).
subscribe_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
"arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286"})
],
output_tests(?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
set_topic_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets topic's attribute.",
?_f(erlcloud_sns:set_topic_attributes("DisplayName", "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "SetTopicAttributes"},
{"AttributeName", "DisplayName"},
{"AttributeValue", "MyTopicName"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse> ",
input_tests(Response, Tests).
set_topic_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets topic's attribute.",
"<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_topic_attributes("DisplayName", "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
list_topics_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists topics.",
?_f(erlcloud_sns:list_topics()),
[
{"Action", "ListTopics"}
]}),
?_sns_test(
{"Test lists topics with token.",
?_f(erlcloud_sns:list_topics("token")),
[
{"Action", "ListTopics"},
{"NextToken", "token"}
]}),
?_sns_test(
{"Test lists topics all.",
?_f(erlcloud_sns:list_topics_all()),
[
{"Action", "ListTopics"}
]})
],
Response = "<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
input_tests(Response, Tests).
list_topics_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_topics()),
[?_sns_test(
{"Test lists topics.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists topics with token.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
<NextToken>token</NextToken>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_topics_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]})
]).
list_subscriptions_by_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]}),
?_sns_test(
{"Test lists Subscriptions toke.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn", "Token")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_by_topic_all("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]})
],
Response = "<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
input_tests(Response, Tests).
list_subscriptions_by_topic_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subsriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subsriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic_all("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
defaults_to_http(_) ->
Config = erlcloud_aws:default_config(),
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_explicit_http(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="http://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_https(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="https://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
is_case_insensitive(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="HTTPS://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
doesnt_support_gopher(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="gopher://"},
?_assertError({sns_error, {unsupported_scheme,"gopher://"}},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
doesnt_accept_non_strings(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme=https},
?_assertError({sns_error, badarg},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
Internal functions
get_values_from_history(Plist) ->
[Call1] = [ Params || {_, {erlcloud_httpc, request, Params}, _} <- Plist ],
list_to_tuple(Call1).
request_params() ->
get_values_from_history(meck:history(erlcloud_httpc)).
mock_httpc_response() ->
{ok, {{200, "ok"}, [], response_body()}}.
response_body() ->
<<"<PublishResponse xmlns='-03-31/'>
<PublishResult>
<MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>
</PublishResult>
<ResponseMetadata>
<RequestId>f187a3c1-376f-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</PublishResponse>">>.
|
78684f33c1e4f9fef92654d42f805e666de3bd57b48cda2f96d34686dac0291e | ocaml-flambda/flambda-backend | fexpr.ml | type location = Lambda.scoped_location
type 'a located =
{ txt : 'a;
loc : location
}
type variable = string located
type continuation_id = string located
type code_id = string located
type function_slot = string located
type value_slot = string located
type compilation_unit =
{ ident : string;
linkage_name : string option (* defaults to same as ident *)
}
type symbol = (compilation_unit option * string) located
type immediate = string
type targetint = int64
type special_continuation =
| Done
(* top-level normal continuation *)
| Error
(* top-level exception continuation *)
type continuation =
| Named of continuation_id
| Special of special_continuation
type result_continuation =
| Return of continuation
| Never_returns
type continuation_sort =
| Normal
| Exn
| Define_root_symbol
(* There's also [Return] and [Toplevel_return], but those don't need to be
* specified explicitly *)
type region =
| Named of variable
| Toplevel
type const =
| Naked_immediate of immediate
| Tagged_immediate of immediate
| Naked_float of float
| Naked_int32 of int32
| Naked_int64 of int64
| Naked_nativeint of targetint
type field_of_block =
| Symbol of symbol
| Tagged_immediate of immediate
| Dynamically_computed of variable
type is_recursive =
| Nonrecursive
| Recursive
type tag_scannable = int
type mutability = Mutability.t =
| Mutable
| Immutable
| Immutable_unique
type 'a or_variable =
| Const of 'a
| Var of variable
type static_data =
| Block of
{ tag : tag_scannable;
mutability : mutability;
elements : field_of_block list
}
| Boxed_float of float or_variable
| Boxed_int32 of int32 or_variable
| Boxed_int64 of int64 or_variable
| Boxed_nativeint of targetint or_variable
| Immutable_float_block of float or_variable list
| Immutable_float_array of float or_variable list
| Immutable_value_array of field_of_block list
| Empty_array
| Mutable_string of { initial_value : string }
| Immutable_string of string
type kind = Flambda_kind.t
type subkind =
| Anything
| Boxed_float
| Boxed_int32
| Boxed_int64
| Boxed_nativeint
| Tagged_immediate
| Variant of
{ consts : targetint list;
non_consts : (tag_scannable * subkind list) list
}
| Float_block of { num_fields : int }
| Float_array
| Immediate_array
| Value_array
| Generic_array
type kind_with_subkind =
| Value of subkind
| Naked_number of Flambda_kind.Naked_number_kind.t
| Region
| Rec_info
type static_data_binding =
{ symbol : symbol;
defining_expr : static_data
}
type raise_kind = Trap_action.Raise_kind.t =
| Regular
| Reraise
| No_trace
type trap_action =
| Push of { exn_handler : continuation }
| Pop of
{ exn_handler : continuation;
raise_kind : raise_kind option
}
type rec_info =
| Depth of int
| Infinity
| Do_not_inline
| Var of variable
| Succ of rec_info
| Unroll of int * rec_info
type coercion =
| Id
| Change_depth of
{ from : rec_info;
to_ : rec_info
}
type kinded_parameter =
{ param : variable;
kind : kind_with_subkind option
}
type name =
| Var of variable
| Symbol of symbol
type simple =
| Var of variable
| Symbol of symbol
| Const of const
| Coerce of simple * coercion
type array_kind = Flambda_primitive.Array_kind.t =
| Immediates
| Values
| Naked_floats
type box_kind = Flambda_kind.Boxable_number.t =
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
type generic_array_specialisation =
| No_specialisation
| Full_of_naked_floats
| Full_of_immediates
| Full_of_arbitrary_values_but_not_floats
type block_access_field_kind = Flambda_primitive.Block_access_field_kind.t =
| Any_value
| Immediate
type block_access_kind =
| Values of
{ tag : tag_scannable option;
size : targetint option;
field_kind : block_access_field_kind
}
| Naked_floats of { size : targetint option }
type standard_int = Flambda_kind.Standard_int.t =
| Tagged_immediate
| Naked_immediate
| Naked_int32
| Naked_int64
| Naked_nativeint
type standard_int_or_float = Flambda_kind.Standard_int_or_float.t =
| Tagged_immediate
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
type string_or_bytes = Flambda_primitive.string_or_bytes =
| String
| Bytes
type alloc_mode_for_allocations =
| Heap
| Local of { region : region }
type init_or_assign =
| Initialization
| Assignment of alloc_mode_for_allocations
type 'signed_or_unsigned comparison =
'signed_or_unsigned Flambda_primitive.comparison =
| Eq
| Neq
| Lt of 'signed_or_unsigned
| Gt of 'signed_or_unsigned
| Le of 'signed_or_unsigned
| Ge of 'signed_or_unsigned
type equality_comparison = Flambda_primitive.equality_comparison =
| Eq
| Neq
type signed_or_unsigned = Flambda_primitive.signed_or_unsigned =
| Signed
| Unsigned
type nullop = Begin_region
type unop =
| Array_length
| Box_number of box_kind
| End_region
| Get_tag
| Is_flat_float_array
| Is_int
| Num_conv of
{ src : standard_int_or_float;
dst : standard_int_or_float
}
| Opaque_identity
| Project_value_slot of
{ project_from : function_slot;
value_slot : value_slot
}
| Project_function_slot of
{ move_from : function_slot;
move_to : function_slot
}
| String_length of string_or_bytes
| Unbox_number of box_kind
| Untag_immediate
| Tag_immediate
type 'signed_or_unsigned comparison_behaviour =
'signed_or_unsigned Flambda_primitive.comparison_behaviour =
| Yielding_bool of 'signed_or_unsigned comparison
| Yielding_int_like_compare_functions of 'signed_or_unsigned
type binary_int_arith_op = Flambda_primitive.binary_int_arith_op =
| Add
| Sub
| Mul
| Div
| Mod
| And
| Or
| Xor
type int_shift_op = Flambda_primitive.int_shift_op =
| Lsl
| Lsr
| Asr
type binary_float_arith_op = Flambda_primitive.binary_float_arith_op =
| Add
| Sub
| Mul
| Div
type infix_binop =
| Int_arith of binary_int_arith_op (* on tagged immediates *)
| Int_shift of int_shift_op (* on tagged immediates *)
on tagged imms
| Float_arith of binary_float_arith_op
| Float_comp of unit comparison_behaviour
type binop =
| Array_load of array_kind * mutability
| Block_load of block_access_kind * mutability
| Phys_equal of equality_comparison
| Int_arith of standard_int * binary_int_arith_op
| Int_comp of standard_int * signed_or_unsigned comparison_behaviour
| Int_shift of standard_int * int_shift_op
| Infix of infix_binop
type ternop = Array_set of array_kind * init_or_assign
type varop = Make_block of tag_scannable * mutability
type prim =
| Nullary of nullop
| Unary of unop * simple
| Binary of binop * simple * simple
| Ternary of ternop * simple * simple * simple
| Variadic of varop * simple list
type arity = kind_with_subkind list
type function_call =
| Direct of
{ code_id : code_id;
function_slot : function_slot option
}
| Indirect
(* Will translate to indirect_known_arity or indirect_unknown_arity depending on
whether the apply record's arities field has a value *)
type method_kind =
| Self
| Public
| Cached
type call_kind =
| Function of function_call
| Method of { kind : ; obj : simple ; }
| C_call of { alloc : bool }
type function_arities =
{ params_arity : arity option;
ret_arity : arity
}
type inline_attribute = Inline_attribute.t =
| Always_inline
| Available_inline
| Never_inline
| Unroll of int
| Default_inline
type inlined_attribute = Inlined_attribute.t =
| Always_inlined
| Hint_inlined
| Never_inlined
| Unroll of int
| Default_inlined
type inlining_state = { depth : int (* CR lmaurer: Add inlining arguments *) }
type apply =
{ func : name;
continuation : result_continuation;
exn_continuation : continuation;
args : simple list;
call_kind : call_kind;
arities : function_arities option;
inlined : inlined_attribute option;
inlining_state : inlining_state option;
region : region
}
type size = int
type apply_cont =
{ cont : continuation;
trap_action : trap_action option;
args : simple list
}
type expr =
| Let of let_
| Let_cont of let_cont
| Let_symbol of let_symbol
| Apply of apply
| Apply_cont of apply_cont
| Switch of
{ scrutinee : simple;
cases : (int * apply_cont) list
}
| Invalid of { message : string }
and value_slots = one_value_slot list
and one_value_slot =
{ var : value_slot;
value : simple
}
and let_ =
{ bindings : let_binding list;
value_slots : value_slots option;
body : expr
}
and let_binding =
{ var : variable;
defining_expr : named
}
and named =
| Simple of simple
| Prim of prim
| Closure of fun_decl
| Rec_info of rec_info
and fun_decl =
{ code_id : code_id;
function_slot : function_slot option (* defaults to same name as code id *)
}
and let_cont =
{ recursive : is_recursive;
body : expr;
bindings : continuation_binding list
}
and continuation_binding =
{ name : continuation_id;
params : kinded_parameter list;
sort : continuation_sort option;
handler : expr
}
and let_symbol =
{ bindings : symbol_binding list;
(* Only used if there's no [Set_of_closures] in the list *)
value_slots : value_slots option;
body : expr
}
and symbol_binding =
| Data of static_data_binding
| Code of code
| Deleted_code of code_id
| Closure of static_closure_binding
| Set_of_closures of static_set_of_closures
and static_set_of_closures =
{ bindings : static_closure_binding list;
elements : value_slots option
}
and code =
{ id : code_id;
newer_version_of : code_id option;
param_arity : arity option;
ret_arity : arity option;
recursive : is_recursive;
inline : inline_attribute option;
params_and_body : params_and_body;
code_size : code_size;
is_tupled : bool
}
and code_size = int
and params_and_body =
{ params : kinded_parameter list;
closure_var : variable;
region_var : variable;
depth_var : variable;
ret_cont : continuation_id;
exn_cont : continuation_id;
body : expr
}
and static_closure_binding =
{ symbol : symbol;
fun_decl : fun_decl
}
type flambda_unit = { body : expr }
type expect_test_spec =
{ before : flambda_unit;
after : flambda_unit
}
type markdown_node =
| Text of string
| Expect of expect_test_spec
type markdown_doc = markdown_node list
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/e2711acd740fb85b2672c8c72e07d3558edd1b57/middle_end/flambda2/parser/fexpr.ml | ocaml | defaults to same as ident
top-level normal continuation
top-level exception continuation
There's also [Return] and [Toplevel_return], but those don't need to be
* specified explicitly
on tagged immediates
on tagged immediates
Will translate to indirect_known_arity or indirect_unknown_arity depending on
whether the apply record's arities field has a value
CR lmaurer: Add inlining arguments
defaults to same name as code id
Only used if there's no [Set_of_closures] in the list | type location = Lambda.scoped_location
type 'a located =
{ txt : 'a;
loc : location
}
type variable = string located
type continuation_id = string located
type code_id = string located
type function_slot = string located
type value_slot = string located
type compilation_unit =
{ ident : string;
}
type symbol = (compilation_unit option * string) located
type immediate = string
type targetint = int64
type special_continuation =
| Done
| Error
type continuation =
| Named of continuation_id
| Special of special_continuation
type result_continuation =
| Return of continuation
| Never_returns
type continuation_sort =
| Normal
| Exn
| Define_root_symbol
type region =
| Named of variable
| Toplevel
type const =
| Naked_immediate of immediate
| Tagged_immediate of immediate
| Naked_float of float
| Naked_int32 of int32
| Naked_int64 of int64
| Naked_nativeint of targetint
type field_of_block =
| Symbol of symbol
| Tagged_immediate of immediate
| Dynamically_computed of variable
type is_recursive =
| Nonrecursive
| Recursive
type tag_scannable = int
type mutability = Mutability.t =
| Mutable
| Immutable
| Immutable_unique
type 'a or_variable =
| Const of 'a
| Var of variable
type static_data =
| Block of
{ tag : tag_scannable;
mutability : mutability;
elements : field_of_block list
}
| Boxed_float of float or_variable
| Boxed_int32 of int32 or_variable
| Boxed_int64 of int64 or_variable
| Boxed_nativeint of targetint or_variable
| Immutable_float_block of float or_variable list
| Immutable_float_array of float or_variable list
| Immutable_value_array of field_of_block list
| Empty_array
| Mutable_string of { initial_value : string }
| Immutable_string of string
type kind = Flambda_kind.t
type subkind =
| Anything
| Boxed_float
| Boxed_int32
| Boxed_int64
| Boxed_nativeint
| Tagged_immediate
| Variant of
{ consts : targetint list;
non_consts : (tag_scannable * subkind list) list
}
| Float_block of { num_fields : int }
| Float_array
| Immediate_array
| Value_array
| Generic_array
type kind_with_subkind =
| Value of subkind
| Naked_number of Flambda_kind.Naked_number_kind.t
| Region
| Rec_info
type static_data_binding =
{ symbol : symbol;
defining_expr : static_data
}
type raise_kind = Trap_action.Raise_kind.t =
| Regular
| Reraise
| No_trace
type trap_action =
| Push of { exn_handler : continuation }
| Pop of
{ exn_handler : continuation;
raise_kind : raise_kind option
}
type rec_info =
| Depth of int
| Infinity
| Do_not_inline
| Var of variable
| Succ of rec_info
| Unroll of int * rec_info
type coercion =
| Id
| Change_depth of
{ from : rec_info;
to_ : rec_info
}
type kinded_parameter =
{ param : variable;
kind : kind_with_subkind option
}
type name =
| Var of variable
| Symbol of symbol
type simple =
| Var of variable
| Symbol of symbol
| Const of const
| Coerce of simple * coercion
type array_kind = Flambda_primitive.Array_kind.t =
| Immediates
| Values
| Naked_floats
type box_kind = Flambda_kind.Boxable_number.t =
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
type generic_array_specialisation =
| No_specialisation
| Full_of_naked_floats
| Full_of_immediates
| Full_of_arbitrary_values_but_not_floats
type block_access_field_kind = Flambda_primitive.Block_access_field_kind.t =
| Any_value
| Immediate
type block_access_kind =
| Values of
{ tag : tag_scannable option;
size : targetint option;
field_kind : block_access_field_kind
}
| Naked_floats of { size : targetint option }
type standard_int = Flambda_kind.Standard_int.t =
| Tagged_immediate
| Naked_immediate
| Naked_int32
| Naked_int64
| Naked_nativeint
type standard_int_or_float = Flambda_kind.Standard_int_or_float.t =
| Tagged_immediate
| Naked_immediate
| Naked_float
| Naked_int32
| Naked_int64
| Naked_nativeint
type string_or_bytes = Flambda_primitive.string_or_bytes =
| String
| Bytes
type alloc_mode_for_allocations =
| Heap
| Local of { region : region }
type init_or_assign =
| Initialization
| Assignment of alloc_mode_for_allocations
type 'signed_or_unsigned comparison =
'signed_or_unsigned Flambda_primitive.comparison =
| Eq
| Neq
| Lt of 'signed_or_unsigned
| Gt of 'signed_or_unsigned
| Le of 'signed_or_unsigned
| Ge of 'signed_or_unsigned
type equality_comparison = Flambda_primitive.equality_comparison =
| Eq
| Neq
type signed_or_unsigned = Flambda_primitive.signed_or_unsigned =
| Signed
| Unsigned
type nullop = Begin_region
type unop =
| Array_length
| Box_number of box_kind
| End_region
| Get_tag
| Is_flat_float_array
| Is_int
| Num_conv of
{ src : standard_int_or_float;
dst : standard_int_or_float
}
| Opaque_identity
| Project_value_slot of
{ project_from : function_slot;
value_slot : value_slot
}
| Project_function_slot of
{ move_from : function_slot;
move_to : function_slot
}
| String_length of string_or_bytes
| Unbox_number of box_kind
| Untag_immediate
| Tag_immediate
type 'signed_or_unsigned comparison_behaviour =
'signed_or_unsigned Flambda_primitive.comparison_behaviour =
| Yielding_bool of 'signed_or_unsigned comparison
| Yielding_int_like_compare_functions of 'signed_or_unsigned
type binary_int_arith_op = Flambda_primitive.binary_int_arith_op =
| Add
| Sub
| Mul
| Div
| Mod
| And
| Or
| Xor
type int_shift_op = Flambda_primitive.int_shift_op =
| Lsl
| Lsr
| Asr
type binary_float_arith_op = Flambda_primitive.binary_float_arith_op =
| Add
| Sub
| Mul
| Div
type infix_binop =
on tagged imms
| Float_arith of binary_float_arith_op
| Float_comp of unit comparison_behaviour
type binop =
| Array_load of array_kind * mutability
| Block_load of block_access_kind * mutability
| Phys_equal of equality_comparison
| Int_arith of standard_int * binary_int_arith_op
| Int_comp of standard_int * signed_or_unsigned comparison_behaviour
| Int_shift of standard_int * int_shift_op
| Infix of infix_binop
type ternop = Array_set of array_kind * init_or_assign
type varop = Make_block of tag_scannable * mutability
type prim =
| Nullary of nullop
| Unary of unop * simple
| Binary of binop * simple * simple
| Ternary of ternop * simple * simple * simple
| Variadic of varop * simple list
type arity = kind_with_subkind list
type function_call =
| Direct of
{ code_id : code_id;
function_slot : function_slot option
}
| Indirect
type method_kind =
| Self
| Public
| Cached
type call_kind =
| Function of function_call
| Method of { kind : ; obj : simple ; }
| C_call of { alloc : bool }
type function_arities =
{ params_arity : arity option;
ret_arity : arity
}
type inline_attribute = Inline_attribute.t =
| Always_inline
| Available_inline
| Never_inline
| Unroll of int
| Default_inline
type inlined_attribute = Inlined_attribute.t =
| Always_inlined
| Hint_inlined
| Never_inlined
| Unroll of int
| Default_inlined
type apply =
{ func : name;
continuation : result_continuation;
exn_continuation : continuation;
args : simple list;
call_kind : call_kind;
arities : function_arities option;
inlined : inlined_attribute option;
inlining_state : inlining_state option;
region : region
}
type size = int
type apply_cont =
{ cont : continuation;
trap_action : trap_action option;
args : simple list
}
type expr =
| Let of let_
| Let_cont of let_cont
| Let_symbol of let_symbol
| Apply of apply
| Apply_cont of apply_cont
| Switch of
{ scrutinee : simple;
cases : (int * apply_cont) list
}
| Invalid of { message : string }
and value_slots = one_value_slot list
and one_value_slot =
{ var : value_slot;
value : simple
}
and let_ =
{ bindings : let_binding list;
value_slots : value_slots option;
body : expr
}
and let_binding =
{ var : variable;
defining_expr : named
}
and named =
| Simple of simple
| Prim of prim
| Closure of fun_decl
| Rec_info of rec_info
and fun_decl =
{ code_id : code_id;
}
and let_cont =
{ recursive : is_recursive;
body : expr;
bindings : continuation_binding list
}
and continuation_binding =
{ name : continuation_id;
params : kinded_parameter list;
sort : continuation_sort option;
handler : expr
}
and let_symbol =
{ bindings : symbol_binding list;
value_slots : value_slots option;
body : expr
}
and symbol_binding =
| Data of static_data_binding
| Code of code
| Deleted_code of code_id
| Closure of static_closure_binding
| Set_of_closures of static_set_of_closures
and static_set_of_closures =
{ bindings : static_closure_binding list;
elements : value_slots option
}
and code =
{ id : code_id;
newer_version_of : code_id option;
param_arity : arity option;
ret_arity : arity option;
recursive : is_recursive;
inline : inline_attribute option;
params_and_body : params_and_body;
code_size : code_size;
is_tupled : bool
}
and code_size = int
and params_and_body =
{ params : kinded_parameter list;
closure_var : variable;
region_var : variable;
depth_var : variable;
ret_cont : continuation_id;
exn_cont : continuation_id;
body : expr
}
and static_closure_binding =
{ symbol : symbol;
fun_decl : fun_decl
}
type flambda_unit = { body : expr }
type expect_test_spec =
{ before : flambda_unit;
after : flambda_unit
}
type markdown_node =
| Text of string
| Expect of expect_test_spec
type markdown_doc = markdown_node list
|
5128a1323f1bb0f5aba2f4291c4b5bfe16e189773ddaff581a7dae88cefe6fa9 | zack-bitcoin/amoveo | keys.erl | the hard drive stores { f , , encrypted(privkey ) , encrypted("sanity " ) ) .
%the ram stores either {pubkey, privkey} or {pubkey, ""} depending on if this node is locked.
-module(keys).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
pubkey/0, sign/1, raw_sign/1,
load/3, unlock/1,
lock/0, status/0, change_password/2, new/1,
shared_secret/1,
encrypt/2, decrypt/1, keypair/0,
test/0, format_status/2]).
%-define(LOC, "keys.db").
-define(LOC, constants:keys()).
-define(SANE(), <<"sanity">>).
start_link() ->
gen_server:start_link({local, ?MODULE},
?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_, _) ->
io:fwrite("keys died. Possibly due to incorrect password.\n"),
ok.
format_status(_,[_,_]) ->
[{[], [{"State", []}]}].
-record(f, {pub = "", priv = "", sanity = ""}).
%sanity is only used on the hard drive, not in ram.
init(ok) ->
io : fwrite("start keys\n " ) ,
X = db:read(?LOC),
Ka = if
X == "" ->
{Pub, Priv} =
signing:new_key(),
store(Pub, Priv, ""),
#f{pub = Pub, priv=Priv};
true -> #f{pub=X#f.pub}
end,
erlang:send_after(1000, self(), set_initial_keys),
{ok, Ka}.
store(Pub, Priv, Brainwallet) ->
true = size(Pub) == constants:pubkey_size(),
X = #f{pub=Pub, priv=encryption:encrypt(Priv, Brainwallet), sanity=encryption:encrypt(?SANE(), Brainwallet)},
db:save(?LOC, X),
X.
handle_call({ss, Pub}, _From, R) ->
{reply, signing:shared_secret(Pub, R#f.priv), R};
handle_call({raw_sign, _}, _From, R) when R#f.priv=="" ->
{reply, "need to unlock passphrase", R};
handle_call({raw_sign, M}, _From, X) when not is_binary(M) ->
{reply, "not binary", X};
handle_call({raw_sign, M}, _From, R) ->
{reply, signing:sign(M, R#f.priv), R};
handle_call({sign, M}, _From, R) ->
{reply, signing:sign_tx(M, R#f.pub, R#f.priv), R};
handle_call(status, _From, R) ->
Y = db:read(?LOC),
Out = if
Y#f.priv == "" -> empty;
R#f.priv == "" -> locked;
true -> unlocked
end,
{reply, Out, R};
handle_call(pubkey, _From, R) -> {reply, R#f.pub, R};
handle_call(keypair, _From, R) ->
Keys = case application:get_env(amoveo_core, test_mode, false) of
true -> {R#f.pub, R#f.priv};
_ -> none
end,
{reply, Keys, R};
handle_call({encrypt, Message, Pubkey}, _From, R) ->
EM=encryption:send_msg(Message, base64:encode(Pubkey), base64:encode(R#f.pub), base64:encode(R#f.priv)),
{reply, EM, R};
handle_call({decrypt, EMsg}, _From, R) ->
io:fwrite("keys decrypt "),
io:fwrite(packer:pack(EMsg)),
io:fwrite("\n"),
Message = encryption:get_msg(EMsg, base64:encode(R#f.priv)),
Message = encryption : get_msg(EMsg , ) ,
{reply, Message, R}.
handle_cast({load, Pub, Priv, Brainwallet}, _R) ->
store(Pub, Priv, Brainwallet),
{noreply, #f{pub=Pub, priv=Priv}};
handle_cast({new, Brainwallet}, _R) ->
{Pub, Priv} = signing:new_key(),
store(Pub, Priv, Brainwallet),
{noreply, #f{pub=Pub, priv=Priv}};
handle_cast({unlock, Brainwallet}, _) ->
X = db:read(?LOC),
?SANE() = encryption:decrypt(X#f.sanity, Brainwallet),
Priv = encryption:decrypt(X#f.priv, Brainwallet),
{noreply, #f{pub=X#f.pub, priv=Priv}};
handle_cast(lock, R) -> {noreply, #f{pub=R#f.pub}};
handle_cast({change_password, Current, New}, R) ->
X = db:read(?LOC),
?SANE() = encryption:decrypt(X#f.sanity, Current),
Priv = encryption:decrypt(X#f.priv, Current),
store(R#f.pub, Priv, New),
{noreply, R};
handle_cast(_, X) -> {noreply, X}.
handle_info(set_initial_keys, State) ->
KeysEnvs = {application:get_env(amoveo_core, keys_pub),
application:get_env(amoveo_core, keys_priv),
application:get_env(amoveo_core, keys_pass)},
case KeysEnvs of
{{ok, Pub}, {ok, Priv}, {ok, Pass}} ->
Pub2 = base64:decode(Pub),
true = size(Pub2) == constants:pubkey_size(),
load(Pub2, base64:decode(Priv), Pass),
unlock(Pass);
{undefined, undefined, {ok, Pass}} ->
unlock(Pass);
_ ->
ok
end,
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
keypair() -> gen_server:call(?MODULE, keypair).
pubkey() -> gen_server:call(?MODULE, pubkey).
sign(M) ->
S = status(),
case S of
unlocked ->
gen_server:call(?MODULE, {sign, M});
_ -> io:fwrite("you need to unlock your account before you can sign transactions. use keys:unlock(\"password\").\n"),
1=2,
{error, locked}
end.
raw_sign(M) -> gen_server:call(?MODULE, {raw_sign, M}).
load(Pub, Priv, Brainwallet) when (is_binary(Pub) and is_binary(Priv))-> gen_server:cast(?MODULE, {load, Pub, Priv, Brainwallet}).
unlock(Brainwallet) -> gen_server:cast(?MODULE, {unlock, Brainwallet}).
lock() -> gen_server:cast(?MODULE, lock).
status() -> gen_server:call(?MODULE, status).
change_password(Current, New) -> gen_server:cast(?MODULE, {change_password, Current, New}).
new(Brainwallet) -> gen_server:cast(?MODULE, {new, Brainwallet}).
shared_secret(Pub) -> gen_server:call(?MODULE, {ss, Pub}).
decrypt(EMessage) ->
packer:unpack(element(3, gen_server:call(?MODULE, {decrypt, EMessage}))).
encrypt(Message, Pubkey) ->
gen_server:call(?MODULE, {encrypt, packer:pack(Message), Pubkey}).
test() ->
unlocked = keys:status(),
Tx = {spend, 1, 1, 2, 1, 1},
Stx = sign(Tx),
true = signing:verify(Stx, 1),
success.
| null | https://raw.githubusercontent.com/zack-bitcoin/amoveo/257f3e8cc07f1bae9df1a7252b8bc67a0dad3262/apps/amoveo_core/src/consensus/keys.erl | erlang | the ram stores either {pubkey, privkey} or {pubkey, ""} depending on if this node is locked.
-define(LOC, "keys.db").
sanity is only used on the hard drive, not in ram. | the hard drive stores { f , , encrypted(privkey ) , encrypted("sanity " ) ) .
-module(keys).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
pubkey/0, sign/1, raw_sign/1,
load/3, unlock/1,
lock/0, status/0, change_password/2, new/1,
shared_secret/1,
encrypt/2, decrypt/1, keypair/0,
test/0, format_status/2]).
-define(LOC, constants:keys()).
-define(SANE(), <<"sanity">>).
start_link() ->
gen_server:start_link({local, ?MODULE},
?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_, _) ->
io:fwrite("keys died. Possibly due to incorrect password.\n"),
ok.
format_status(_,[_,_]) ->
[{[], [{"State", []}]}].
-record(f, {pub = "", priv = "", sanity = ""}).
init(ok) ->
io : fwrite("start keys\n " ) ,
X = db:read(?LOC),
Ka = if
X == "" ->
{Pub, Priv} =
signing:new_key(),
store(Pub, Priv, ""),
#f{pub = Pub, priv=Priv};
true -> #f{pub=X#f.pub}
end,
erlang:send_after(1000, self(), set_initial_keys),
{ok, Ka}.
store(Pub, Priv, Brainwallet) ->
true = size(Pub) == constants:pubkey_size(),
X = #f{pub=Pub, priv=encryption:encrypt(Priv, Brainwallet), sanity=encryption:encrypt(?SANE(), Brainwallet)},
db:save(?LOC, X),
X.
handle_call({ss, Pub}, _From, R) ->
{reply, signing:shared_secret(Pub, R#f.priv), R};
handle_call({raw_sign, _}, _From, R) when R#f.priv=="" ->
{reply, "need to unlock passphrase", R};
handle_call({raw_sign, M}, _From, X) when not is_binary(M) ->
{reply, "not binary", X};
handle_call({raw_sign, M}, _From, R) ->
{reply, signing:sign(M, R#f.priv), R};
handle_call({sign, M}, _From, R) ->
{reply, signing:sign_tx(M, R#f.pub, R#f.priv), R};
handle_call(status, _From, R) ->
Y = db:read(?LOC),
Out = if
Y#f.priv == "" -> empty;
R#f.priv == "" -> locked;
true -> unlocked
end,
{reply, Out, R};
handle_call(pubkey, _From, R) -> {reply, R#f.pub, R};
handle_call(keypair, _From, R) ->
Keys = case application:get_env(amoveo_core, test_mode, false) of
true -> {R#f.pub, R#f.priv};
_ -> none
end,
{reply, Keys, R};
handle_call({encrypt, Message, Pubkey}, _From, R) ->
EM=encryption:send_msg(Message, base64:encode(Pubkey), base64:encode(R#f.pub), base64:encode(R#f.priv)),
{reply, EM, R};
handle_call({decrypt, EMsg}, _From, R) ->
io:fwrite("keys decrypt "),
io:fwrite(packer:pack(EMsg)),
io:fwrite("\n"),
Message = encryption:get_msg(EMsg, base64:encode(R#f.priv)),
Message = encryption : get_msg(EMsg , ) ,
{reply, Message, R}.
handle_cast({load, Pub, Priv, Brainwallet}, _R) ->
store(Pub, Priv, Brainwallet),
{noreply, #f{pub=Pub, priv=Priv}};
handle_cast({new, Brainwallet}, _R) ->
{Pub, Priv} = signing:new_key(),
store(Pub, Priv, Brainwallet),
{noreply, #f{pub=Pub, priv=Priv}};
handle_cast({unlock, Brainwallet}, _) ->
X = db:read(?LOC),
?SANE() = encryption:decrypt(X#f.sanity, Brainwallet),
Priv = encryption:decrypt(X#f.priv, Brainwallet),
{noreply, #f{pub=X#f.pub, priv=Priv}};
handle_cast(lock, R) -> {noreply, #f{pub=R#f.pub}};
handle_cast({change_password, Current, New}, R) ->
X = db:read(?LOC),
?SANE() = encryption:decrypt(X#f.sanity, Current),
Priv = encryption:decrypt(X#f.priv, Current),
store(R#f.pub, Priv, New),
{noreply, R};
handle_cast(_, X) -> {noreply, X}.
handle_info(set_initial_keys, State) ->
KeysEnvs = {application:get_env(amoveo_core, keys_pub),
application:get_env(amoveo_core, keys_priv),
application:get_env(amoveo_core, keys_pass)},
case KeysEnvs of
{{ok, Pub}, {ok, Priv}, {ok, Pass}} ->
Pub2 = base64:decode(Pub),
true = size(Pub2) == constants:pubkey_size(),
load(Pub2, base64:decode(Priv), Pass),
unlock(Pass);
{undefined, undefined, {ok, Pass}} ->
unlock(Pass);
_ ->
ok
end,
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
keypair() -> gen_server:call(?MODULE, keypair).
pubkey() -> gen_server:call(?MODULE, pubkey).
sign(M) ->
S = status(),
case S of
unlocked ->
gen_server:call(?MODULE, {sign, M});
_ -> io:fwrite("you need to unlock your account before you can sign transactions. use keys:unlock(\"password\").\n"),
1=2,
{error, locked}
end.
raw_sign(M) -> gen_server:call(?MODULE, {raw_sign, M}).
load(Pub, Priv, Brainwallet) when (is_binary(Pub) and is_binary(Priv))-> gen_server:cast(?MODULE, {load, Pub, Priv, Brainwallet}).
unlock(Brainwallet) -> gen_server:cast(?MODULE, {unlock, Brainwallet}).
lock() -> gen_server:cast(?MODULE, lock).
status() -> gen_server:call(?MODULE, status).
change_password(Current, New) -> gen_server:cast(?MODULE, {change_password, Current, New}).
new(Brainwallet) -> gen_server:cast(?MODULE, {new, Brainwallet}).
shared_secret(Pub) -> gen_server:call(?MODULE, {ss, Pub}).
decrypt(EMessage) ->
packer:unpack(element(3, gen_server:call(?MODULE, {decrypt, EMessage}))).
encrypt(Message, Pubkey) ->
gen_server:call(?MODULE, {encrypt, packer:pack(Message), Pubkey}).
test() ->
unlocked = keys:status(),
Tx = {spend, 1, 1, 2, 1, 1},
Stx = sign(Tx),
true = signing:verify(Stx, 1),
success.
|
616e383e0f83eaec6f8e83c43e9d6a90bc3e0197a4dae9da4c3e0902b7a4f9ce | alertlogic/erllambda | erllambda_sup.erl | %%%---------------------------------------------------------------------------
%% @doc erllambda_sup - Erllambda Application supervisor
%%
This module implements the Erlang < code > supervisor</code > behavior , which
%% exists, but starts no server processes.
%%
%%
2018 Alert Logic , Inc.
%%%---------------------------------------------------------------------------
-module(erllambda_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
init([]) ->
Children = [
erllambda_poller:spec(),
server_spec( erllambda_config_srv, [] )
],
% in AWS Lambda environment it's better to die fast
{ok, {{one_for_one, 1, 5}, Children}}.
server_spec( Module, Args ) ->
#{id => Module,
start => {Module, start_link, Args},
restart => permanent, shutdown => (15 * 1000), type => worker,
modules => [Module]
}.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/alertlogic/erllambda/314690c4941be5c0548603cca74927deacac3b34/src/erllambda_sup.erl | erlang | ---------------------------------------------------------------------------
@doc erllambda_sup - Erllambda Application supervisor
exists, but starts no server processes.
---------------------------------------------------------------------------
API
Supervisor callbacks
====================================================================
API functions
====================================================================
====================================================================
Supervisor callbacks
====================================================================
in AWS Lambda environment it's better to die fast
====================================================================
==================================================================== | This module implements the Erlang < code > supervisor</code > behavior , which
2018 Alert Logic , Inc.
-module(erllambda_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Children = [
erllambda_poller:spec(),
server_spec( erllambda_config_srv, [] )
],
{ok, {{one_for_one, 1, 5}, Children}}.
server_spec( Module, Args ) ->
#{id => Module,
start => {Module, start_link, Args},
restart => permanent, shutdown => (15 * 1000), type => worker,
modules => [Module]
}.
Internal functions
|
07fbb6ea1654b5802ce4837545e41966110563f1fa7754a107dc221bd1e2572b | andersfugmann/amqp-client | repeat.ml | open Amqp
open Thread
let uniq s =
Printf.sprintf "%s_%d_%s" (Filename.basename Sys.argv.(0)) (Unix.getpid ()) s
let rec repeat channel queue =
Log.info "rep";
Queue.publish channel queue (Message.make "Test") >>= function
| `Ok ->
begin
Queue.get ~no_ack:true channel queue >>= function
| Some _ ->
after 1000.0 >>= fun () ->
repeat channel queue
| None -> failwith "No message"
end
| _ -> failwith "Cannot publish"
let test =
let port = Sys.getenv_opt "AMQP_PORT" |> function Some port -> Some (int_of_string port) | None -> None in
Connection.connect ~id:(uniq "") ?port "localhost" >>= fun connection ->
Log.info "Connection started";
Connection.open_channel ~id:(uniq "test.repeat") Channel.no_confirm connection >>= fun channel ->
Queue.declare channel ~auto_delete:true (uniq "test.repeat") >>= fun queue ->
repeat channel queue >>= fun () ->
Connection.close connection >>= fun () ->
Scheduler.shutdown 0 |> return
let _ =
Scheduler.go ()
| null | https://raw.githubusercontent.com/andersfugmann/amqp-client/2932a69510af550e9e156ed479f4fca7daee31cc/async/test/repeat.ml | ocaml | open Amqp
open Thread
let uniq s =
Printf.sprintf "%s_%d_%s" (Filename.basename Sys.argv.(0)) (Unix.getpid ()) s
let rec repeat channel queue =
Log.info "rep";
Queue.publish channel queue (Message.make "Test") >>= function
| `Ok ->
begin
Queue.get ~no_ack:true channel queue >>= function
| Some _ ->
after 1000.0 >>= fun () ->
repeat channel queue
| None -> failwith "No message"
end
| _ -> failwith "Cannot publish"
let test =
let port = Sys.getenv_opt "AMQP_PORT" |> function Some port -> Some (int_of_string port) | None -> None in
Connection.connect ~id:(uniq "") ?port "localhost" >>= fun connection ->
Log.info "Connection started";
Connection.open_channel ~id:(uniq "test.repeat") Channel.no_confirm connection >>= fun channel ->
Queue.declare channel ~auto_delete:true (uniq "test.repeat") >>= fun queue ->
repeat channel queue >>= fun () ->
Connection.close connection >>= fun () ->
Scheduler.shutdown 0 |> return
let _ =
Scheduler.go ()
| |
08e9ac77aad9c209299fe33c3aa01cf1648404491c787b558f19fea149afc2b7 | Eduap-com/WordMat | mmacro.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module mmacro)
Exported functions are MDEFMACRO , , $ MACROEXPAND1 , MMACRO - APPLY
MMACROEXPANDED , MMACROEXPAND and
(declare-top (special $macros $functions $transrun $translate))
;; $MACROS declared in jpg;mlisp >
(defmvar $macroexpansion ()
"Governs the expansion of Maxima Macros. The following settings are
available: FALSE means to re-expand the macro every time it gets called.
EXPAND means to remember the expansion for each individual call do that it
won't have to be re-expanded every time the form is evaluated. The form will
still grind and display as if the expansion had not taken place. DISPLACE
means to completely replace the form with the expansion. This is more space
efficient than EXPAND but grinds and displays the expansion instead of the
call."
modified-commands '($macroexpand)
setting-list '( () $expand $displace ) )
;;; LOCAL MACRO ;;;
(defmacro copy1cons (name) `(cons (car ,name) (cdr ,name)))
DEFINING A MACRO ; ; ;
(defmspec mdefmacro (form) (setq form (cdr form))
(cond ((or (null (cdr form)) (cdddr form))
(merror (intl:gettext "macro definition: must have exactly two arguments; found: ~M")
`((mdefmacro) ,@form))
)
(t (mdefmacro1 (car form) (cadr form)))))
(defun mdefmacro1 (fun body)
(let ((name) (args))
(cond ((or (atom fun)
(not (atom (caar fun)))
(member 'array (cdar fun) :test #'eq)
(mopp (setq name ($verbify (caar fun))))
(member name '($all $% $%% mqapply) :test #'eq))
(merror (intl:gettext "macro definition: illegal definition: ~M") ;ferret out all the
fun)) ; illegal forms
((not (eq name (caar fun))) ;efficiency hack I guess
(rplaca (car fun) name))) ; done in jpg;mlisp
( in MDEFINE ) .
(let ((dup (find-duplicate args :test #'eq :key #'mparam)))
(when dup
(merror (intl:gettext "macro definition: ~M occurs more than once in the parameter list") (mparam dup))))
(mredef-check name)
(do ((a args (cdr a)) (mlexprp))
((null a)
(remove1 (ncons name) 'mexpr t $functions t) ;do all arg checking,
(cond (mlexprp (mputprop name t 'mlexprp)) ; then remove MEXPR defn
(t nil)))
(cond ((mdefparam (car a)))
((and (mdeflistp a)
(mdefparam (cadr (car a))))
(setq mlexprp t))
(t
(merror (intl:gettext "macro definition: bad argument: ~M")
(car a)))))
(remove-transl-fun-props name)
(add2lnc `((,name) ,@args) $macros)
(mputprop name (mdefine1 args body) 'mmacro)
(cond ($translate (translate-and-eval-macsyma-expression
`((mdefmacro) ,fun ,body))))
`((mdefmacro simp) ,fun ,body)))
EVALUATING A MACRO CALL ; ; ;
(defun mmacro-apply (defn form)
(mmacroexpansion-check form
(if (and (atom defn)
(not (symbolp defn)))
added this clause for NIL . MAPPLY
;; doesn't really handle applying interpreter
;; closures and subrs very well.
(apply defn (cdr form))
(mapply1 defn (cdr form) (caar form) form))))
;;; MACROEXPANSION HACKERY ;;;
;; does any reformatting necessary according to the current setting of
;; $MACROEXPANSION. Note that it always returns the expansion returned
;; by displace, for future displacing.
(defun mmacroexpansion-check (form expansion)
(case $macroexpansion
(( () )
(cond ((eq (caar form) 'mmacroexpanded)
(mmacro-displace form expansion))
(t expansion)))
(($expand)
(cond ((not (eq (caar form) 'mmacroexpanded))
(displace form `((mmacroexpanded)
,expansion
,(copy1cons form)))))
expansion)
(($displace)
(mmacro-displace form expansion))
(t (mtell (intl:gettext "warning: unrecognized value of 'macroexpansion'.")))))
(defun mmacro-displace (form expansion)
(displace form (cond ((atom expansion) `((mprogn) ,expansion))
(t expansion))))
Handles memo - ized forms . them if $ MACROEXPANSION has changed .
;; Format is ((MMACROEXPANDED) <expansion> <original form>)
(defmspec mmacroexpanded (form)
(meval (mmacroexpansion-check form (cadr form))))
;;; MACROEXPANDING FUNCTIONS ;;;
(defmspec $macroexpand (form) (setq form (cdr form))
(cond ((or (null form) (cdr form))
(merror (intl:gettext "macroexpand: must have exactly one argument; found: ~M")
`(($macroexpand) ,@form)))
(t (mmacroexpand (car form)))))
(defmspec $macroexpand1 (form) (setq form (cdr form))
(cond ((or (null form) (cdr form))
(merror (intl:gettext "macroexpand1: must have exactly one argument; found: ~M")
`(($macroexpand1) ,@form)))
(t (mmacroexpand1 (car form)))))
;; Expands the top-level form repeatedly until it is no longer a macro
;; form. Has to copy the form each time because if macros are displacing
the form given to will get bashed each time . Recursion
;; is used instead of iteration so the user gets a pdl overflow error
;; if he tries to expand recursive macro definitions that never terminate.
(defun mmacroexpand (form)
(let ((test-form (if (atom form) form (copy1cons form)))
(expansion (mmacroexpand1 form)))
(cond ((equal expansion test-form)
expansion)
(t (mmacroexpand expansion)))))
;; only expands the form once. If the form is not a valid macro
form it just gets returned ( eq'ness is preserved ) . Note that if the
;; macros are displacing, the returned form is also eq to the given
;; form (which has been bashed).
(defun mmacroexpand1 (form)
(let ((funname) (macro-defn))
(cond ((or (atom form)
(atom (car form))
(member 'array (cdar form) :test #'eq)
(not (symbolp (setq funname (mop form)))))
form)
((eq funname 'mmacroexpanded)
(mmacroexpansion-check form (cadr form)))
((setq macro-defn
(or (and $transrun
(get (caar form) 'translated-mmacro))
(mget (caar form) 'mmacro)))
(mmacro-apply macro-defn form))
(t form))))
SIMPLIFICATION ; ; ;
(defprop mdefmacro simpmdefmacro operators)
emulating ( for mdefine ) in jm;simp
(defun simpmdefmacro (x ignored simp-flag)
(declare (ignore ignored simp-flag))
(cons '(mdefmacro simp) (cdr x)))
(defun displace (x y)
(setf (car x) (car y))
(setf (cdr x) (cdr y))
x)
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/src/mmacro.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
$MACROS declared in jpg;mlisp >
LOCAL MACRO ;;;
; ;
ferret out all the
illegal forms
efficiency hack I guess
done in jpg;mlisp
do all arg checking,
then remove MEXPR defn
; ;
doesn't really handle applying interpreter
closures and subrs very well.
MACROEXPANSION HACKERY ;;;
does any reformatting necessary according to the current setting of
$MACROEXPANSION. Note that it always returns the expansion returned
by displace, for future displacing.
Format is ((MMACROEXPANDED) <expansion> <original form>)
MACROEXPANDING FUNCTIONS ;;;
Expands the top-level form repeatedly until it is no longer a macro
form. Has to copy the form each time because if macros are displacing
is used instead of iteration so the user gets a pdl overflow error
if he tries to expand recursive macro definitions that never terminate.
only expands the form once. If the form is not a valid macro
macros are displacing, the returned form is also eq to the given
form (which has been bashed).
; ;
simp |
(in-package :maxima)
(macsyma-module mmacro)
Exported functions are MDEFMACRO , , $ MACROEXPAND1 , MMACRO - APPLY
MMACROEXPANDED , MMACROEXPAND and
(declare-top (special $macros $functions $transrun $translate))
(defmvar $macroexpansion ()
"Governs the expansion of Maxima Macros. The following settings are
available: FALSE means to re-expand the macro every time it gets called.
EXPAND means to remember the expansion for each individual call do that it
won't have to be re-expanded every time the form is evaluated. The form will
still grind and display as if the expansion had not taken place. DISPLACE
means to completely replace the form with the expansion. This is more space
efficient than EXPAND but grinds and displays the expansion instead of the
call."
modified-commands '($macroexpand)
setting-list '( () $expand $displace ) )
(defmacro copy1cons (name) `(cons (car ,name) (cdr ,name)))
(defmspec mdefmacro (form) (setq form (cdr form))
(cond ((or (null (cdr form)) (cdddr form))
(merror (intl:gettext "macro definition: must have exactly two arguments; found: ~M")
`((mdefmacro) ,@form))
)
(t (mdefmacro1 (car form) (cadr form)))))
(defun mdefmacro1 (fun body)
(let ((name) (args))
(cond ((or (atom fun)
(not (atom (caar fun)))
(member 'array (cdar fun) :test #'eq)
(mopp (setq name ($verbify (caar fun))))
(member name '($all $% $%% mqapply) :test #'eq))
( in MDEFINE ) .
(let ((dup (find-duplicate args :test #'eq :key #'mparam)))
(when dup
(merror (intl:gettext "macro definition: ~M occurs more than once in the parameter list") (mparam dup))))
(mredef-check name)
(do ((a args (cdr a)) (mlexprp))
((null a)
(t nil)))
(cond ((mdefparam (car a)))
((and (mdeflistp a)
(mdefparam (cadr (car a))))
(setq mlexprp t))
(t
(merror (intl:gettext "macro definition: bad argument: ~M")
(car a)))))
(remove-transl-fun-props name)
(add2lnc `((,name) ,@args) $macros)
(mputprop name (mdefine1 args body) 'mmacro)
(cond ($translate (translate-and-eval-macsyma-expression
`((mdefmacro) ,fun ,body))))
`((mdefmacro simp) ,fun ,body)))
(defun mmacro-apply (defn form)
(mmacroexpansion-check form
(if (and (atom defn)
(not (symbolp defn)))
added this clause for NIL . MAPPLY
(apply defn (cdr form))
(mapply1 defn (cdr form) (caar form) form))))
(defun mmacroexpansion-check (form expansion)
(case $macroexpansion
(( () )
(cond ((eq (caar form) 'mmacroexpanded)
(mmacro-displace form expansion))
(t expansion)))
(($expand)
(cond ((not (eq (caar form) 'mmacroexpanded))
(displace form `((mmacroexpanded)
,expansion
,(copy1cons form)))))
expansion)
(($displace)
(mmacro-displace form expansion))
(t (mtell (intl:gettext "warning: unrecognized value of 'macroexpansion'.")))))
(defun mmacro-displace (form expansion)
(displace form (cond ((atom expansion) `((mprogn) ,expansion))
(t expansion))))
Handles memo - ized forms . them if $ MACROEXPANSION has changed .
(defmspec mmacroexpanded (form)
(meval (mmacroexpansion-check form (cadr form))))
(defmspec $macroexpand (form) (setq form (cdr form))
(cond ((or (null form) (cdr form))
(merror (intl:gettext "macroexpand: must have exactly one argument; found: ~M")
`(($macroexpand) ,@form)))
(t (mmacroexpand (car form)))))
(defmspec $macroexpand1 (form) (setq form (cdr form))
(cond ((or (null form) (cdr form))
(merror (intl:gettext "macroexpand1: must have exactly one argument; found: ~M")
`(($macroexpand1) ,@form)))
(t (mmacroexpand1 (car form)))))
the form given to will get bashed each time . Recursion
(defun mmacroexpand (form)
(let ((test-form (if (atom form) form (copy1cons form)))
(expansion (mmacroexpand1 form)))
(cond ((equal expansion test-form)
expansion)
(t (mmacroexpand expansion)))))
form it just gets returned ( eq'ness is preserved ) . Note that if the
(defun mmacroexpand1 (form)
(let ((funname) (macro-defn))
(cond ((or (atom form)
(atom (car form))
(member 'array (cdar form) :test #'eq)
(not (symbolp (setq funname (mop form)))))
form)
((eq funname 'mmacroexpanded)
(mmacroexpansion-check form (cadr form)))
((setq macro-defn
(or (and $transrun
(get (caar form) 'translated-mmacro))
(mget (caar form) 'mmacro)))
(mmacro-apply macro-defn form))
(t form))))
(defprop mdefmacro simpmdefmacro operators)
(defun simpmdefmacro (x ignored simp-flag)
(declare (ignore ignored simp-flag))
(cons '(mdefmacro simp) (cdr x)))
(defun displace (x y)
(setf (car x) (car y))
(setf (cdr x) (cdr y))
x)
|
621eab76457ea61a2b42b02eee605058a10ae54adc1d8d1d69dbc1b0981b2f2b | viercc/kitchen-sink-hs | NumExpr.hs | {-# LANGUAGE RankNTypes #-}
module NumExpr where
isNegate :: (forall a. Num a => a -> a) -> Bool
isNegate f = f (Var "x") == Fun "negate" [Var "x"]
data Expr = Var String | Literal Integer | Fun String [Expr]
deriving (Eq, Show)
instance Num Expr where
fromInteger = Literal
a + b = Fun "+" [a,b]
a - b = Fun "-" [a,b]
-- etc.
negate a = Fun "negate" [a]
| null | https://raw.githubusercontent.com/viercc/kitchen-sink-hs/391efc1a30f02a65bbcc37a4391bd5cb0d3eee8c/snippets/src/NumExpr.hs | haskell | # LANGUAGE RankNTypes #
etc. | module NumExpr where
isNegate :: (forall a. Num a => a -> a) -> Bool
isNegate f = f (Var "x") == Fun "negate" [Var "x"]
data Expr = Var String | Literal Integer | Fun String [Expr]
deriving (Eq, Show)
instance Num Expr where
fromInteger = Literal
a + b = Fun "+" [a,b]
a - b = Fun "-" [a,b]
negate a = Fun "negate" [a]
|
088a4445cd784fd2f245ac7b1a23c97a66d3fb8bb51feee1b68a81324365a373 | asakeron/cljs-webgl | shader_source.cljs | (ns cljs-webgl.constants.shader-source)
(def compile-status 0x8B81)
| null | https://raw.githubusercontent.com/asakeron/cljs-webgl/f4554fbee6fbc6133a4eb0416548dabd284e735c/src/cljs/cljs_webgl/constants/shader_source.cljs | clojure | (ns cljs-webgl.constants.shader-source)
(def compile-status 0x8B81)
| |
1e3d9262264c98313617b0138fede44c78a6a83ce3c987cb391eb0d1354e5fd4 | helium/blockchain-core | blockchain_console.erl | -module(blockchain_console).
-export([command/1]).
-spec command([string()]) -> rpc_ok | {rpc_error, non_neg_integer()}.
command(Cmd) ->
%% this is the contents of clique:run but
%% we want to figure out if the command worked
%% or not
M0 = clique_command:match(Cmd),
M1 = clique_parser:parse(M0),
M2 = clique_parser:extract_global_flags(M1),
M3 = clique_parser:validate(M2),
M4 = clique_command:run(M3),
clique:print(M4, Cmd),
case M4 of
{error, {no_matching_spec, _Spec}} ->
{rpc_error, 1};
{_Status, ExitCode, _} when ExitCode == 0 ->
rpc_ok;
{_Status, ExitCode, _} ->
{rpc_error, ExitCode}
end.
| null | https://raw.githubusercontent.com/helium/blockchain-core/c3d9fc124c8004dddc85ef40af296d34b3a8b1e3/src/cli/blockchain_console.erl | erlang | this is the contents of clique:run but
we want to figure out if the command worked
or not | -module(blockchain_console).
-export([command/1]).
-spec command([string()]) -> rpc_ok | {rpc_error, non_neg_integer()}.
command(Cmd) ->
M0 = clique_command:match(Cmd),
M1 = clique_parser:parse(M0),
M2 = clique_parser:extract_global_flags(M1),
M3 = clique_parser:validate(M2),
M4 = clique_command:run(M3),
clique:print(M4, Cmd),
case M4 of
{error, {no_matching_spec, _Spec}} ->
{rpc_error, 1};
{_Status, ExitCode, _} when ExitCode == 0 ->
rpc_ok;
{_Status, ExitCode, _} ->
{rpc_error, ExitCode}
end.
|
80272950e9bb24c655f78c366adfd81ecb4e440bc62264cd03f8b1b0482d2879 | LuisThiamNye/chic | move.clj | (ns chic.controls.textbox.move
(:require
[proteus :refer [let-mutable]]
[chic.controls.textbox.helper :as hpr]
[chic.clipboard :as clipboard]
[chic.debug]
[taoensso.encore :as enc]
[chic.controls.textbox.cursor :as cursor]
[potemkin :refer [doit]]
[chic.controls.textbox.keybindings :as keybindings]
[chic.style :as style]
[chic.ui2.event :as ievt]
[chic.ui.font :as uifont]
[chic.ui :as cui]
[chic.ui.ui2 :as ui2]
[chic.clj-editor.ast :as ast]
[io.github.humbleui.paint :as huipaint]
[chic.paint :as cpaint]
[chic.util :as util]
[clj-commons.primitive-math :as prim]
[chic.ui.layout :as cuilay]
[io.github.humbleui.ui :as ui]
[chic.clj-editor.parser :as parser]
[chic.bifurcan :as b])
(:import
(io.lacuna.bifurcan Rope)
(io.github.humbleui.skija Paint Font Canvas TextLine)
(io.github.humbleui.types Rect Point RRect)
(com.ibm.icu.text BreakIterator)))
(defn ^BreakIterator make-word-iter [rope]
(doto (BreakIterator/getWordInstance)
(.setText (b/rope-character-iterator rope))))
;; this implementation gives same word-movement results as macOS TextEdit
(defn word-before [^BreakIterator iter idx]
(loop [idx' (.following iter (dec idx))
found-word? false]
(when (prim/<= 0 idx')
(if (or (prim/zero? idx') found-word?)
idx'
(let [rs (.getRuleStatus iter)]
(recur (.previous iter)
(or (prim/< rs BreakIterator/WORD_NONE)
(prim/<= BreakIterator/WORD_NONE_LIMIT rs))))))))
(defn word-after [^BreakIterator iter idx]
(let [n (.last iter)]
(loop [idx' (.following iter idx)]
(when (prim/<= 0 idx')
(if (or (prim/== n idx')
(let [rs (.getRuleStatus iter)]
;; if not punctuation/space
(or (prim/< rs BreakIterator/WORD_NONE)
(prim/<= BreakIterator/WORD_NONE_LIMIT rs))))
idx'
(recur (.next iter)))))))
(comment
(.following (make-word-iter (Rope/from "012 45 78")) 9) ;; -1
getRuleStatus is 0 at WORD_NONE boundaries
;; type of boundary defined by the index before
eg idx=3 " 012| 45 " gives number rule status ( 100 )
eg idx=0 or idx=4 " 012 |45 " gives WORD_NONE rule status ( 100 )
;; WORD_NONE includes space & punctuation and does not distinguish between them
(.getRuleStatus
(doto (make-word-iter (Rope/from "012 45 78"))
(.following 6)))
(.getRuleStatus
(doto (make-word-iter (Rope/from "012 5 78"))
(.preceding 2)))
;; there is a boundary between each instance of:
;; newline = , .
;; & other punctuation, but spaces are contiguous
(.following (make-word-iter (Rope/from "...")) 0)
;; It may be feasible to create an interator with a set of
;; custom compiled rules
(type (BreakIterator/getWordInstance)) ;; RuleBasedBreakIterator
(str (BreakIterator/getWordInstance)) ;; prints the rule source
#!
)
(defn move-cursor-to-coord* [state {:keys [x y]}]
(let [{:keys [line-start-idxs text-lines]
{:keys [line-height first-line-origin]} :layout} state
dy (- y (:y first-line-origin))
lidx (long (Math/floor (/ dy line-height)))
nlines (count line-start-idxs)
lidx (max 0 (min (dec nlines) lidx))
text-line ^TextLine (nth text-lines lidx)
dx (- x (:x first-line-origin))
cidx (.getOffsetAtCoord text-line dx)]
(-> state
(assoc :cursor-dx (.getCoordAtOffset text-line cidx))
(assoc :cursor-idx (+ (nth line-start-idxs lidx) cidx))
(assoc :cursor-line-idx lidx))))
(defn cursor-move-right* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (inc cursor-line-idx)]
(-> state
(assoc :cursor-idx (min (.size rope) (inc cursor-idx)))
(cond-> (<= (nth line-start-idxs next-line-idx Long/MAX_VALUE) (inc cursor-idx))
(assoc :cursor-line-idx next-line-idx))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-left* [{:keys [cursor-idx line-start-idxs
cursor-line-idx] :as state}]
(let [cursor-idx2 (max 0 (dec cursor-idx))]
(-> state
(assoc :cursor-idx cursor-idx2)
(cond-> (< cursor-idx2 (nth line-start-idxs cursor-line-idx))
(assoc :cursor-line-idx (dec cursor-line-idx)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-to-idx* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state} cursor-idx2]
(let [line-idx2 (hpr/find-line-idx line-start-idxs cursor-idx2)]
(-> state
(assoc :cursor-idx cursor-idx2)
(cond-> (not (== cursor-line-idx line-idx2))
(assoc :cursor-line-idx line-idx2))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-right-word* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [word-iter (make-word-iter rope)
cursor-idx2 (word-after word-iter cursor-idx)]
(if cursor-idx2
(cursor-move-to-idx* state cursor-idx2)
state)))
(defn cursor-move-left-word* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [word-iter (make-word-iter rope)
cursor-idx2 (word-before word-iter cursor-idx)]
(if cursor-idx2
(cursor-move-to-idx* state cursor-idx2)
state)))
(defn cursor-move-down* [{:keys [cursor-target-dx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (inc cursor-line-idx)
has-next? (< next-line-idx (count line-start-idxs))]
(-> state
(cond-> has-next?
(-> (assoc :cursor-line-idx next-line-idx)
(as-> state (assoc state :cursor-idx (hpr/dx->cursor-idx state cursor-target-dx)))))
(cond-> (not has-next?)
(assoc :cursor-idx (.size rope)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-up* [{:keys [cursor-target-dx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (dec cursor-line-idx)
has-prev? (<= 0 next-line-idx)]
(-> state
(cond-> has-prev?
(-> (assoc :cursor-line-idx next-line-idx)
(as-> state (assoc state :cursor-idx (hpr/dx->cursor-idx state cursor-target-dx)))))
(cond-> (not has-prev?)
(assoc :cursor-idx 0))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-start* [{:keys [line-start-idxs
cursor-line-idx] :as state}]
(-> state
(assoc :cursor-idx (nth line-start-idxs cursor-line-idx))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-end* [{:keys [^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(-> state
(assoc :cursor-idx (dec (nth line-start-idxs (inc cursor-line-idx)
(inc (.size rope)))))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-start-up* [{:keys [line-start-idxs cursor-idx
cursor-line-idx] :as state}]
(if (== cursor-idx (nth line-start-idxs cursor-line-idx))
(cursor-move-up* state)
(cursor-move-start* state)))
(defn cursor-move-end-down* [{:keys [^Rope rope line-start-idxs
cursor-line-idx cursor-idx] :as state}]
(if (== cursor-idx (dec (nth line-start-idxs (inc cursor-line-idx)
(inc (.size rope)))))
(-> state cursor-move-down* cursor-move-end*)
(cursor-move-end* state)))
(defn cursor-move-doc-start* [{:keys [] :as state}]
(-> state
(assoc :cursor-idx 0)
(assoc :cursor-line-idx 0)
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-doc-end* [{:keys [^Rope rope line-start-idxs] :as state}]
(-> state
(assoc :cursor-idx (.size rope))
(assoc :cursor-line-idx (dec (count line-start-idxs)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn handle-move-intent [*state intent]
(case intent
:move-right
(vswap! *state cursor-move-right*)
:move-left
(vswap! *state cursor-move-left*)
:move-right-word
(vswap! *state cursor-move-right-word*)
:move-left-word
(vswap! *state cursor-move-left-word*)
:move-down
(vswap! *state cursor-move-down*)
:move-up
(vswap! *state cursor-move-up*)
:move-start
(vswap! *state cursor-move-start*)
:move-end
(vswap! *state cursor-move-end*)
:move-start-up
(vswap! *state cursor-move-start-up*)
:move-end-down
(vswap! *state cursor-move-end-down*)
:move-doc-start
(vswap! *state cursor-move-doc-start*)
:move-doc-end
(vswap! *state cursor-move-doc-end*)
nil))
| null | https://raw.githubusercontent.com/LuisThiamNye/chic/813633a689f9080731613f788a295604d4d9a510/src/chic/controls/textbox/move.clj | clojure | this implementation gives same word-movement results as macOS TextEdit
if not punctuation/space
-1
type of boundary defined by the index before
WORD_NONE includes space & punctuation and does not distinguish between them
there is a boundary between each instance of:
newline = , .
& other punctuation, but spaces are contiguous
It may be feasible to create an interator with a set of
custom compiled rules
RuleBasedBreakIterator
prints the rule source | (ns chic.controls.textbox.move
(:require
[proteus :refer [let-mutable]]
[chic.controls.textbox.helper :as hpr]
[chic.clipboard :as clipboard]
[chic.debug]
[taoensso.encore :as enc]
[chic.controls.textbox.cursor :as cursor]
[potemkin :refer [doit]]
[chic.controls.textbox.keybindings :as keybindings]
[chic.style :as style]
[chic.ui2.event :as ievt]
[chic.ui.font :as uifont]
[chic.ui :as cui]
[chic.ui.ui2 :as ui2]
[chic.clj-editor.ast :as ast]
[io.github.humbleui.paint :as huipaint]
[chic.paint :as cpaint]
[chic.util :as util]
[clj-commons.primitive-math :as prim]
[chic.ui.layout :as cuilay]
[io.github.humbleui.ui :as ui]
[chic.clj-editor.parser :as parser]
[chic.bifurcan :as b])
(:import
(io.lacuna.bifurcan Rope)
(io.github.humbleui.skija Paint Font Canvas TextLine)
(io.github.humbleui.types Rect Point RRect)
(com.ibm.icu.text BreakIterator)))
(defn ^BreakIterator make-word-iter [rope]
(doto (BreakIterator/getWordInstance)
(.setText (b/rope-character-iterator rope))))
(defn word-before [^BreakIterator iter idx]
(loop [idx' (.following iter (dec idx))
found-word? false]
(when (prim/<= 0 idx')
(if (or (prim/zero? idx') found-word?)
idx'
(let [rs (.getRuleStatus iter)]
(recur (.previous iter)
(or (prim/< rs BreakIterator/WORD_NONE)
(prim/<= BreakIterator/WORD_NONE_LIMIT rs))))))))
(defn word-after [^BreakIterator iter idx]
(let [n (.last iter)]
(loop [idx' (.following iter idx)]
(when (prim/<= 0 idx')
(if (or (prim/== n idx')
(let [rs (.getRuleStatus iter)]
(or (prim/< rs BreakIterator/WORD_NONE)
(prim/<= BreakIterator/WORD_NONE_LIMIT rs))))
idx'
(recur (.next iter)))))))
(comment
getRuleStatus is 0 at WORD_NONE boundaries
eg idx=3 " 012| 45 " gives number rule status ( 100 )
eg idx=0 or idx=4 " 012 |45 " gives WORD_NONE rule status ( 100 )
(.getRuleStatus
(doto (make-word-iter (Rope/from "012 45 78"))
(.following 6)))
(.getRuleStatus
(doto (make-word-iter (Rope/from "012 5 78"))
(.preceding 2)))
(.following (make-word-iter (Rope/from "...")) 0)
#!
)
(defn move-cursor-to-coord* [state {:keys [x y]}]
(let [{:keys [line-start-idxs text-lines]
{:keys [line-height first-line-origin]} :layout} state
dy (- y (:y first-line-origin))
lidx (long (Math/floor (/ dy line-height)))
nlines (count line-start-idxs)
lidx (max 0 (min (dec nlines) lidx))
text-line ^TextLine (nth text-lines lidx)
dx (- x (:x first-line-origin))
cidx (.getOffsetAtCoord text-line dx)]
(-> state
(assoc :cursor-dx (.getCoordAtOffset text-line cidx))
(assoc :cursor-idx (+ (nth line-start-idxs lidx) cidx))
(assoc :cursor-line-idx lidx))))
(defn cursor-move-right* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (inc cursor-line-idx)]
(-> state
(assoc :cursor-idx (min (.size rope) (inc cursor-idx)))
(cond-> (<= (nth line-start-idxs next-line-idx Long/MAX_VALUE) (inc cursor-idx))
(assoc :cursor-line-idx next-line-idx))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-left* [{:keys [cursor-idx line-start-idxs
cursor-line-idx] :as state}]
(let [cursor-idx2 (max 0 (dec cursor-idx))]
(-> state
(assoc :cursor-idx cursor-idx2)
(cond-> (< cursor-idx2 (nth line-start-idxs cursor-line-idx))
(assoc :cursor-line-idx (dec cursor-line-idx)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-to-idx* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state} cursor-idx2]
(let [line-idx2 (hpr/find-line-idx line-start-idxs cursor-idx2)]
(-> state
(assoc :cursor-idx cursor-idx2)
(cond-> (not (== cursor-line-idx line-idx2))
(assoc :cursor-line-idx line-idx2))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-right-word* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [word-iter (make-word-iter rope)
cursor-idx2 (word-after word-iter cursor-idx)]
(if cursor-idx2
(cursor-move-to-idx* state cursor-idx2)
state)))
(defn cursor-move-left-word* [{:keys [cursor-idx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [word-iter (make-word-iter rope)
cursor-idx2 (word-before word-iter cursor-idx)]
(if cursor-idx2
(cursor-move-to-idx* state cursor-idx2)
state)))
(defn cursor-move-down* [{:keys [cursor-target-dx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (inc cursor-line-idx)
has-next? (< next-line-idx (count line-start-idxs))]
(-> state
(cond-> has-next?
(-> (assoc :cursor-line-idx next-line-idx)
(as-> state (assoc state :cursor-idx (hpr/dx->cursor-idx state cursor-target-dx)))))
(cond-> (not has-next?)
(assoc :cursor-idx (.size rope)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-up* [{:keys [cursor-target-dx ^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(let [next-line-idx (dec cursor-line-idx)
has-prev? (<= 0 next-line-idx)]
(-> state
(cond-> has-prev?
(-> (assoc :cursor-line-idx next-line-idx)
(as-> state (assoc state :cursor-idx (hpr/dx->cursor-idx state cursor-target-dx)))))
(cond-> (not has-prev?)
(assoc :cursor-idx 0))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state))))))
(defn cursor-move-start* [{:keys [line-start-idxs
cursor-line-idx] :as state}]
(-> state
(assoc :cursor-idx (nth line-start-idxs cursor-line-idx))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-end* [{:keys [^Rope rope line-start-idxs
cursor-line-idx] :as state}]
(-> state
(assoc :cursor-idx (dec (nth line-start-idxs (inc cursor-line-idx)
(inc (.size rope)))))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-start-up* [{:keys [line-start-idxs cursor-idx
cursor-line-idx] :as state}]
(if (== cursor-idx (nth line-start-idxs cursor-line-idx))
(cursor-move-up* state)
(cursor-move-start* state)))
(defn cursor-move-end-down* [{:keys [^Rope rope line-start-idxs
cursor-line-idx cursor-idx] :as state}]
(if (== cursor-idx (dec (nth line-start-idxs (inc cursor-line-idx)
(inc (.size rope)))))
(-> state cursor-move-down* cursor-move-end*)
(cursor-move-end* state)))
(defn cursor-move-doc-start* [{:keys [] :as state}]
(-> state
(assoc :cursor-idx 0)
(assoc :cursor-line-idx 0)
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn cursor-move-doc-end* [{:keys [^Rope rope line-start-idxs] :as state}]
(-> state
(assoc :cursor-idx (.size rope))
(assoc :cursor-line-idx (dec (count line-start-idxs)))
(as-> state (assoc state :cursor-dx (hpr/calc-cursor-dx state)))))
(defn handle-move-intent [*state intent]
(case intent
:move-right
(vswap! *state cursor-move-right*)
:move-left
(vswap! *state cursor-move-left*)
:move-right-word
(vswap! *state cursor-move-right-word*)
:move-left-word
(vswap! *state cursor-move-left-word*)
:move-down
(vswap! *state cursor-move-down*)
:move-up
(vswap! *state cursor-move-up*)
:move-start
(vswap! *state cursor-move-start*)
:move-end
(vswap! *state cursor-move-end*)
:move-start-up
(vswap! *state cursor-move-start-up*)
:move-end-down
(vswap! *state cursor-move-end-down*)
:move-doc-start
(vswap! *state cursor-move-doc-start*)
:move-doc-end
(vswap! *state cursor-move-doc-end*)
nil))
|
f01f45cfb069a11abf434366a882db993a094fdcfcf12fd0e782222b00f13692 | rbardou/red | layout.mli | (** Panel layouts. *)
(** How to split a layout. *)
type split_direction =
| Vertical (** top and bottom *)
| Horizontal (** left and right *)
(** Where to split a layout. *)
type split_position =
| Absolute_first of int (** set the size of the top or left sublayout, and the other one takes the rest *)
| Absolute_second of int (** set the size of the bottom or right sublayout, and the other one takes the rest *)
| Ratio of int * int (** numerator, denominator: denotes a fraction of the parent's size *)
(** The main sublayout to pick with [get_main_panel]. *)
type split_main =
| First
| Second
(** Panel layouts. *)
type t
(** A layout with a single panel. *)
val single: Panel.t -> t
(** Create a view for a file, create a panel for this view, and return a single layout for this panel. *)
val create_file: File.t -> t
* A layout split in two .
val split: split_direction -> ?pos: split_position -> ?sep: bool -> ?main: split_main -> t -> t -> t
(** Get the main panel of a layout. *)
val get_main_panel: t -> Panel.t
(** Render a layout by computing panel positions and calling a render function on them. *)
val render:
(Render.frame -> Panel.t -> x: int -> y: int -> w: int -> h: int -> unit) ->
Render.frame -> ?x: int -> ?y: int -> w: int -> h: int -> t -> unit
(** Get the panel which is at the right of given panel.
If several panels are at the right, return the top-left one. *)
val get_panel_right: Panel.t -> t -> Panel.t option
(** Get the panel which is at the left of given panel. *)
val get_panel_left: Panel.t -> t -> Panel.t option
(** Get the panel which is below a given panel. *)
val get_panel_down: Panel.t -> t -> Panel.t option
(** Get the panel which is above a given panel. *)
val get_panel_up: Panel.t -> t -> Panel.t option
(** Replace a panel by a layout.
Usage: [replace_panel panel replacement layout]
Return [None] if [panel] was not found in [layout]. *)
val replace_panel: Panel.t -> t -> t -> t option
(** Remove a panel.
Return [None] if panel was not found in layout or if it is the only panel.
Also return the panel which was next to the removed panel. *)
val remove_panel: Panel.t -> t -> (t * Panel.t) option
(** Return whether a panel is visible in a layout. *)
val panel_is_visible: Panel.t -> t -> bool
(** Iterate on each panel. *)
val foreach_panel: t -> (Panel.t -> unit) -> unit
| null | https://raw.githubusercontent.com/rbardou/red/e23c2830909b9e5cd6afe563313435ddaeda90bf/src/layout.mli | ocaml | * Panel layouts.
* How to split a layout.
* top and bottom
* left and right
* Where to split a layout.
* set the size of the top or left sublayout, and the other one takes the rest
* set the size of the bottom or right sublayout, and the other one takes the rest
* numerator, denominator: denotes a fraction of the parent's size
* The main sublayout to pick with [get_main_panel].
* Panel layouts.
* A layout with a single panel.
* Create a view for a file, create a panel for this view, and return a single layout for this panel.
* Get the main panel of a layout.
* Render a layout by computing panel positions and calling a render function on them.
* Get the panel which is at the right of given panel.
If several panels are at the right, return the top-left one.
* Get the panel which is at the left of given panel.
* Get the panel which is below a given panel.
* Get the panel which is above a given panel.
* Replace a panel by a layout.
Usage: [replace_panel panel replacement layout]
Return [None] if [panel] was not found in [layout].
* Remove a panel.
Return [None] if panel was not found in layout or if it is the only panel.
Also return the panel which was next to the removed panel.
* Return whether a panel is visible in a layout.
* Iterate on each panel. |
type split_direction =
type split_position =
type split_main =
| First
| Second
type t
val single: Panel.t -> t
val create_file: File.t -> t
* A layout split in two .
val split: split_direction -> ?pos: split_position -> ?sep: bool -> ?main: split_main -> t -> t -> t
val get_main_panel: t -> Panel.t
val render:
(Render.frame -> Panel.t -> x: int -> y: int -> w: int -> h: int -> unit) ->
Render.frame -> ?x: int -> ?y: int -> w: int -> h: int -> t -> unit
val get_panel_right: Panel.t -> t -> Panel.t option
val get_panel_left: Panel.t -> t -> Panel.t option
val get_panel_down: Panel.t -> t -> Panel.t option
val get_panel_up: Panel.t -> t -> Panel.t option
val replace_panel: Panel.t -> t -> t -> t option
val remove_panel: Panel.t -> t -> (t * Panel.t) option
val panel_is_visible: Panel.t -> t -> bool
val foreach_panel: t -> (Panel.t -> unit) -> unit
|
2386d81f2fbb72241ebd642fd7fe72bec94db2fd6eaaadc138e8753e03af9bda | xtdb/xtdb | lubm.clj | (ns xtdb.fixtures.lubm
(:require [xtdb.fixtures :refer [*api*]]
[xtdb.api :as xt]
[xtdb.rdf :as rdf]))
(def ^:const lubm-triples-resource-8k "lubm/University0_0.ntriples")
(def ^:const lubm-triples-resource-100k "lubm/lubm10.ntriples")
(defn with-lubm-data [f]
(let [last-tx (->> (concat (rdf/->tx-ops (rdf/ntriples "lubm/univ-bench.ntriples"))
(rdf/->tx-ops (rdf/ntriples lubm-triples-resource-8k)))
(rdf/->default-language)
(partition-all 1000)
(reduce (fn [_ tx-ops]
(xt/submit-tx *api* (vec tx-ops)))
nil))]
(xt/await-tx *api* last-tx)
(f)))
| null | https://raw.githubusercontent.com/xtdb/xtdb/e2f51ed99fc2716faa8ad254c0b18166c937b134/test/test/xtdb/fixtures/lubm.clj | clojure | (ns xtdb.fixtures.lubm
(:require [xtdb.fixtures :refer [*api*]]
[xtdb.api :as xt]
[xtdb.rdf :as rdf]))
(def ^:const lubm-triples-resource-8k "lubm/University0_0.ntriples")
(def ^:const lubm-triples-resource-100k "lubm/lubm10.ntriples")
(defn with-lubm-data [f]
(let [last-tx (->> (concat (rdf/->tx-ops (rdf/ntriples "lubm/univ-bench.ntriples"))
(rdf/->tx-ops (rdf/ntriples lubm-triples-resource-8k)))
(rdf/->default-language)
(partition-all 1000)
(reduce (fn [_ tx-ops]
(xt/submit-tx *api* (vec tx-ops)))
nil))]
(xt/await-tx *api* last-tx)
(f)))
| |
5c6c93971d13163dde7c538aa470577a39b222b9259d7c25a29fad890beb2209 | Akii/acme-fucks | Fucks.hs | module Acme.Fucks
( Fucks
, Amount
, giveFucks
) where
import Control.Monad
type Amount = Int
| Tells us how many fucks were given that day .
-- We make it a phantom type (parametrized over `f`) because we would like to pretend we're able to give a fuck about anything.
newtype Fucks f = Fucks Amount
-- | The essence of how many fucks should be given.
It first , we do n't give a fuck . If at any point , somehow a fuck is given , we make sure to not give a fuck again .
instance Monoid (Fucks f) where
mempty = Fucks 0
mappend _ _ = mempty
| This functor instance makes a ton of sense but is not law - abiding .
--
-- It makes sense because: regardless how much fuck we give, we're only fooling ourselves.
-- We can't and so, wont, give a single fuck.
--
-- It is not law-abiding because:
Law # 1 : fmap i d = i d
-- We notice that applying any transformation, even something like `id`, always results in no fucks given.
Law # 2 : fmap ( p . q ) = ( fmap p ) . ( fmap q )
We do n't even have to give this one a fuck because law # 1 has been broken .
instance Functor Fucks where
fmap _ _ = mempty
-- | Provided something that wants to make us give a fuck (raise awareness) in regards to the low amount of fucks given,
-- we ignore the problem and still do not give a fuck.
--
" TODO " : Laws
instance Applicative Fucks where
pure = mempty
_ <*> _ = mempty
-- | No one really gives a fuck about Monads.
--
" TODO " : Laws
instance Monad Fucks where
_ >>= _ = mempty
giveFucks :: Amount -> Maybe (Fucks f)
giveFucks 0 = Just mempty
giveFucks _ = Nothing
| null | https://raw.githubusercontent.com/Akii/acme-fucks/ef9221d19cf9914f804fe8050abe91285d41f0cf/src/Acme/Fucks.hs | haskell | We make it a phantom type (parametrized over `f`) because we would like to pretend we're able to give a fuck about anything.
| The essence of how many fucks should be given.
It makes sense because: regardless how much fuck we give, we're only fooling ourselves.
We can't and so, wont, give a single fuck.
It is not law-abiding because:
We notice that applying any transformation, even something like `id`, always results in no fucks given.
| Provided something that wants to make us give a fuck (raise awareness) in regards to the low amount of fucks given,
we ignore the problem and still do not give a fuck.
| No one really gives a fuck about Monads.
| module Acme.Fucks
( Fucks
, Amount
, giveFucks
) where
import Control.Monad
type Amount = Int
| Tells us how many fucks were given that day .
newtype Fucks f = Fucks Amount
It first , we do n't give a fuck . If at any point , somehow a fuck is given , we make sure to not give a fuck again .
instance Monoid (Fucks f) where
mempty = Fucks 0
mappend _ _ = mempty
| This functor instance makes a ton of sense but is not law - abiding .
Law # 1 : fmap i d = i d
Law # 2 : fmap ( p . q ) = ( fmap p ) . ( fmap q )
We do n't even have to give this one a fuck because law # 1 has been broken .
instance Functor Fucks where
fmap _ _ = mempty
" TODO " : Laws
instance Applicative Fucks where
pure = mempty
_ <*> _ = mempty
" TODO " : Laws
instance Monad Fucks where
_ >>= _ = mempty
giveFucks :: Amount -> Maybe (Fucks f)
giveFucks 0 = Just mempty
giveFucks _ = Nothing
|
41d1e26c761ea3a494d9938195715866b19a2419649291bb404023d8801b04bd | bmeurer/ocaml-arm | format.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
* Pretty printing .
This module implements a pretty - printing facility to format text
within ` ` pretty - printing boxes '' . The pretty - printer breaks lines
at specified break hints , and indents lines according to the box
structure .
For a gentle introduction to the basics of pretty - printing using
[ Format ] , read
{ { : }
} .
You may consider this module as providing an extension to the
[ printf ] facility to provide automatic line breaking . The addition of
pretty - printing annotations to your regular [ printf ] formats gives you
fancy indentation and line breaks .
Pretty - printing annotations are described below in the documentation of
the function { ! Format.fprintf } .
You may also use the explicit box management and printing functions
provided by this module . This style is more basic but more verbose
than the [ fprintf ] concise formats .
For instance , the sequence
[ open_box 0 ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ]
that prints [ x = 1 ] within a pretty - printing box , can be
abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter
[ printf " @[x = @ % i@]@. " 1 ] .
Rule of thumb for casual users of this library :
- use simple boxes ( as obtained by [ open_box 0 ] ) ;
- use simple break hints ( as obtained by [ print_cut ( ) ] that outputs a
simple break hint , or by [ print_space ( ) ] that outputs a space
indicating a break hint ) ;
- once a box is opened , display its material with basic printing
functions ( [ print_int ] and [ print_string ] ) ;
- when the material for a box has been printed , call [ close_box ( ) ] to
close the box ;
- at the end of your routine , flush the pretty - printer to display all the
remaining material , e.g. evaluate [ print_newline ( ) ] .
The behaviour of pretty - printing commands is unspecified
if there is no opened pretty - printing box . Each box opened via
one of the [ open _ ] functions below must be closed using [ close_box ]
for proper formatting . Otherwise , some of the material printed in the
boxes may not be output , or may be formatted incorrectly .
In case of interactive use , the system closes all opened boxes and
flushes all pending text ( as with the [ print_newline ] function )
after each phrase . Each phrase is therefore executed in the initial
state of the pretty - printer .
Warning : the material output by the following functions is delayed
in the pretty - printer queue in order to compute the proper line
breaking . Hence , you should not mix calls to the printing functions
of the basic I / O system with calls to the functions of this module :
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands .
This module implements a pretty-printing facility to format text
within ``pretty-printing boxes''. The pretty-printer breaks lines
at specified break hints, and indents lines according to the box
structure.
For a gentle introduction to the basics of pretty-printing using
[Format], read
{{:}
}.
You may consider this module as providing an extension to the
[printf] facility to provide automatic line breaking. The addition of
pretty-printing annotations to your regular [printf] formats gives you
fancy indentation and line breaks.
Pretty-printing annotations are described below in the documentation of
the function {!Format.fprintf}.
You may also use the explicit box management and printing functions
provided by this module. This style is more basic but more verbose
than the [fprintf] concise formats.
For instance, the sequence
[open_box 0; print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()]
that prints [x = 1] within a pretty-printing box, can be
abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter
[printf "@[x =@ %i@]@." 1].
Rule of thumb for casual users of this library:
- use simple boxes (as obtained by [open_box 0]);
- use simple break hints (as obtained by [print_cut ()] that outputs a
simple break hint, or by [print_space ()] that outputs a space
indicating a break hint);
- once a box is opened, display its material with basic printing
functions (e. g. [print_int] and [print_string]);
- when the material for a box has been printed, call [close_box ()] to
close the box;
- at the end of your routine, flush the pretty-printer to display all the
remaining material, e.g. evaluate [print_newline ()].
The behaviour of pretty-printing commands is unspecified
if there is no opened pretty-printing box. Each box opened via
one of the [open_] functions below must be closed using [close_box]
for proper formatting. Otherwise, some of the material printed in the
boxes may not be output, or may be formatted incorrectly.
In case of interactive use, the system closes all opened boxes and
flushes all pending text (as with the [print_newline] function)
after each phrase. Each phrase is therefore executed in the initial
state of the pretty-printer.
Warning: the material output by the following functions is delayed
in the pretty-printer queue in order to compute the proper line
breaking. Hence, you should not mix calls to the printing functions
of the basic I/O system with calls to the functions of this module:
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands.
*)
* { 6 Boxes }
val open_box : int -> unit;;
(** [open_box d] opens a new pretty-printing box
with offset [d].
This box is the general purpose pretty-printing box.
Material in this box is displayed ``horizontal or vertical'':
break hints inside the box may lead to a new line, if there
is no more room on the line to print the remainder of the box,
or if a new line may lead to a new indentation
(demonstrating the indentation of the box).
When a new line is printed in the box, [d] is added to the
current indentation. *)
val close_box : unit -> unit;;
(** Closes the most recently opened pretty-printing box. *)
* { 6 Formatting functions }
val print_string : string -> unit;;
(** [print_string str] prints [str] in the current box. *)
val print_as : int -> string -> unit;;
* [ ] prints [ str ] in the
current box . The pretty - printer formats [ str ] as if
it were of length [ len ] .
current box. The pretty-printer formats [str] as if
it were of length [len]. *)
val print_int : int -> unit;;
(** Prints an integer in the current box. *)
val print_float : float -> unit;;
(** Prints a floating point number in the current box. *)
val print_char : char -> unit;;
(** Prints a character in the current box. *)
val print_bool : bool -> unit;;
(** Prints a boolean in the current box. *)
* { 6 Break hints }
val print_space : unit -> unit;;
* [ print_space ( ) ] is used to separate items ( typically to print
a space between two words ) .
It indicates that the line may be split at this
point . It either prints one space or splits the line .
It is equivalent to [ print_break 1 0 ] .
a space between two words).
It indicates that the line may be split at this
point. It either prints one space or splits the line.
It is equivalent to [print_break 1 0]. *)
val print_cut : unit -> unit;;
* [ print_cut ( ) ] is used to mark a good break position .
It indicates that the line may be split at this
point . It either prints nothing or splits the line .
This allows line splitting at the current
point , without printing spaces or adding indentation .
It is equivalent to [ print_break 0 0 ] .
It indicates that the line may be split at this
point. It either prints nothing or splits the line.
This allows line splitting at the current
point, without printing spaces or adding indentation.
It is equivalent to [print_break 0 0]. *)
val print_break : int -> int -> unit;;
(** Inserts a break hint in a pretty-printing box.
[print_break nspaces offset] indicates that the line may
be split (a newline character is printed) at this point,
if the contents of the current box does not fit on the
current line.
If the line is split at that point, [offset] is added to
the current indentation. If the line is not split,
[nspaces] spaces are printed. *)
val print_flush : unit -> unit;;
(** Flushes the pretty printer: all opened boxes are closed,
and all pending text is displayed. *)
val print_newline : unit -> unit;;
(** Equivalent to [print_flush] followed by a new line. *)
val force_newline : unit -> unit;;
(** Forces a newline in the current box. Not the normal way of
pretty-printing, you should prefer break hints. *)
val print_if_newline : unit -> unit;;
(** Executes the next formatting command if the preceding line
has just been split. Otherwise, ignore the next formatting
command. *)
* { 6 Margin }
val set_margin : int -> unit;;
* [ set_margin d ] sets the value of the right margin
to [ d ] ( in characters ): this value is used to detect line
overflows that leads to split lines .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the right margin is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
to [d] (in characters): this value is used to detect line
overflows that leads to split lines.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the right margin is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_margin : unit -> int;;
(** Returns the position of the right margin. *)
* { 6 Maximum indentation limit }
val set_max_indent : int -> unit;;
* [ set_max_indent d ] sets the value of the maximum
indentation limit to [ d ] ( in characters ):
once this limit is reached , boxes are rejected to the left ,
if they do not fit on the current line .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the limit is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
indentation limit to [d] (in characters):
once this limit is reached, boxes are rejected to the left,
if they do not fit on the current line.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the limit is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_max_indent : unit -> int;;
(** Return the value of the maximum indentation limit (in characters). *)
* { 6 Formatting depth : maximum number of boxes allowed before ellipsis }
val set_max_boxes : int -> unit;;
* [ set_max_boxes max ] sets the maximum number
of boxes simultaneously opened .
Material inside boxes nested deeper is printed as an
ellipsis ( more precisely as the text returned by
[ get_ellipsis_text ( ) ] ) .
Nothing happens if [ max ] is smaller than 2 .
of boxes simultaneously opened.
Material inside boxes nested deeper is printed as an
ellipsis (more precisely as the text returned by
[get_ellipsis_text ()]).
Nothing happens if [max] is smaller than 2. *)
val get_max_boxes : unit -> int;;
(** Returns the maximum number of boxes allowed before ellipsis. *)
val over_max_boxes : unit -> bool;;
(** Tests if the maximum number of boxes allowed have already been opened. *)
* { 6 Advanced formatting }
val open_hbox : unit -> unit;;
(** [open_hbox ()] opens a new pretty-printing box.
This box is ``horizontal'': the line is not split in this box
(new lines may still occur inside boxes nested deeper). *)
val open_vbox : int -> unit;;
(** [open_vbox d] opens a new pretty-printing box
with offset [d].
This box is ``vertical'': every break hint inside this
box leads to a new line.
When a new line is printed in the box, [d] is added to the
current indentation. *)
val open_hvbox : int -> unit;;
(** [open_hvbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal-vertical'': it behaves as an
``horizontal'' box if it fits on a single line,
otherwise it behaves as a ``vertical'' box.
When a new line is printed in the box, [d] is added to the
current indentation. *)
val open_hovbox : int -> unit;;
(** [open_hovbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal or vertical'': break hints
inside this box may lead to a new line, if there is no more room
on the line to print the remainder of the box.
When a new line is printed in the box, [d] is added to the
current indentation. *)
* { 6 Tabulations }
val open_tbox : unit -> unit;;
(** Opens a tabulation box. *)
val close_tbox : unit -> unit;;
(** Closes the most recently opened tabulation box. *)
val print_tbreak : int -> int -> unit;;
* Break hint in a tabulation box .
[ print_tbreak spaces offset ] moves the insertion point to
the next tabulation ( [ spaces ] being added to this position ) .
Nothing occurs if insertion point is already on a
tabulation mark .
If there is no next tabulation on the line , then a newline
is printed and the insertion point moves to the first
tabulation of the box .
If a new line is printed , [ offset ] is added to the current
indentation .
[print_tbreak spaces offset] moves the insertion point to
the next tabulation ([spaces] being added to this position).
Nothing occurs if insertion point is already on a
tabulation mark.
If there is no next tabulation on the line, then a newline
is printed and the insertion point moves to the first
tabulation of the box.
If a new line is printed, [offset] is added to the current
indentation. *)
val set_tab : unit -> unit;;
(** Sets a tabulation mark at the current insertion point. *)
val print_tab : unit -> unit;;
(** [print_tab ()] is equivalent to [print_tbreak 0 0]. *)
* { 6 Ellipsis }
val set_ellipsis_text : string -> unit;;
(** Set the text of the ellipsis printed when too many boxes
are opened (a single dot, [.], by default). *)
val get_ellipsis_text : unit -> string;;
(** Return the text of the ellipsis. *)
* { 6 : tags Semantics Tags }
type tag = string;;
* { i Semantics tags } ( or simply { e tags } ) are used to decorate printed
entities for user 's defined purposes , e.g. setting font and giving size
indications for a display device , or marking delimitation of semantics
entities ( e.g. HTML or TeX elements or terminal escape sequences ) .
By default , those tags do not influence line breaking calculation :
the tag ` ` markers '' are not considered as part of the printing
material that drives line breaking ( in other words , the length of
those strings is considered as zero for line breaking ) .
Thus , tag handling is in some sense transparent to pretty - printing
and does not interfere with usual pretty - printing . Hence , a single
pretty printing routine can output both simple ` ` verbatim ''
material or richer decorated output depending on the treatment of
tags . By default , tags are not active , hence the output is not
decorated with tag information . Once [ set_tags ] is set to [ true ] ,
the pretty printer engine honours tags and decorates the output
accordingly .
When a tag has been opened ( or closed ) , it is both and successively
` ` printed '' and ` ` marked '' . Printing a tag means calling a
formatter specific function with the name of the tag as argument :
that ` ` tag printing '' function can then print any regular material
to the formatter ( so that this material is enqueued as usual in the
formatter queue for further line - breaking computation ) . Marking a
tag means to output an arbitrary string ( the ` ` tag marker '' ) ,
directly into the output device of the formatter . Hence , the
formatter specific ` ` tag marking '' function must return the tag
marker string associated to its tag argument . Being flushed
directly into the output device of the formatter , tag marker
strings are not considered as part of the printing material that
drives line breaking ( in other words , the length of the strings
corresponding to tag markers is considered as zero for line
breaking ) . In addition , advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines , and
precisely when the queue is flushed into the output device .
In the spirit of HTML tags , the default tag marking functions
output tags enclosed in " < " and " > " : hence , the opening marker of
tag [ t ] is [ " < t > " ] and the closing marker [ " < /t > " ] .
tag printing functions just do nothing .
Tag marking and tag printing functions are user definable and can
be set by calling [ set_formatter_tag_functions ] .
entities for user's defined purposes, e.g. setting font and giving size
indications for a display device, or marking delimitation of semantics
entities (e.g. HTML or TeX elements or terminal escape sequences).
By default, those tags do not influence line breaking calculation:
the tag ``markers'' are not considered as part of the printing
material that drives line breaking (in other words, the length of
those strings is considered as zero for line breaking).
Thus, tag handling is in some sense transparent to pretty-printing
and does not interfere with usual pretty-printing. Hence, a single
pretty printing routine can output both simple ``verbatim''
material or richer decorated output depending on the treatment of
tags. By default, tags are not active, hence the output is not
decorated with tag information. Once [set_tags] is set to [true],
the pretty printer engine honours tags and decorates the output
accordingly.
When a tag has been opened (or closed), it is both and successively
``printed'' and ``marked''. Printing a tag means calling a
formatter specific function with the name of the tag as argument:
that ``tag printing'' function can then print any regular material
to the formatter (so that this material is enqueued as usual in the
formatter queue for further line-breaking computation). Marking a
tag means to output an arbitrary string (the ``tag marker''),
directly into the output device of the formatter. Hence, the
formatter specific ``tag marking'' function must return the tag
marker string associated to its tag argument. Being flushed
directly into the output device of the formatter, tag marker
strings are not considered as part of the printing material that
drives line breaking (in other words, the length of the strings
corresponding to tag markers is considered as zero for line
breaking). In addition, advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines, and
precisely when the queue is flushed into the output device.
In the spirit of HTML tags, the default tag marking functions
output tags enclosed in "<" and ">": hence, the opening marker of
tag [t] is ["<t>"] and the closing marker ["</t>"].
Default tag printing functions just do nothing.
Tag marking and tag printing functions are user definable and can
be set by calling [set_formatter_tag_functions]. *)
val open_tag : tag -> unit;;
(** [open_tag t] opens the tag named [t]; the [print_open_tag]
function of the formatter is called with [t] as argument;
the tag marker [mark_open_tag t] will be flushed into the output
device of the formatter. *)
val close_tag : unit -> unit;;
(** [close_tag ()] closes the most recently opened tag [t].
In addition, the [print_close_tag] function of the formatter is called
with [t] as argument. The marker [mark_close_tag t] will be flushed
into the output device of the formatter. *)
val set_tags : bool -> unit;;
(** [set_tags b] turns on or off the treatment of tags (default is off). *)
val set_print_tags : bool -> unit;;
val set_mark_tags : bool -> unit;;
(** [set_print_tags b] turns on or off the printing of tags, while
[set_mark_tags b] turns on or off the output of tag markers. *)
val get_print_tags : unit -> bool;;
val get_mark_tags : unit -> bool;;
(** Return the current status of tags printing and tags marking. *)
* { 6 Redirecting the standard formatter output }
val set_formatter_out_channel : Pervasives.out_channel -> unit;;
(** Redirect the pretty-printer output to the given channel.
(All the output functions of the standard formatter are set to the
default output functions printing to the given channel.) *)
val set_formatter_output_functions :
(string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
(** [set_formatter_output_functions out flush] redirects the
relevant pretty-printer output functions to the functions [out] and
[flush].
The [out] function performs the pretty-printer string output. It is called
with a string [s], a start position [p], and a number of characters
[n]; it is supposed to output characters [p] to [p + n - 1] of
[s]. The [flush] function is called whenever the pretty-printer is
flushed (via conversion [%!], pretty-printing indications [@?] or [@.],
or using low level function [print_flush] or [print_newline]). *)
val get_formatter_output_functions :
unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
(** Return the current output functions of the pretty-printer. *)
* { 6 : meaning Changing the meaning of standard formatter pretty printing }
(** The [Format] module is versatile enough to let you completely redefine
the meaning of pretty printing: you may provide your own functions to define
how to handle indentation, line breaking, and even printing of all the
characters that have to be printed! *)
val set_all_formatter_output_functions :
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) ->
spaces:(int -> unit) ->
unit
;;
* [ set_all_formatter_output_functions out flush outnewline outspace ]
redirects the pretty - printer output to the functions [ out ] and
[ flush ] as described in [ set_formatter_output_functions ] . In
addition , the pretty - printer function that outputs a newline is set
to the function [ outnewline ] and the function that outputs
indentation spaces is set to the function [ outspace ] .
This way , you can change the meaning of indentation ( which can be
something else than just printing space characters ) and the
meaning of new lines opening ( which can be connected to any other
action needed by the application at hand ) . The two functions
[ outspace ] and [ outnewline ] are normally connected to [ out ] and
[ flush ] : respective default values for [ outspace ] and [ outnewline ]
are [ out ( String.make n ' ' ) 0 n ] and [ out " \n " 0 1 ] .
redirects the pretty-printer output to the functions [out] and
[flush] as described in [set_formatter_output_functions]. In
addition, the pretty-printer function that outputs a newline is set
to the function [outnewline] and the function that outputs
indentation spaces is set to the function [outspace].
This way, you can change the meaning of indentation (which can be
something else than just printing space characters) and the
meaning of new lines opening (which can be connected to any other
action needed by the application at hand). The two functions
[outspace] and [outnewline] are normally connected to [out] and
[flush]: respective default values for [outspace] and [outnewline]
are [out (String.make n ' ') 0 n] and [out "\n" 0 1]. *)
val get_all_formatter_output_functions :
unit ->
(string -> int -> int -> unit) *
(unit -> unit) *
(unit -> unit) *
(int -> unit)
;;
(** Return the current output functions of the pretty-printer,
including line breaking and indentation functions. Useful to record the
current setting and restore it afterwards. *)
* { 6 : tagsmeaning Changing the meaning of printing semantics tags }
type formatter_tag_functions = {
mark_open_tag : tag -> string;
mark_close_tag : tag -> string;
print_open_tag : tag -> unit;
print_close_tag : tag -> unit;
}
;;
(** The tag handling functions specific to a formatter:
[mark] versions are the ``tag marking'' functions that associate a string
marker to a tag in order for the pretty-printing engine to flush
those markers as 0 length tokens in the output device of the formatter.
[print] versions are the ``tag printing'' functions that can perform
regular printing when a tag is closed or opened. *)
val set_formatter_tag_functions :
formatter_tag_functions -> unit
;;
(** [set_formatter_tag_functions tag_funs] changes the meaning of
opening and closing tags to use the functions in [tag_funs].
When opening a tag name [t], the string [t] is passed to the
opening tag marking function (the [mark_open_tag] field of the
record [tag_funs]), that must return the opening tag marker for
that name. When the next call to [close_tag ()] happens, the tag
name [t] is sent back to the closing tag marking function (the
[mark_close_tag] field of record [tag_funs]), that must return a
closing tag marker for that name.
The [print_] field of the record contains the functions that are
called at tag opening and tag closing time, to output regular
material in the pretty-printer queue. *)
val get_formatter_tag_functions :
unit -> formatter_tag_functions
;;
(** Return the current tag functions of the pretty-printer. *)
* { 6 Multiple formatted output }
type formatter;;
(** Abstract data corresponding to a pretty-printer (also called a
formatter) and all its machinery.
Defining new pretty-printers permits unrelated output of material in
parallel on several output channels.
All the parameters of a pretty-printer are local to this pretty-printer:
margin, maximum indentation limit, maximum number of boxes
simultaneously opened, ellipsis, and so on, are specific to
each pretty-printer and may be fixed independently.
Given a [Pervasives.out_channel] output channel [oc], a new formatter
writing to that channel is simply obtained by calling
[formatter_of_out_channel oc].
Alternatively, the [make_formatter] function allocates a new
formatter with explicit output and flushing functions
(convenient to output material to strings for instance).
*)
val formatter_of_out_channel : out_channel -> formatter;;
(** [formatter_of_out_channel oc] returns a new formatter that
writes to the corresponding channel [oc]. *)
val std_formatter : formatter;;
(** The standard formatter used by the formatting functions
above. It is defined as [formatter_of_out_channel stdout]. *)
val err_formatter : formatter;;
(** A formatter to use with formatting functions below for
output to standard error. It is defined as
[formatter_of_out_channel stderr]. *)
val formatter_of_buffer : Buffer.t -> formatter;;
(** [formatter_of_buffer b] returns a new formatter writing to
buffer [b]. As usual, the formatter has to be flushed at
the end of pretty printing, using [pp_print_flush] or
[pp_print_newline], to display all the pending material. *)
val stdbuf : Buffer.t;;
(** The string buffer in which [str_formatter] writes. *)
val str_formatter : formatter;;
(** A formatter to use with formatting functions below for
output to the [stdbuf] string buffer.
[str_formatter] is defined as [formatter_of_buffer stdbuf]. *)
val flush_str_formatter : unit -> string;;
(** Returns the material printed with [str_formatter], flushes
the formatter and resets the corresponding buffer. *)
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
;;
(** [make_formatter out flush] returns a new formatter that writes according
to the output function [out], and the flushing function [flush]. For
instance, a formatter to the [Pervasives.out_channel] [oc] is returned by
[make_formatter (Pervasives.output oc) (fun () -> Pervasives.flush oc)]. *)
* { 6 Basic functions to use with formatters }
val pp_open_hbox : formatter -> unit -> unit;;
val pp_open_vbox : formatter -> int -> unit;;
val pp_open_hvbox : formatter -> int -> unit;;
val pp_open_hovbox : formatter -> int -> unit;;
val pp_open_box : formatter -> int -> unit;;
val pp_close_box : formatter -> unit -> unit;;
val pp_open_tag : formatter -> string -> unit;;
val pp_close_tag : formatter -> unit -> unit;;
val pp_print_string : formatter -> string -> unit;;
val pp_print_as : formatter -> int -> string -> unit;;
val pp_print_int : formatter -> int -> unit;;
val pp_print_float : formatter -> float -> unit;;
val pp_print_char : formatter -> char -> unit;;
val pp_print_bool : formatter -> bool -> unit;;
val pp_print_break : formatter -> int -> int -> unit;;
val pp_print_cut : formatter -> unit -> unit;;
val pp_print_space : formatter -> unit -> unit;;
val pp_force_newline : formatter -> unit -> unit;;
val pp_print_flush : formatter -> unit -> unit;;
val pp_print_newline : formatter -> unit -> unit;;
val pp_print_if_newline : formatter -> unit -> unit;;
val pp_open_tbox : formatter -> unit -> unit;;
val pp_close_tbox : formatter -> unit -> unit;;
val pp_print_tbreak : formatter -> int -> int -> unit;;
val pp_set_tab : formatter -> unit -> unit;;
val pp_print_tab : formatter -> unit -> unit;;
val pp_set_tags : formatter -> bool -> unit;;
val pp_set_print_tags : formatter -> bool -> unit;;
val pp_set_mark_tags : formatter -> bool -> unit;;
val pp_get_print_tags : formatter -> unit -> bool;;
val pp_get_mark_tags : formatter -> unit -> bool;;
val pp_set_margin : formatter -> int -> unit;;
val pp_get_margin : formatter -> unit -> int;;
val pp_set_max_indent : formatter -> int -> unit;;
val pp_get_max_indent : formatter -> unit -> int;;
val pp_set_max_boxes : formatter -> int -> unit;;
val pp_get_max_boxes : formatter -> unit -> int;;
val pp_over_max_boxes : formatter -> unit -> bool;;
val pp_set_ellipsis_text : formatter -> string -> unit;;
val pp_get_ellipsis_text : formatter -> unit -> string;;
val pp_set_formatter_out_channel : formatter -> Pervasives.out_channel -> unit;;
val pp_set_formatter_output_functions :
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
val pp_set_all_formatter_output_functions :
formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
;;
val pp_get_all_formatter_output_functions :
formatter -> unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
;;
val pp_set_formatter_tag_functions :
formatter -> formatter_tag_functions -> unit
;;
val pp_get_formatter_tag_functions :
formatter -> unit -> formatter_tag_functions
;;
(** These functions are the basic ones: usual functions
operating on the standard formatter are defined via partial
evaluation of these primitives. For instance,
[print_string] is equal to [pp_print_string std_formatter]. *)
* { 6 [ printf ] like functions for pretty - printing . }
val fprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ]
according to the format string [ fmt ] , and outputs the resulting string on
the formatter [ ff ] .
The format [ fmt ] is a character string which contains three types of
objects : plain characters and conversion specifications as specified in
the [ Printf ] module , and pretty - printing indications specific to the
[ Format ] module .
The pretty - printing indication characters are introduced by
a [ @ ] character , and their meanings are :
- [ @\ [ ] : open a pretty - printing box . The type and offset of the
box may be optionally specified with the following syntax :
the [ < ] character , followed by an optional box type indication ,
then an optional integer offset , and the closing [ > ] character .
Box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] ,
which stand respectively for an horizontal box , a vertical box ,
an ` ` horizontal - vertical '' box , or an ` ` horizontal or
vertical '' box ( [ b ] standing for an ` ` horizontal or
vertical '' box demonstrating indentation and [ hov ] standing
for a regular``horizontal or vertical '' box ) .
For instance , [ @\[<hov 2 > ] opens an ` ` horizontal or vertical ''
box with indentation 2 as obtained with [ open_hovbox 2 ] .
For more details about boxes , see the various box opening
functions [ open_*box ] .
- [ @\ ] ] : close the most recently opened pretty - printing box .
- [ @ , ] : output a good break as with [ print_cut ( ) ] .
- [ @ ] : output a space , as with [ print_space ( ) ] .
- [ @\n ] : force a newline , as with [ force_newline ( ) ] .
- [ @ ; ] : output a good break as with [ print_break ] . The
[ nspaces ] and [ offset ] parameters of the break may be
optionally specified with the following syntax :
the [ < ] character , followed by an integer [ nspaces ] value ,
then an integer [ offset ] , and a closing [ > ] character .
If no parameters are provided , the good break defaults to a
space .
- [ @ ? ] : flush the pretty printer as with [ print_flush ( ) ] .
This is equivalent to the conversion [ % ! ] .
- [ @. ] : flush the pretty printer and output a new line , as with
[ print_newline ( ) ] .
- [ @<n > ] : print the following item as if it were of length [ n ] .
Hence , [ printf " @<0>%s " arg ] prints [ arg ] as a zero length string .
If [ @<n > ] is not followed by a conversion specification ,
then the following character of the format is printed as if
it were of length [ n ] .
- [ @\ { ] : open a tag . The name of the tag may be optionally
specified with the following syntax :
the [ < ] character , followed by an optional string
specification , and the closing [ > ] character . The string
specification is any character string that does not contain the
closing character [ ' > ' ] . If omitted , the tag name defaults to the
empty string .
For more details about tags , see the functions [ open_tag ] and
[ close_tag ] .
- [ @\ } ] : close the most recently opened tag .
Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to
[ open_box ( ) ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ] .
It prints [ x = 1 ] within a pretty - printing box .
Note : the old [ @@ ] ` ` pretty - printing indication '' is now deprecated , since
it had no pretty - printing indication semantics . If you need to prevent
the pretty - printing indication interpretation of a [ @ ] character , simply
use the regular way to escape a character in format string : write [ % @ ] .
@since 3.12.2 .
according to the format string [fmt], and outputs the resulting string on
the formatter [ff].
The format [fmt] is a character string which contains three types of
objects: plain characters and conversion specifications as specified in
the [Printf] module, and pretty-printing indications specific to the
[Format] module.
The pretty-printing indication characters are introduced by
a [@] character, and their meanings are:
- [@\[]: open a pretty-printing box. The type and offset of the
box may be optionally specified with the following syntax:
the [<] character, followed by an optional box type indication,
then an optional integer offset, and the closing [>] character.
Box type is one of [h], [v], [hv], [b], or [hov],
which stand respectively for an horizontal box, a vertical box,
an ``horizontal-vertical'' box, or an ``horizontal or
vertical'' box ([b] standing for an ``horizontal or
vertical'' box demonstrating indentation and [hov] standing
for a regular``horizontal or vertical'' box).
For instance, [@\[<hov 2>] opens an ``horizontal or vertical''
box with indentation 2 as obtained with [open_hovbox 2].
For more details about boxes, see the various box opening
functions [open_*box].
- [@\]]: close the most recently opened pretty-printing box.
- [@,]: output a good break as with [print_cut ()].
- [@ ]: output a space, as with [print_space ()].
- [@\n]: force a newline, as with [force_newline ()].
- [@;]: output a good break as with [print_break]. The
[nspaces] and [offset] parameters of the break may be
optionally specified with the following syntax:
the [<] character, followed by an integer [nspaces] value,
then an integer [offset], and a closing [>] character.
If no parameters are provided, the good break defaults to a
space.
- [@?]: flush the pretty printer as with [print_flush ()].
This is equivalent to the conversion [%!].
- [@.]: flush the pretty printer and output a new line, as with
[print_newline ()].
- [@<n>]: print the following item as if it were of length [n].
Hence, [printf "@<0>%s" arg] prints [arg] as a zero length string.
If [@<n>] is not followed by a conversion specification,
then the following character of the format is printed as if
it were of length [n].
- [@\{]: open a tag. The name of the tag may be optionally
specified with the following syntax:
the [<] character, followed by an optional string
specification, and the closing [>] character. The string
specification is any character string that does not contain the
closing character ['>']. If omitted, the tag name defaults to the
empty string.
For more details about tags, see the functions [open_tag] and
[close_tag].
- [@\}]: close the most recently opened tag.
Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to
[open_box (); print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()].
It prints [x = 1] within a pretty-printing box.
Note: the old [@@] ``pretty-printing indication'' is now deprecated, since
it had no pretty-printing indication semantics. If you need to prevent
the pretty-printing indication interpretation of a [@] character, simply
use the regular way to escape a character in format string: write [%@].
@since 3.12.2.
*)
val printf : ('a, formatter, unit) format -> 'a;;
(** Same as [fprintf] above, but output on [std_formatter]. *)
val eprintf : ('a, formatter, unit) format -> 'a;;
(** Same as [fprintf] above, but output on [err_formatter]. *)
val sprintf : ('a, unit, string) format -> 'a;;
(** Same as [printf] above, but instead of printing on a formatter,
returns a string containing the result of formatting the arguments.
Note that the pretty-printer queue is flushed at the end of {e each
call} to [sprintf].
In case of multiple and related calls to [sprintf] to output
material on a single string, you should consider using [fprintf]
with the predefined formatter [str_formatter] and call
[flush_str_formatter ()] to get the final result.
Alternatively, you can use [Format.fprintf] with a formatter writing to a
buffer of your own: flushing the formatter and the buffer at the end of
pretty-printing returns the desired string. *)
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* Same as [ fprintf ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.10.0
Useful to ignore some material when conditionally printing.
@since 3.10.0
*)
(** Formatted output functions with continuations. *)
val kfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ fprintf ] above , but instead of returning immediately ,
passes the formatter to its first argument at the end of printing .
passes the formatter to its first argument at the end of printing. *)
val ikfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.12.0
Useful to ignore some material when conditionally printing.
@since 3.12.0
*)
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
* Same as [ sprintf ] above , but instead of returning the string ,
passes it to the first argument .
passes it to the first argument. *)
* { 6 Deprecated }
val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a;;
* A deprecated and error prone function . Do not use it .
If you need to print to some buffer [ b ] , you must first define a
formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then
use regular calls to [ Format.fprintf ] on formatter [ to_b ] .
If you need to print to some buffer [b], you must first define a
formatter writing to [b], using [let to_b = formatter_of_buffer b]; then
use regular calls to [Format.fprintf] on formatter [to_b]. *)
val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
(** A deprecated synonym for [ksprintf]. *)
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/stdlib/format.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* [open_box d] opens a new pretty-printing box
with offset [d].
This box is the general purpose pretty-printing box.
Material in this box is displayed ``horizontal or vertical'':
break hints inside the box may lead to a new line, if there
is no more room on the line to print the remainder of the box,
or if a new line may lead to a new indentation
(demonstrating the indentation of the box).
When a new line is printed in the box, [d] is added to the
current indentation.
* Closes the most recently opened pretty-printing box.
* [print_string str] prints [str] in the current box.
* Prints an integer in the current box.
* Prints a floating point number in the current box.
* Prints a character in the current box.
* Prints a boolean in the current box.
* Inserts a break hint in a pretty-printing box.
[print_break nspaces offset] indicates that the line may
be split (a newline character is printed) at this point,
if the contents of the current box does not fit on the
current line.
If the line is split at that point, [offset] is added to
the current indentation. If the line is not split,
[nspaces] spaces are printed.
* Flushes the pretty printer: all opened boxes are closed,
and all pending text is displayed.
* Equivalent to [print_flush] followed by a new line.
* Forces a newline in the current box. Not the normal way of
pretty-printing, you should prefer break hints.
* Executes the next formatting command if the preceding line
has just been split. Otherwise, ignore the next formatting
command.
* Returns the position of the right margin.
* Return the value of the maximum indentation limit (in characters).
* Returns the maximum number of boxes allowed before ellipsis.
* Tests if the maximum number of boxes allowed have already been opened.
* [open_hbox ()] opens a new pretty-printing box.
This box is ``horizontal'': the line is not split in this box
(new lines may still occur inside boxes nested deeper).
* [open_vbox d] opens a new pretty-printing box
with offset [d].
This box is ``vertical'': every break hint inside this
box leads to a new line.
When a new line is printed in the box, [d] is added to the
current indentation.
* [open_hvbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal-vertical'': it behaves as an
``horizontal'' box if it fits on a single line,
otherwise it behaves as a ``vertical'' box.
When a new line is printed in the box, [d] is added to the
current indentation.
* [open_hovbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal or vertical'': break hints
inside this box may lead to a new line, if there is no more room
on the line to print the remainder of the box.
When a new line is printed in the box, [d] is added to the
current indentation.
* Opens a tabulation box.
* Closes the most recently opened tabulation box.
* Sets a tabulation mark at the current insertion point.
* [print_tab ()] is equivalent to [print_tbreak 0 0].
* Set the text of the ellipsis printed when too many boxes
are opened (a single dot, [.], by default).
* Return the text of the ellipsis.
* [open_tag t] opens the tag named [t]; the [print_open_tag]
function of the formatter is called with [t] as argument;
the tag marker [mark_open_tag t] will be flushed into the output
device of the formatter.
* [close_tag ()] closes the most recently opened tag [t].
In addition, the [print_close_tag] function of the formatter is called
with [t] as argument. The marker [mark_close_tag t] will be flushed
into the output device of the formatter.
* [set_tags b] turns on or off the treatment of tags (default is off).
* [set_print_tags b] turns on or off the printing of tags, while
[set_mark_tags b] turns on or off the output of tag markers.
* Return the current status of tags printing and tags marking.
* Redirect the pretty-printer output to the given channel.
(All the output functions of the standard formatter are set to the
default output functions printing to the given channel.)
* [set_formatter_output_functions out flush] redirects the
relevant pretty-printer output functions to the functions [out] and
[flush].
The [out] function performs the pretty-printer string output. It is called
with a string [s], a start position [p], and a number of characters
[n]; it is supposed to output characters [p] to [p + n - 1] of
[s]. The [flush] function is called whenever the pretty-printer is
flushed (via conversion [%!], pretty-printing indications [@?] or [@.],
or using low level function [print_flush] or [print_newline]).
* Return the current output functions of the pretty-printer.
* The [Format] module is versatile enough to let you completely redefine
the meaning of pretty printing: you may provide your own functions to define
how to handle indentation, line breaking, and even printing of all the
characters that have to be printed!
* Return the current output functions of the pretty-printer,
including line breaking and indentation functions. Useful to record the
current setting and restore it afterwards.
* The tag handling functions specific to a formatter:
[mark] versions are the ``tag marking'' functions that associate a string
marker to a tag in order for the pretty-printing engine to flush
those markers as 0 length tokens in the output device of the formatter.
[print] versions are the ``tag printing'' functions that can perform
regular printing when a tag is closed or opened.
* [set_formatter_tag_functions tag_funs] changes the meaning of
opening and closing tags to use the functions in [tag_funs].
When opening a tag name [t], the string [t] is passed to the
opening tag marking function (the [mark_open_tag] field of the
record [tag_funs]), that must return the opening tag marker for
that name. When the next call to [close_tag ()] happens, the tag
name [t] is sent back to the closing tag marking function (the
[mark_close_tag] field of record [tag_funs]), that must return a
closing tag marker for that name.
The [print_] field of the record contains the functions that are
called at tag opening and tag closing time, to output regular
material in the pretty-printer queue.
* Return the current tag functions of the pretty-printer.
* Abstract data corresponding to a pretty-printer (also called a
formatter) and all its machinery.
Defining new pretty-printers permits unrelated output of material in
parallel on several output channels.
All the parameters of a pretty-printer are local to this pretty-printer:
margin, maximum indentation limit, maximum number of boxes
simultaneously opened, ellipsis, and so on, are specific to
each pretty-printer and may be fixed independently.
Given a [Pervasives.out_channel] output channel [oc], a new formatter
writing to that channel is simply obtained by calling
[formatter_of_out_channel oc].
Alternatively, the [make_formatter] function allocates a new
formatter with explicit output and flushing functions
(convenient to output material to strings for instance).
* [formatter_of_out_channel oc] returns a new formatter that
writes to the corresponding channel [oc].
* The standard formatter used by the formatting functions
above. It is defined as [formatter_of_out_channel stdout].
* A formatter to use with formatting functions below for
output to standard error. It is defined as
[formatter_of_out_channel stderr].
* [formatter_of_buffer b] returns a new formatter writing to
buffer [b]. As usual, the formatter has to be flushed at
the end of pretty printing, using [pp_print_flush] or
[pp_print_newline], to display all the pending material.
* The string buffer in which [str_formatter] writes.
* A formatter to use with formatting functions below for
output to the [stdbuf] string buffer.
[str_formatter] is defined as [formatter_of_buffer stdbuf].
* Returns the material printed with [str_formatter], flushes
the formatter and resets the corresponding buffer.
* [make_formatter out flush] returns a new formatter that writes according
to the output function [out], and the flushing function [flush]. For
instance, a formatter to the [Pervasives.out_channel] [oc] is returned by
[make_formatter (Pervasives.output oc) (fun () -> Pervasives.flush oc)].
* These functions are the basic ones: usual functions
operating on the standard formatter are defined via partial
evaluation of these primitives. For instance,
[print_string] is equal to [pp_print_string std_formatter].
* Same as [fprintf] above, but output on [std_formatter].
* Same as [fprintf] above, but output on [err_formatter].
* Same as [printf] above, but instead of printing on a formatter,
returns a string containing the result of formatting the arguments.
Note that the pretty-printer queue is flushed at the end of {e each
call} to [sprintf].
In case of multiple and related calls to [sprintf] to output
material on a single string, you should consider using [fprintf]
with the predefined formatter [str_formatter] and call
[flush_str_formatter ()] to get the final result.
Alternatively, you can use [Format.fprintf] with a formatter writing to a
buffer of your own: flushing the formatter and the buffer at the end of
pretty-printing returns the desired string.
* Formatted output functions with continuations.
* A deprecated synonym for [ksprintf]. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
* Pretty printing .
This module implements a pretty - printing facility to format text
within ` ` pretty - printing boxes '' . The pretty - printer breaks lines
at specified break hints , and indents lines according to the box
structure .
For a gentle introduction to the basics of pretty - printing using
[ Format ] , read
{ { : }
} .
You may consider this module as providing an extension to the
[ printf ] facility to provide automatic line breaking . The addition of
pretty - printing annotations to your regular [ printf ] formats gives you
fancy indentation and line breaks .
Pretty - printing annotations are described below in the documentation of
the function { ! Format.fprintf } .
You may also use the explicit box management and printing functions
provided by this module . This style is more basic but more verbose
than the [ fprintf ] concise formats .
For instance , the sequence
[ open_box 0 ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ]
that prints [ x = 1 ] within a pretty - printing box , can be
abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter
[ printf " @[x = @ % i@]@. " 1 ] .
Rule of thumb for casual users of this library :
- use simple boxes ( as obtained by [ open_box 0 ] ) ;
- use simple break hints ( as obtained by [ print_cut ( ) ] that outputs a
simple break hint , or by [ print_space ( ) ] that outputs a space
indicating a break hint ) ;
- once a box is opened , display its material with basic printing
functions ( [ print_int ] and [ print_string ] ) ;
- when the material for a box has been printed , call [ close_box ( ) ] to
close the box ;
- at the end of your routine , flush the pretty - printer to display all the
remaining material , e.g. evaluate [ print_newline ( ) ] .
The behaviour of pretty - printing commands is unspecified
if there is no opened pretty - printing box . Each box opened via
one of the [ open _ ] functions below must be closed using [ close_box ]
for proper formatting . Otherwise , some of the material printed in the
boxes may not be output , or may be formatted incorrectly .
In case of interactive use , the system closes all opened boxes and
flushes all pending text ( as with the [ print_newline ] function )
after each phrase . Each phrase is therefore executed in the initial
state of the pretty - printer .
Warning : the material output by the following functions is delayed
in the pretty - printer queue in order to compute the proper line
breaking . Hence , you should not mix calls to the printing functions
of the basic I / O system with calls to the functions of this module :
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands .
This module implements a pretty-printing facility to format text
within ``pretty-printing boxes''. The pretty-printer breaks lines
at specified break hints, and indents lines according to the box
structure.
For a gentle introduction to the basics of pretty-printing using
[Format], read
{{:}
}.
You may consider this module as providing an extension to the
[printf] facility to provide automatic line breaking. The addition of
pretty-printing annotations to your regular [printf] formats gives you
fancy indentation and line breaks.
Pretty-printing annotations are described below in the documentation of
the function {!Format.fprintf}.
You may also use the explicit box management and printing functions
provided by this module. This style is more basic but more verbose
than the [fprintf] concise formats.
For instance, the sequence
[open_box 0; print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()]
that prints [x = 1] within a pretty-printing box, can be
abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter
[printf "@[x =@ %i@]@." 1].
Rule of thumb for casual users of this library:
- use simple boxes (as obtained by [open_box 0]);
- use simple break hints (as obtained by [print_cut ()] that outputs a
simple break hint, or by [print_space ()] that outputs a space
indicating a break hint);
- once a box is opened, display its material with basic printing
functions (e. g. [print_int] and [print_string]);
- when the material for a box has been printed, call [close_box ()] to
close the box;
- at the end of your routine, flush the pretty-printer to display all the
remaining material, e.g. evaluate [print_newline ()].
The behaviour of pretty-printing commands is unspecified
if there is no opened pretty-printing box. Each box opened via
one of the [open_] functions below must be closed using [close_box]
for proper formatting. Otherwise, some of the material printed in the
boxes may not be output, or may be formatted incorrectly.
In case of interactive use, the system closes all opened boxes and
flushes all pending text (as with the [print_newline] function)
after each phrase. Each phrase is therefore executed in the initial
state of the pretty-printer.
Warning: the material output by the following functions is delayed
in the pretty-printer queue in order to compute the proper line
breaking. Hence, you should not mix calls to the printing functions
of the basic I/O system with calls to the functions of this module:
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands.
*)
* { 6 Boxes }
val open_box : int -> unit;;
val close_box : unit -> unit;;
* { 6 Formatting functions }
val print_string : string -> unit;;
val print_as : int -> string -> unit;;
* [ ] prints [ str ] in the
current box . The pretty - printer formats [ str ] as if
it were of length [ len ] .
current box. The pretty-printer formats [str] as if
it were of length [len]. *)
val print_int : int -> unit;;
val print_float : float -> unit;;
val print_char : char -> unit;;
val print_bool : bool -> unit;;
* { 6 Break hints }
val print_space : unit -> unit;;
* [ print_space ( ) ] is used to separate items ( typically to print
a space between two words ) .
It indicates that the line may be split at this
point . It either prints one space or splits the line .
It is equivalent to [ print_break 1 0 ] .
a space between two words).
It indicates that the line may be split at this
point. It either prints one space or splits the line.
It is equivalent to [print_break 1 0]. *)
val print_cut : unit -> unit;;
* [ print_cut ( ) ] is used to mark a good break position .
It indicates that the line may be split at this
point . It either prints nothing or splits the line .
This allows line splitting at the current
point , without printing spaces or adding indentation .
It is equivalent to [ print_break 0 0 ] .
It indicates that the line may be split at this
point. It either prints nothing or splits the line.
This allows line splitting at the current
point, without printing spaces or adding indentation.
It is equivalent to [print_break 0 0]. *)
val print_break : int -> int -> unit;;
val print_flush : unit -> unit;;
val print_newline : unit -> unit;;
val force_newline : unit -> unit;;
val print_if_newline : unit -> unit;;
* { 6 Margin }
val set_margin : int -> unit;;
* [ set_margin d ] sets the value of the right margin
to [ d ] ( in characters ): this value is used to detect line
overflows that leads to split lines .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the right margin is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
to [d] (in characters): this value is used to detect line
overflows that leads to split lines.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the right margin is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_margin : unit -> int;;
* { 6 Maximum indentation limit }
val set_max_indent : int -> unit;;
* [ set_max_indent d ] sets the value of the maximum
indentation limit to [ d ] ( in characters ):
once this limit is reached , boxes are rejected to the left ,
if they do not fit on the current line .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the limit is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
indentation limit to [d] (in characters):
once this limit is reached, boxes are rejected to the left,
if they do not fit on the current line.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the limit is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_max_indent : unit -> int;;
* { 6 Formatting depth : maximum number of boxes allowed before ellipsis }
val set_max_boxes : int -> unit;;
* [ set_max_boxes max ] sets the maximum number
of boxes simultaneously opened .
Material inside boxes nested deeper is printed as an
ellipsis ( more precisely as the text returned by
[ get_ellipsis_text ( ) ] ) .
Nothing happens if [ max ] is smaller than 2 .
of boxes simultaneously opened.
Material inside boxes nested deeper is printed as an
ellipsis (more precisely as the text returned by
[get_ellipsis_text ()]).
Nothing happens if [max] is smaller than 2. *)
val get_max_boxes : unit -> int;;
val over_max_boxes : unit -> bool;;
* { 6 Advanced formatting }
val open_hbox : unit -> unit;;
val open_vbox : int -> unit;;
val open_hvbox : int -> unit;;
val open_hovbox : int -> unit;;
* { 6 Tabulations }
val open_tbox : unit -> unit;;
val close_tbox : unit -> unit;;
val print_tbreak : int -> int -> unit;;
* Break hint in a tabulation box .
[ print_tbreak spaces offset ] moves the insertion point to
the next tabulation ( [ spaces ] being added to this position ) .
Nothing occurs if insertion point is already on a
tabulation mark .
If there is no next tabulation on the line , then a newline
is printed and the insertion point moves to the first
tabulation of the box .
If a new line is printed , [ offset ] is added to the current
indentation .
[print_tbreak spaces offset] moves the insertion point to
the next tabulation ([spaces] being added to this position).
Nothing occurs if insertion point is already on a
tabulation mark.
If there is no next tabulation on the line, then a newline
is printed and the insertion point moves to the first
tabulation of the box.
If a new line is printed, [offset] is added to the current
indentation. *)
val set_tab : unit -> unit;;
val print_tab : unit -> unit;;
* { 6 Ellipsis }
val set_ellipsis_text : string -> unit;;
val get_ellipsis_text : unit -> string;;
* { 6 : tags Semantics Tags }
type tag = string;;
* { i Semantics tags } ( or simply { e tags } ) are used to decorate printed
entities for user 's defined purposes , e.g. setting font and giving size
indications for a display device , or marking delimitation of semantics
entities ( e.g. HTML or TeX elements or terminal escape sequences ) .
By default , those tags do not influence line breaking calculation :
the tag ` ` markers '' are not considered as part of the printing
material that drives line breaking ( in other words , the length of
those strings is considered as zero for line breaking ) .
Thus , tag handling is in some sense transparent to pretty - printing
and does not interfere with usual pretty - printing . Hence , a single
pretty printing routine can output both simple ` ` verbatim ''
material or richer decorated output depending on the treatment of
tags . By default , tags are not active , hence the output is not
decorated with tag information . Once [ set_tags ] is set to [ true ] ,
the pretty printer engine honours tags and decorates the output
accordingly .
When a tag has been opened ( or closed ) , it is both and successively
` ` printed '' and ` ` marked '' . Printing a tag means calling a
formatter specific function with the name of the tag as argument :
that ` ` tag printing '' function can then print any regular material
to the formatter ( so that this material is enqueued as usual in the
formatter queue for further line - breaking computation ) . Marking a
tag means to output an arbitrary string ( the ` ` tag marker '' ) ,
directly into the output device of the formatter . Hence , the
formatter specific ` ` tag marking '' function must return the tag
marker string associated to its tag argument . Being flushed
directly into the output device of the formatter , tag marker
strings are not considered as part of the printing material that
drives line breaking ( in other words , the length of the strings
corresponding to tag markers is considered as zero for line
breaking ) . In addition , advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines , and
precisely when the queue is flushed into the output device .
In the spirit of HTML tags , the default tag marking functions
output tags enclosed in " < " and " > " : hence , the opening marker of
tag [ t ] is [ " < t > " ] and the closing marker [ " < /t > " ] .
tag printing functions just do nothing .
Tag marking and tag printing functions are user definable and can
be set by calling [ set_formatter_tag_functions ] .
entities for user's defined purposes, e.g. setting font and giving size
indications for a display device, or marking delimitation of semantics
entities (e.g. HTML or TeX elements or terminal escape sequences).
By default, those tags do not influence line breaking calculation:
the tag ``markers'' are not considered as part of the printing
material that drives line breaking (in other words, the length of
those strings is considered as zero for line breaking).
Thus, tag handling is in some sense transparent to pretty-printing
and does not interfere with usual pretty-printing. Hence, a single
pretty printing routine can output both simple ``verbatim''
material or richer decorated output depending on the treatment of
tags. By default, tags are not active, hence the output is not
decorated with tag information. Once [set_tags] is set to [true],
the pretty printer engine honours tags and decorates the output
accordingly.
When a tag has been opened (or closed), it is both and successively
``printed'' and ``marked''. Printing a tag means calling a
formatter specific function with the name of the tag as argument:
that ``tag printing'' function can then print any regular material
to the formatter (so that this material is enqueued as usual in the
formatter queue for further line-breaking computation). Marking a
tag means to output an arbitrary string (the ``tag marker''),
directly into the output device of the formatter. Hence, the
formatter specific ``tag marking'' function must return the tag
marker string associated to its tag argument. Being flushed
directly into the output device of the formatter, tag marker
strings are not considered as part of the printing material that
drives line breaking (in other words, the length of the strings
corresponding to tag markers is considered as zero for line
breaking). In addition, advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines, and
precisely when the queue is flushed into the output device.
In the spirit of HTML tags, the default tag marking functions
output tags enclosed in "<" and ">": hence, the opening marker of
tag [t] is ["<t>"] and the closing marker ["</t>"].
Default tag printing functions just do nothing.
Tag marking and tag printing functions are user definable and can
be set by calling [set_formatter_tag_functions]. *)
val open_tag : tag -> unit;;
val close_tag : unit -> unit;;
val set_tags : bool -> unit;;
val set_print_tags : bool -> unit;;
val set_mark_tags : bool -> unit;;
val get_print_tags : unit -> bool;;
val get_mark_tags : unit -> bool;;
* { 6 Redirecting the standard formatter output }
val set_formatter_out_channel : Pervasives.out_channel -> unit;;
val set_formatter_output_functions :
(string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val get_formatter_output_functions :
unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
* { 6 : meaning Changing the meaning of standard formatter pretty printing }
val set_all_formatter_output_functions :
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) ->
spaces:(int -> unit) ->
unit
;;
* [ set_all_formatter_output_functions out flush outnewline outspace ]
redirects the pretty - printer output to the functions [ out ] and
[ flush ] as described in [ set_formatter_output_functions ] . In
addition , the pretty - printer function that outputs a newline is set
to the function [ outnewline ] and the function that outputs
indentation spaces is set to the function [ outspace ] .
This way , you can change the meaning of indentation ( which can be
something else than just printing space characters ) and the
meaning of new lines opening ( which can be connected to any other
action needed by the application at hand ) . The two functions
[ outspace ] and [ outnewline ] are normally connected to [ out ] and
[ flush ] : respective default values for [ outspace ] and [ outnewline ]
are [ out ( String.make n ' ' ) 0 n ] and [ out " \n " 0 1 ] .
redirects the pretty-printer output to the functions [out] and
[flush] as described in [set_formatter_output_functions]. In
addition, the pretty-printer function that outputs a newline is set
to the function [outnewline] and the function that outputs
indentation spaces is set to the function [outspace].
This way, you can change the meaning of indentation (which can be
something else than just printing space characters) and the
meaning of new lines opening (which can be connected to any other
action needed by the application at hand). The two functions
[outspace] and [outnewline] are normally connected to [out] and
[flush]: respective default values for [outspace] and [outnewline]
are [out (String.make n ' ') 0 n] and [out "\n" 0 1]. *)
val get_all_formatter_output_functions :
unit ->
(string -> int -> int -> unit) *
(unit -> unit) *
(unit -> unit) *
(int -> unit)
;;
* { 6 : tagsmeaning Changing the meaning of printing semantics tags }
type formatter_tag_functions = {
mark_open_tag : tag -> string;
mark_close_tag : tag -> string;
print_open_tag : tag -> unit;
print_close_tag : tag -> unit;
}
;;
val set_formatter_tag_functions :
formatter_tag_functions -> unit
;;
val get_formatter_tag_functions :
unit -> formatter_tag_functions
;;
* { 6 Multiple formatted output }
type formatter;;
val formatter_of_out_channel : out_channel -> formatter;;
val std_formatter : formatter;;
val err_formatter : formatter;;
val formatter_of_buffer : Buffer.t -> formatter;;
val stdbuf : Buffer.t;;
val str_formatter : formatter;;
val flush_str_formatter : unit -> string;;
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
;;
* { 6 Basic functions to use with formatters }
val pp_open_hbox : formatter -> unit -> unit;;
val pp_open_vbox : formatter -> int -> unit;;
val pp_open_hvbox : formatter -> int -> unit;;
val pp_open_hovbox : formatter -> int -> unit;;
val pp_open_box : formatter -> int -> unit;;
val pp_close_box : formatter -> unit -> unit;;
val pp_open_tag : formatter -> string -> unit;;
val pp_close_tag : formatter -> unit -> unit;;
val pp_print_string : formatter -> string -> unit;;
val pp_print_as : formatter -> int -> string -> unit;;
val pp_print_int : formatter -> int -> unit;;
val pp_print_float : formatter -> float -> unit;;
val pp_print_char : formatter -> char -> unit;;
val pp_print_bool : formatter -> bool -> unit;;
val pp_print_break : formatter -> int -> int -> unit;;
val pp_print_cut : formatter -> unit -> unit;;
val pp_print_space : formatter -> unit -> unit;;
val pp_force_newline : formatter -> unit -> unit;;
val pp_print_flush : formatter -> unit -> unit;;
val pp_print_newline : formatter -> unit -> unit;;
val pp_print_if_newline : formatter -> unit -> unit;;
val pp_open_tbox : formatter -> unit -> unit;;
val pp_close_tbox : formatter -> unit -> unit;;
val pp_print_tbreak : formatter -> int -> int -> unit;;
val pp_set_tab : formatter -> unit -> unit;;
val pp_print_tab : formatter -> unit -> unit;;
val pp_set_tags : formatter -> bool -> unit;;
val pp_set_print_tags : formatter -> bool -> unit;;
val pp_set_mark_tags : formatter -> bool -> unit;;
val pp_get_print_tags : formatter -> unit -> bool;;
val pp_get_mark_tags : formatter -> unit -> bool;;
val pp_set_margin : formatter -> int -> unit;;
val pp_get_margin : formatter -> unit -> int;;
val pp_set_max_indent : formatter -> int -> unit;;
val pp_get_max_indent : formatter -> unit -> int;;
val pp_set_max_boxes : formatter -> int -> unit;;
val pp_get_max_boxes : formatter -> unit -> int;;
val pp_over_max_boxes : formatter -> unit -> bool;;
val pp_set_ellipsis_text : formatter -> string -> unit;;
val pp_get_ellipsis_text : formatter -> unit -> string;;
val pp_set_formatter_out_channel : formatter -> Pervasives.out_channel -> unit;;
val pp_set_formatter_output_functions :
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
val pp_set_all_formatter_output_functions :
formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
;;
val pp_get_all_formatter_output_functions :
formatter -> unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
;;
val pp_set_formatter_tag_functions :
formatter -> formatter_tag_functions -> unit
;;
val pp_get_formatter_tag_functions :
formatter -> unit -> formatter_tag_functions
;;
* { 6 [ printf ] like functions for pretty - printing . }
val fprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ]
according to the format string [ fmt ] , and outputs the resulting string on
the formatter [ ff ] .
The format [ fmt ] is a character string which contains three types of
objects : plain characters and conversion specifications as specified in
the [ Printf ] module , and pretty - printing indications specific to the
[ Format ] module .
The pretty - printing indication characters are introduced by
a [ @ ] character , and their meanings are :
- [ @\ [ ] : open a pretty - printing box . The type and offset of the
box may be optionally specified with the following syntax :
the [ < ] character , followed by an optional box type indication ,
then an optional integer offset , and the closing [ > ] character .
Box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] ,
which stand respectively for an horizontal box , a vertical box ,
an ` ` horizontal - vertical '' box , or an ` ` horizontal or
vertical '' box ( [ b ] standing for an ` ` horizontal or
vertical '' box demonstrating indentation and [ hov ] standing
for a regular``horizontal or vertical '' box ) .
For instance , [ @\[<hov 2 > ] opens an ` ` horizontal or vertical ''
box with indentation 2 as obtained with [ open_hovbox 2 ] .
For more details about boxes , see the various box opening
functions [ open_*box ] .
- [ @\ ] ] : close the most recently opened pretty - printing box .
- [ @ , ] : output a good break as with [ print_cut ( ) ] .
- [ @ ] : output a space , as with [ print_space ( ) ] .
- [ @\n ] : force a newline , as with [ force_newline ( ) ] .
- [ @ ; ] : output a good break as with [ print_break ] . The
[ nspaces ] and [ offset ] parameters of the break may be
optionally specified with the following syntax :
the [ < ] character , followed by an integer [ nspaces ] value ,
then an integer [ offset ] , and a closing [ > ] character .
If no parameters are provided , the good break defaults to a
space .
- [ @ ? ] : flush the pretty printer as with [ print_flush ( ) ] .
This is equivalent to the conversion [ % ! ] .
- [ @. ] : flush the pretty printer and output a new line , as with
[ print_newline ( ) ] .
- [ @<n > ] : print the following item as if it were of length [ n ] .
Hence , [ printf " @<0>%s " arg ] prints [ arg ] as a zero length string .
If [ @<n > ] is not followed by a conversion specification ,
then the following character of the format is printed as if
it were of length [ n ] .
- [ @\ { ] : open a tag . The name of the tag may be optionally
specified with the following syntax :
the [ < ] character , followed by an optional string
specification , and the closing [ > ] character . The string
specification is any character string that does not contain the
closing character [ ' > ' ] . If omitted , the tag name defaults to the
empty string .
For more details about tags , see the functions [ open_tag ] and
[ close_tag ] .
- [ @\ } ] : close the most recently opened tag .
Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to
[ open_box ( ) ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ] .
It prints [ x = 1 ] within a pretty - printing box .
Note : the old [ @@ ] ` ` pretty - printing indication '' is now deprecated , since
it had no pretty - printing indication semantics . If you need to prevent
the pretty - printing indication interpretation of a [ @ ] character , simply
use the regular way to escape a character in format string : write [ % @ ] .
@since 3.12.2 .
according to the format string [fmt], and outputs the resulting string on
the formatter [ff].
The format [fmt] is a character string which contains three types of
objects: plain characters and conversion specifications as specified in
the [Printf] module, and pretty-printing indications specific to the
[Format] module.
The pretty-printing indication characters are introduced by
a [@] character, and their meanings are:
- [@\[]: open a pretty-printing box. The type and offset of the
box may be optionally specified with the following syntax:
the [<] character, followed by an optional box type indication,
then an optional integer offset, and the closing [>] character.
Box type is one of [h], [v], [hv], [b], or [hov],
which stand respectively for an horizontal box, a vertical box,
an ``horizontal-vertical'' box, or an ``horizontal or
vertical'' box ([b] standing for an ``horizontal or
vertical'' box demonstrating indentation and [hov] standing
for a regular``horizontal or vertical'' box).
For instance, [@\[<hov 2>] opens an ``horizontal or vertical''
box with indentation 2 as obtained with [open_hovbox 2].
For more details about boxes, see the various box opening
functions [open_*box].
- [@\]]: close the most recently opened pretty-printing box.
- [@,]: output a good break as with [print_cut ()].
- [@ ]: output a space, as with [print_space ()].
- [@\n]: force a newline, as with [force_newline ()].
- [@;]: output a good break as with [print_break]. The
[nspaces] and [offset] parameters of the break may be
optionally specified with the following syntax:
the [<] character, followed by an integer [nspaces] value,
then an integer [offset], and a closing [>] character.
If no parameters are provided, the good break defaults to a
space.
- [@?]: flush the pretty printer as with [print_flush ()].
This is equivalent to the conversion [%!].
- [@.]: flush the pretty printer and output a new line, as with
[print_newline ()].
- [@<n>]: print the following item as if it were of length [n].
Hence, [printf "@<0>%s" arg] prints [arg] as a zero length string.
If [@<n>] is not followed by a conversion specification,
then the following character of the format is printed as if
it were of length [n].
- [@\{]: open a tag. The name of the tag may be optionally
specified with the following syntax:
the [<] character, followed by an optional string
specification, and the closing [>] character. The string
specification is any character string that does not contain the
closing character ['>']. If omitted, the tag name defaults to the
empty string.
For more details about tags, see the functions [open_tag] and
[close_tag].
- [@\}]: close the most recently opened tag.
Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to
[open_box (); print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()].
It prints [x = 1] within a pretty-printing box.
Note: the old [@@] ``pretty-printing indication'' is now deprecated, since
it had no pretty-printing indication semantics. If you need to prevent
the pretty-printing indication interpretation of a [@] character, simply
use the regular way to escape a character in format string: write [%@].
@since 3.12.2.
*)
val printf : ('a, formatter, unit) format -> 'a;;
val eprintf : ('a, formatter, unit) format -> 'a;;
val sprintf : ('a, unit, string) format -> 'a;;
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* Same as [ fprintf ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.10.0
Useful to ignore some material when conditionally printing.
@since 3.10.0
*)
val kfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ fprintf ] above , but instead of returning immediately ,
passes the formatter to its first argument at the end of printing .
passes the formatter to its first argument at the end of printing. *)
val ikfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.12.0
Useful to ignore some material when conditionally printing.
@since 3.12.0
*)
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
* Same as [ sprintf ] above , but instead of returning the string ,
passes it to the first argument .
passes it to the first argument. *)
* { 6 Deprecated }
val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a;;
* A deprecated and error prone function . Do not use it .
If you need to print to some buffer [ b ] , you must first define a
formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then
use regular calls to [ Format.fprintf ] on formatter [ to_b ] .
If you need to print to some buffer [b], you must first define a
formatter writing to [b], using [let to_b = formatter_of_buffer b]; then
use regular calls to [Format.fprintf] on formatter [to_b]. *)
val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
|
eb638ff01173e3762de60fabd2d4f96fa2d92ad477a980ea232f063d53f6f1cf | oliyh/slacky | memecaptain.clj | (ns slacky.memecaptain
(:require [clj-http.client :as http]
[clojure.tools.logging :as log]
[clojure.java.shell :as sh]
[clojure.java.io :as io])
(:import [java.util UUID]
[java.io File]))
(defn init
"Copies the font to disk so it can be used and creates the meme directories"
[]
(io/copy (io/input-stream (io/resource "memecaptain/impact.ttf"))
(io/file "impact.ttf"))
(.mkdir (io/file "./memes"))
(.mkdir (io/file "./templates")))
(defn create-direct [image-url text-upper text-lower]
(let [extension (second (re-find #".*\.(\w{3,4})($|\?)" image-url))
filename (str (UUID/randomUUID) (when extension (str "." extension)))
output-file (io/file "memes/" filename)
input-file (io/file "templates/" filename)]
(io/make-parents input-file)
(io/make-parents output-file)
(log/info "Downloading" image-url "to" (.getPath input-file))
(try
(let [response (http/get image-url {:as :byte-array})]
(if-not (http/unexceptional-status? (:status response))
(throw (ex-info (str "Could not download" image-url)
response))
(do (io/copy (io/input-stream (:body response)) input-file)
(log/info "Generating meme" (.getPath output-file))
(sh/with-sh-dir (io/file ".")
(let [result (sh/sh "./bin/memecaptain" (.getAbsolutePath input-file) "-o" (.getAbsolutePath output-file) "-f" "impact.ttf" "-t" text-upper "-b" text-lower)]
(if (zero? (:exit result))
(.getPath output-file)
(throw (ex-info "Failed to generate meme"
(merge result
{:image-url image-url
:input-file (.getPath input-file)
:output-file (.getPath output-file)})))))))))
(finally
(.delete input-file)))))
| null | https://raw.githubusercontent.com/oliyh/slacky/909110e0555b7e443c3cf014c7c34b00b31c1a18/src/clj/slacky/memecaptain.clj | clojure | (ns slacky.memecaptain
(:require [clj-http.client :as http]
[clojure.tools.logging :as log]
[clojure.java.shell :as sh]
[clojure.java.io :as io])
(:import [java.util UUID]
[java.io File]))
(defn init
"Copies the font to disk so it can be used and creates the meme directories"
[]
(io/copy (io/input-stream (io/resource "memecaptain/impact.ttf"))
(io/file "impact.ttf"))
(.mkdir (io/file "./memes"))
(.mkdir (io/file "./templates")))
(defn create-direct [image-url text-upper text-lower]
(let [extension (second (re-find #".*\.(\w{3,4})($|\?)" image-url))
filename (str (UUID/randomUUID) (when extension (str "." extension)))
output-file (io/file "memes/" filename)
input-file (io/file "templates/" filename)]
(io/make-parents input-file)
(io/make-parents output-file)
(log/info "Downloading" image-url "to" (.getPath input-file))
(try
(let [response (http/get image-url {:as :byte-array})]
(if-not (http/unexceptional-status? (:status response))
(throw (ex-info (str "Could not download" image-url)
response))
(do (io/copy (io/input-stream (:body response)) input-file)
(log/info "Generating meme" (.getPath output-file))
(sh/with-sh-dir (io/file ".")
(let [result (sh/sh "./bin/memecaptain" (.getAbsolutePath input-file) "-o" (.getAbsolutePath output-file) "-f" "impact.ttf" "-t" text-upper "-b" text-lower)]
(if (zero? (:exit result))
(.getPath output-file)
(throw (ex-info "Failed to generate meme"
(merge result
{:image-url image-url
:input-file (.getPath input-file)
:output-file (.getPath output-file)})))))))))
(finally
(.delete input-file)))))
| |
bff87712ed10170dc40373059834d04e2eccab60778c2a081eed73067074b62d | mathematical-systems/clml | blas.lisp | (in-package :mkl.blas)
blas1
;;; asum
(defblas asum (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int))
(defffun scasum :float
(n blas-int)
(x (:array complex-float *))
(incx blas-int))
(export 'scasum)
(defffun dzasum :double
(n blas-int)
(x (:array complex-double *))
(incx blas-int))
(export 'dzasum)
;;; axpy
(defblas axpy (:single :double :complex-single :complex-double) :void
(n blas-int)
(a :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; copy
(defblas copy (:single :double :complex-single :complex-double) :void
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; dot
(defblas dot (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
sdsdot , dsdot
(defffun sdsdot :float
(n blas-int)
(sb :float)
(sx (:array :float *))
(incx blas-int)
(sy (:array :float *))
(incy blas-int))
(export 'sdsdot)
(defffun dsdot :double
(n blas-int)
(sx (:array :float *))
(incx blas-int)
(sy (:array :float *))
(incy blas-int))
(export 'dsdot)
;;; dotc
(defblas dotc (:complex-single :complex-double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
dotu
(defblas dotu (:complex-single :complex-double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
;;; nrm2
(defblas nrm2 (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int))
(defffun scnrm2 :float
(n blas-int)
(x (:array complex-float *))
(incx blas-int))
(export 'scnrm2)
(defffun dznrm2 :double
(n blas-int)
(x (:array complex-double *))
(incx blas-int))
(export 'dznrm2)
;;; rot
(defblas rot (:single :double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int)
(c :precision)
(s :precision))
FIXME : cause SBCL to crash
(defffun csrot :void
(n blas-int)
(x (:array complex-float *) :in-out)
(incx blas-int)
(y (:array complex-float *) :in-out)
(incy blas-int)
(c :float)
(s :float))
(export 'csrot)
FIXME : cause SBCL to crash
(defffun zdrot :void
(n blas-int)
(x (:array complex-double *) :in-out)
(incx blas-int)
(y (:array complex-double *) :in-out)
(incy blas-int)
(c :double)
(s :double))
(export 'zdrot)
;;; rotg
(defblas rotg (:single :double :complex-single :complex-double) :void
(a :precision :in-out)
(b :precision :in-out)
(c :precision :out)
(d :precision :out))
;;; rotm
(defblas rotm (:single :double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int)
(param (:array :precision 5)))
;;; rotmg
(defblas rotmg (:single :double) :void
(d1 :precision :in-out)
(d2 :precision :in-out)
(x1 :precision :in-out)
(y1 :precision)
(param (:array :precision 5) :out))
;;; scal
(defblas scal (:single :double :complex-single :complex-double) :void
(n blas-int)
(a :precision)
(x (:array :precision *) :in-out)
(incx blas-int))
;;; swap
(defblas swap (:single :double :complex-single :complex-double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; i?amax
;;; it's generated and modified from
( (: single : double : complex - single : complex - double )
;; :precision
;; (n blas-int)
;; (x (:array :precision *))
( ) )
(PROGN
(DEFFFUN iSAMAX :FLOAT
(N BLAS-INT)
(X (:ARRAY :FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iSAMAX)
(DEFFFUN iDAMAX :DOUBLE
(N BLAS-INT)
(X (:ARRAY :DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iDAMAX)
(DEFFFUN iCAMAX COMPLEX-FLOAT
(N BLAS-INT)
(X (:ARRAY COMPLEX-FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iCAMAX)
(DEFFFUN iZAMAX COMPLEX-DOUBLE
(N BLAS-INT)
(X (:ARRAY COMPLEX-DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iZAMAX))
;;; i?amin
;;; it's generated and modified from
( defblas amin (: single : double : complex - single : complex - double )
;; :precision
;; (n blas-int)
;; (x (:array :precision *))
( ) )
(PROGN
(DEFFFUN iSAMIN :FLOAT
(N BLAS-INT)
(X (:ARRAY :FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iSAMIN)
(DEFFFUN iDAMIN :DOUBLE
(N BLAS-INT)
(X (:ARRAY :DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iDAMIN)
(DEFFFUN iCAMIN COMPLEX-FLOAT
(N BLAS-INT)
(X (:ARRAY COMPLEX-FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iCAMIN)
(DEFFFUN iZAMIN COMPLEX-DOUBLE
(N BLAS-INT)
(X (:ARRAY COMPLEX-DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iZAMIN))
;;; cabs1
#+nil
(defblas cabs1 (:double) :double
(z :complex-double))
;;;; blas2
;;; gbmv
(defblas gbmv (:single :double :complex-single :complex-double) :void
(trans :string)
(m blas-int)
(n blas-int)
(kl blas-int)
(ku blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x :precision)
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; gemv
(defblas gemv (:single :double :complex-single :complex-double) :void
(trans :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; ger
(defblas ger (:single :double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
;;; gerc
(defblas gerc (:complex-single :complex-double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
;;; geru
(defblas geru (:complex-single :complex-double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
;;; hbmv
(defblas hbmv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; hemv
(defblas hemv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; her
(defblas her (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(x (:array :precision *))
(incx blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
;;; her2
(defblas her2 (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
;;; hpmv
(defblas hpmv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(ap (:array :precision *))
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; hpr
(defblas hpr (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(x (:array :precision *))
(incx blas-int)
(ap (:array :precision *) :in-out))
;;; hpr2
(defblas hpr2 (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(ap (:array :precision *) :in-out))
sbmv
(defblas sbmv (:single :double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; spmv
(defblas spmv (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(ap (:array :precision *))
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; spr
(defblas spr (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(ap (:array :precision *) :in-out))
;;; spr2
(defblas spr2 (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(ap (:array :precision *) :in-out))
;;; symv
(defblas symv (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
;;; syr
(defblas syr (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
syr2
(defblas syr2 (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision *) :in-out)
(lda blas-int))
;;; tbmv
(defblas tbmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(k blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
;;; tbsv
(defblas tbsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(k blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
;;; tpmv
(defblas tpmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(ap (:array :precision *))
(x (:array :precision *) :in-out)
(incx blas-int))
;;; tpsv
(defblas tpsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(ap (:array :precision *))
(x (:array :precision *) :in-out)
(incx blas-int))
;;; trmv
(defblas trmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
;;; trsv
(defblas trsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
;;;; blas 3
;;; gemm
(defblas gemm (:single :double :complex-single :complex-double) :void
(transa :string)
(transb :string)
(m blas-int)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; hemm
(defblas hemm (:complex-single :complex-double) :void
(side :string)
(uplo :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; herk
(defblas herk (:complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(a (:array :precision * *))
(lda blas-int)
(beta (case :precision
(:complex-single :single)
(:complex-double :double)))
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; her2k
(defblas her2k (:complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(beta :precision)
(b (:array :precision * *))
(ldb blas-int)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; symm
(defblas symm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; syrk
(defblas syrk (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; syrk2
(defblas syr2k (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
;;; trmm
(defblas trmm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(transa :string)
(diag :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *) :in-out)
(ldb blas-int))
;;; trsm
(defblas trsm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(transa :string)
(diag :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *) :in-out)
(ldb blas-int))
| null | https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/addons/blas-lapack-ffi/src/blas.lisp | lisp | asum
axpy
copy
dot
dotc
nrm2
rot
rotg
rotm
rotmg
scal
swap
i?amax
it's generated and modified from
:precision
(n blas-int)
(x (:array :precision *))
i?amin
it's generated and modified from
:precision
(n blas-int)
(x (:array :precision *))
cabs1
blas2
gbmv
gemv
ger
gerc
geru
hbmv
hemv
her
her2
hpmv
hpr
hpr2
spmv
spr
spr2
symv
syr
tbmv
tbsv
tpmv
tpsv
trmv
trsv
blas 3
gemm
hemm
herk
her2k
symm
syrk
syrk2
trmm
trsm | (in-package :mkl.blas)
blas1
(defblas asum (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int))
(defffun scasum :float
(n blas-int)
(x (:array complex-float *))
(incx blas-int))
(export 'scasum)
(defffun dzasum :double
(n blas-int)
(x (:array complex-double *))
(incx blas-int))
(export 'dzasum)
(defblas axpy (:single :double :complex-single :complex-double) :void
(n blas-int)
(a :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas copy (:single :double :complex-single :complex-double) :void
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas dot (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
sdsdot , dsdot
(defffun sdsdot :float
(n blas-int)
(sb :float)
(sx (:array :float *))
(incx blas-int)
(sy (:array :float *))
(incy blas-int))
(export 'sdsdot)
(defffun dsdot :double
(n blas-int)
(sx (:array :float *))
(incx blas-int)
(sy (:array :float *))
(incy blas-int))
(export 'dsdot)
(defblas dotc (:complex-single :complex-double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
dotu
(defblas dotu (:complex-single :complex-double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int))
(defblas nrm2 (:single :double) :precision
(n blas-int)
(x (:array :precision *))
(incx blas-int))
(defffun scnrm2 :float
(n blas-int)
(x (:array complex-float *))
(incx blas-int))
(export 'scnrm2)
(defffun dznrm2 :double
(n blas-int)
(x (:array complex-double *))
(incx blas-int))
(export 'dznrm2)
(defblas rot (:single :double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int)
(c :precision)
(s :precision))
FIXME : cause SBCL to crash
(defffun csrot :void
(n blas-int)
(x (:array complex-float *) :in-out)
(incx blas-int)
(y (:array complex-float *) :in-out)
(incy blas-int)
(c :float)
(s :float))
(export 'csrot)
FIXME : cause SBCL to crash
(defffun zdrot :void
(n blas-int)
(x (:array complex-double *) :in-out)
(incx blas-int)
(y (:array complex-double *) :in-out)
(incy blas-int)
(c :double)
(s :double))
(export 'zdrot)
(defblas rotg (:single :double :complex-single :complex-double) :void
(a :precision :in-out)
(b :precision :in-out)
(c :precision :out)
(d :precision :out))
(defblas rotm (:single :double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int)
(param (:array :precision 5)))
(defblas rotmg (:single :double) :void
(d1 :precision :in-out)
(d2 :precision :in-out)
(x1 :precision :in-out)
(y1 :precision)
(param (:array :precision 5) :out))
(defblas scal (:single :double :complex-single :complex-double) :void
(n blas-int)
(a :precision)
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas swap (:single :double :complex-single :complex-double) :void
(n blas-int)
(x (:array :precision *) :in-out)
(incx blas-int)
(y (:array :precision *) :in-out)
(incy blas-int))
( (: single : double : complex - single : complex - double )
( ) )
(PROGN
(DEFFFUN iSAMAX :FLOAT
(N BLAS-INT)
(X (:ARRAY :FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iSAMAX)
(DEFFFUN iDAMAX :DOUBLE
(N BLAS-INT)
(X (:ARRAY :DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iDAMAX)
(DEFFFUN iCAMAX COMPLEX-FLOAT
(N BLAS-INT)
(X (:ARRAY COMPLEX-FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iCAMAX)
(DEFFFUN iZAMAX COMPLEX-DOUBLE
(N BLAS-INT)
(X (:ARRAY COMPLEX-DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iZAMAX))
( defblas amin (: single : double : complex - single : complex - double )
( ) )
(PROGN
(DEFFFUN iSAMIN :FLOAT
(N BLAS-INT)
(X (:ARRAY :FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iSAMIN)
(DEFFFUN iDAMIN :DOUBLE
(N BLAS-INT)
(X (:ARRAY :DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iDAMIN)
(DEFFFUN iCAMIN COMPLEX-FLOAT
(N BLAS-INT)
(X (:ARRAY COMPLEX-FLOAT *))
(INCX BLAS-INT))
(EXPORT 'iCAMIN)
(DEFFFUN iZAMIN COMPLEX-DOUBLE
(N BLAS-INT)
(X (:ARRAY COMPLEX-DOUBLE *))
(INCX BLAS-INT))
(EXPORT 'iZAMIN))
#+nil
(defblas cabs1 (:double) :double
(z :complex-double))
(defblas gbmv (:single :double :complex-single :complex-double) :void
(trans :string)
(m blas-int)
(n blas-int)
(kl blas-int)
(ku blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x :precision)
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas gemv (:single :double :complex-single :complex-double) :void
(trans :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas ger (:single :double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
(defblas gerc (:complex-single :complex-double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
(defblas geru (:complex-single :complex-double) :void
(m blas-int)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
(defblas hbmv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas hemv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas her (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(x (:array :precision *))
(incx blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
(defblas her2 (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
(defblas hpmv (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(ap (:array :precision *))
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas hpr (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(x (:array :precision *))
(incx blas-int)
(ap (:array :precision *) :in-out))
(defblas hpr2 (:complex-single :complex-double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(ap (:array :precision *) :in-out))
sbmv
(defblas sbmv (:single :double) :void
(uplo :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas spmv (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(ap (:array :precision *))
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas spr (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(ap (:array :precision *) :in-out))
(defblas spr2 (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(ap (:array :precision *) :in-out))
(defblas symv (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *))
(incx blas-int)
(beta :precision)
(y (:array :precision *) :in-out)
(incy blas-int))
(defblas syr (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(a (:array :precision * *) :in-out)
(lda blas-int))
syr2
(defblas syr2 (:single :double) :void
(uplo :string)
(n blas-int)
(alpha :precision)
(x (:array :precision *))
(incx blas-int)
(y (:array :precision *))
(incy blas-int)
(a (:array :precision *) :in-out)
(lda blas-int))
(defblas tbmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(k blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas tbsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(k blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas tpmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(ap (:array :precision *))
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas tpsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(ap (:array :precision *))
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas trmv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas trsv (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(diag :string)
(n blas-int)
(a (:array :precision * *))
(lda blas-int)
(x (:array :precision *) :in-out)
(incx blas-int))
(defblas gemm (:single :double :complex-single :complex-double) :void
(transa :string)
(transb :string)
(m blas-int)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas hemm (:complex-single :complex-double) :void
(side :string)
(uplo :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas herk (:complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha (case :precision
(:complex-single :single)
(:complex-double :double)))
(a (:array :precision * *))
(lda blas-int)
(beta (case :precision
(:complex-single :single)
(:complex-double :double)))
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas her2k (:complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(beta :precision)
(b (:array :precision * *))
(ldb blas-int)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas symm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas syrk (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas syr2k (:single :double :complex-single :complex-double) :void
(uplo :string)
(trans :string)
(n blas-int)
(k blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *))
(ldb blas-int)
(beta :precision)
(c (:array :precision * *) :in-out)
(ldc blas-int))
(defblas trmm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(transa :string)
(diag :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *) :in-out)
(ldb blas-int))
(defblas trsm (:single :double :complex-single :complex-double) :void
(side :string)
(uplo :string)
(transa :string)
(diag :string)
(m blas-int)
(n blas-int)
(alpha :precision)
(a (:array :precision * *))
(lda blas-int)
(b (:array :precision * *) :in-out)
(ldb blas-int))
|
ba3e8b7aa3bce80e447a39c60d852428f03b4acca694a7a0653085bca0061d78 | exercism/babashka | kindergarten_garden_test.clj | (ns kindergarten-garden-test
(:require [clojure.test :refer [deftest is]]
kindergarten-garden))
(deftest garden-test
(is (= [:radishes :clover :grass :grass]
(:alice (kindergarten-garden/garden "RC\nGG"))))
(is (= [:violets :clover :radishes :clover]
(:alice (kindergarten-garden/garden "VC\nRC")))))
(deftest small-garden-test
(let [small-garden (kindergarten-garden/garden "VVCG\nVVRC")]
(is (= [:clover :grass :radishes :clover] (:bob small-garden)))))
(deftest medium-garden-test
(let [medium-garden (kindergarten-garden/garden "VVCCGG\nVVCCGG")]
(is (= [:clover :clover :clover :clover] (:bob medium-garden)))
(is (= [:grass :grass :grass :grass] (:charlie medium-garden)))))
(deftest full-garden-test
(let [string "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"
full-garden (kindergarten-garden/garden string)]
(is (= [:violets :radishes :violets :radishes] (:alice full-garden)))
(is (= [:clover :grass :clover :clover] (:bob full-garden)))
(is (= [:violets :violets :clover :grass] (:charlie full-garden)))
(is (= [:radishes :violets :clover :radishes] (:david full-garden)))
(is (= [:clover :grass :radishes :grass] (:eve full-garden)))
(is (= [:grass :clover :violets :clover] (:fred full-garden)))
(is (= [:clover :grass :grass :clover] (:ginny full-garden)))
(is (= [:violets :radishes :radishes :violets] (:harriet full-garden)))
(is (= [:grass :clover :violets :clover] (:ileana full-garden)))
(is (= [:violets :clover :violets :grass] (:joseph full-garden)))
(is (= [:grass :clover :clover :grass] (:kincaid full-garden)))
(is (= [:grass :violets :clover :violets] (:larry full-garden)))))
(deftest surprise-garden-test
(let [string "VCRRGVRG\nRVGCCGCV"
students ["Samantha" "Patricia" "Xander" "Roger"]
surprise-garden (kindergarten-garden/garden string students)]
(is (= [:violets :clover :radishes :violets]
(:patricia surprise-garden)))
(is (= [:radishes :radishes :grass :clover]
(:roger surprise-garden)))
(is (= [:grass :violets :clover :grass]
(:samantha surprise-garden)))
(is (= [:radishes :grass :clover :violets]
(:xander surprise-garden)))))
| null | https://raw.githubusercontent.com/exercism/babashka/7375f1938ff95b242320313eaeedb8eca31a1b5b/exercises/practice/kindergarten-garden/test/kindergarten_garden_test.clj | clojure | (ns kindergarten-garden-test
(:require [clojure.test :refer [deftest is]]
kindergarten-garden))
(deftest garden-test
(is (= [:radishes :clover :grass :grass]
(:alice (kindergarten-garden/garden "RC\nGG"))))
(is (= [:violets :clover :radishes :clover]
(:alice (kindergarten-garden/garden "VC\nRC")))))
(deftest small-garden-test
(let [small-garden (kindergarten-garden/garden "VVCG\nVVRC")]
(is (= [:clover :grass :radishes :clover] (:bob small-garden)))))
(deftest medium-garden-test
(let [medium-garden (kindergarten-garden/garden "VVCCGG\nVVCCGG")]
(is (= [:clover :clover :clover :clover] (:bob medium-garden)))
(is (= [:grass :grass :grass :grass] (:charlie medium-garden)))))
(deftest full-garden-test
(let [string "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"
full-garden (kindergarten-garden/garden string)]
(is (= [:violets :radishes :violets :radishes] (:alice full-garden)))
(is (= [:clover :grass :clover :clover] (:bob full-garden)))
(is (= [:violets :violets :clover :grass] (:charlie full-garden)))
(is (= [:radishes :violets :clover :radishes] (:david full-garden)))
(is (= [:clover :grass :radishes :grass] (:eve full-garden)))
(is (= [:grass :clover :violets :clover] (:fred full-garden)))
(is (= [:clover :grass :grass :clover] (:ginny full-garden)))
(is (= [:violets :radishes :radishes :violets] (:harriet full-garden)))
(is (= [:grass :clover :violets :clover] (:ileana full-garden)))
(is (= [:violets :clover :violets :grass] (:joseph full-garden)))
(is (= [:grass :clover :clover :grass] (:kincaid full-garden)))
(is (= [:grass :violets :clover :violets] (:larry full-garden)))))
(deftest surprise-garden-test
(let [string "VCRRGVRG\nRVGCCGCV"
students ["Samantha" "Patricia" "Xander" "Roger"]
surprise-garden (kindergarten-garden/garden string students)]
(is (= [:violets :clover :radishes :violets]
(:patricia surprise-garden)))
(is (= [:radishes :radishes :grass :clover]
(:roger surprise-garden)))
(is (= [:grass :violets :clover :grass]
(:samantha surprise-garden)))
(is (= [:radishes :grass :clover :violets]
(:xander surprise-garden)))))
| |
d39652b739bfc3855f1a4d9340485c7d4baf8d6b1fa890236846427d1298f100 | cl-axon/shop2 | pfile11.lisp | (in-package :shop2-user)
(defproblem pfile11 DEPOT
(
;;;
;;; facts
;;;
(DEPOT DEPOT0)
(DEPOT DEPOT1)
(DEPOT DEPOT2)
(DISTRIBUTOR DISTRIBUTOR0)
(DISTRIBUTOR DISTRIBUTOR1)
(DISTRIBUTOR DISTRIBUTOR2)
(TRUCK TRUCK0)
(TRUCK TRUCK1)
(TRUCK TRUCK2)
(TRUCK TRUCK3)
(PALLET PALLET0)
(PALLET PALLET1)
(PALLET PALLET2)
(PALLET PALLET3)
(PALLET PALLET4)
(PALLET PALLET5)
(CRATE CRATE0)
(CRATE CRATE1)
(CRATE CRATE2)
(CRATE CRATE3)
(CRATE CRATE4)
(CRATE CRATE5)
(CRATE CRATE6)
(CRATE CRATE7)
(CRATE CRATE8)
(CRATE CRATE9)
(CRATE CRATE10)
(CRATE CRATE11)
(CRATE CRATE12)
(CRATE CRATE13)
(CRATE CRATE14)
(CRATE CRATE15)
(CRATE CRATE16)
(CRATE CRATE17)
(CRATE CRATE18)
(CRATE CRATE19)
(CRATE CRATE20)
(CRATE CRATE21)
(CRATE CRATE22)
(CRATE CRATE23)
(CRATE CRATE24)
(CRATE CRATE25)
(CRATE CRATE26)
(CRATE CRATE27)
(CRATE CRATE28)
(CRATE CRATE29)
(CRATE CRATE30)
(CRATE CRATE31)
(CRATE CRATE32)
(CRATE CRATE33)
(CRATE CRATE34)
(CRATE CRATE35)
(CRATE CRATE36)
(CRATE CRATE37)
(CRATE CRATE38)
(CRATE CRATE39)
(CRATE CRATE40)
(CRATE CRATE41)
(CRATE CRATE42)
(CRATE CRATE43)
(CRATE CRATE44)
(CRATE CRATE45)
(CRATE CRATE46)
(CRATE CRATE47)
(CRATE CRATE48)
(CRATE CRATE49)
(CRATE CRATE50)
(CRATE CRATE51)
(CRATE CRATE52)
(CRATE CRATE53)
(CRATE CRATE54)
(CRATE CRATE55)
(CRATE CRATE56)
(CRATE CRATE57)
(CRATE CRATE58)
(CRATE CRATE59)
(HOIST HOIST0)
(HOIST HOIST1)
(HOIST HOIST2)
(HOIST HOIST3)
(HOIST HOIST4)
(HOIST HOIST5)
;;;
;;; initial states
;;;
(AT PALLET0 DEPOT0)
(CLEAR CRATE59)
(AT PALLET1 DEPOT1)
(CLEAR CRATE35)
(AT PALLET2 DEPOT2)
(CLEAR CRATE55)
(AT PALLET3 DISTRIBUTOR0)
(CLEAR CRATE52)
(AT PALLET4 DISTRIBUTOR1)
(CLEAR CRATE57)
(AT PALLET5 DISTRIBUTOR2)
(CLEAR CRATE58)
(AT TRUCK0 DEPOT2)
(AT TRUCK1 DISTRIBUTOR0)
(AT TRUCK2 DEPOT1)
(AT TRUCK3 DEPOT1)
(AT HOIST0 DEPOT0)
(AVAILABLE HOIST0)
(AT HOIST1 DEPOT1)
(AVAILABLE HOIST1)
(AT HOIST2 DEPOT2)
(AVAILABLE HOIST2)
(AT HOIST3 DISTRIBUTOR0)
(AVAILABLE HOIST3)
(AT HOIST4 DISTRIBUTOR1)
(AVAILABLE HOIST4)
(AT HOIST5 DISTRIBUTOR2)
(AVAILABLE HOIST5)
(AT CRATE0 DEPOT1)
(ON CRATE0 PALLET1)
(AT CRATE1 DEPOT2)
(ON CRATE1 PALLET2)
(AT CRATE2 DEPOT2)
(ON CRATE2 CRATE1)
(AT CRATE3 DISTRIBUTOR2)
(ON CRATE3 PALLET5)
(AT CRATE4 DISTRIBUTOR2)
(ON CRATE4 CRATE3)
(AT CRATE5 DISTRIBUTOR2)
(ON CRATE5 CRATE4)
(AT CRATE6 DEPOT2)
(ON CRATE6 CRATE2)
(AT CRATE7 DEPOT2)
(ON CRATE7 CRATE6)
(AT CRATE8 DEPOT1)
(ON CRATE8 CRATE0)
(AT CRATE9 DEPOT2)
(ON CRATE9 CRATE7)
(AT CRATE10 DEPOT2)
(ON CRATE10 CRATE9)
(AT CRATE11 DISTRIBUTOR1)
(ON CRATE11 PALLET4)
(AT CRATE12 DISTRIBUTOR0)
(ON CRATE12 PALLET3)
(AT CRATE13 DISTRIBUTOR2)
(ON CRATE13 CRATE5)
(AT CRATE14 DISTRIBUTOR1)
(ON CRATE14 CRATE11)
(AT CRATE15 DEPOT2)
(ON CRATE15 CRATE10)
(AT CRATE16 DISTRIBUTOR2)
(ON CRATE16 CRATE13)
(AT CRATE17 DISTRIBUTOR0)
(ON CRATE17 CRATE12)
(AT CRATE18 DEPOT1)
(ON CRATE18 CRATE8)
(AT CRATE19 DEPOT0)
(ON CRATE19 PALLET0)
(AT CRATE20 DISTRIBUTOR1)
(ON CRATE20 CRATE14)
(AT CRATE21 DEPOT0)
(ON CRATE21 CRATE19)
(AT CRATE22 DISTRIBUTOR0)
(ON CRATE22 CRATE17)
(AT CRATE23 DISTRIBUTOR1)
(ON CRATE23 CRATE20)
(AT CRATE24 DEPOT2)
(ON CRATE24 CRATE15)
(AT CRATE25 DEPOT0)
(ON CRATE25 CRATE21)
(AT CRATE26 DEPOT2)
(ON CRATE26 CRATE24)
(AT CRATE27 DISTRIBUTOR0)
(ON CRATE27 CRATE22)
(AT CRATE28 DISTRIBUTOR1)
(ON CRATE28 CRATE23)
(AT CRATE29 DISTRIBUTOR1)
(ON CRATE29 CRATE28)
(AT CRATE30 DISTRIBUTOR1)
(ON CRATE30 CRATE29)
(AT CRATE31 DEPOT1)
(ON CRATE31 CRATE18)
(AT CRATE32 DEPOT0)
(ON CRATE32 CRATE25)
(AT CRATE33 DEPOT0)
(ON CRATE33 CRATE32)
(AT CRATE34 DISTRIBUTOR0)
(ON CRATE34 CRATE27)
(AT CRATE35 DEPOT1)
(ON CRATE35 CRATE31)
(AT CRATE36 DEPOT0)
(ON CRATE36 CRATE33)
(AT CRATE37 DISTRIBUTOR0)
(ON CRATE37 CRATE34)
(AT CRATE38 DISTRIBUTOR1)
(ON CRATE38 CRATE30)
(AT CRATE39 DISTRIBUTOR0)
(ON CRATE39 CRATE37)
(AT CRATE40 DISTRIBUTOR0)
(ON CRATE40 CRATE39)
(AT CRATE41 DISTRIBUTOR2)
(ON CRATE41 CRATE16)
(AT CRATE42 DEPOT2)
(ON CRATE42 CRATE26)
(AT CRATE43 DISTRIBUTOR2)
(ON CRATE43 CRATE41)
(AT CRATE44 DEPOT0)
(ON CRATE44 CRATE36)
(AT CRATE45 DEPOT2)
(ON CRATE45 CRATE42)
(AT CRATE46 DISTRIBUTOR1)
(ON CRATE46 CRATE38)
(AT CRATE47 DISTRIBUTOR0)
(ON CRATE47 CRATE40)
(AT CRATE48 DISTRIBUTOR0)
(ON CRATE48 CRATE47)
(AT CRATE49 DISTRIBUTOR2)
(ON CRATE49 CRATE43)
(AT CRATE50 DISTRIBUTOR0)
(ON CRATE50 CRATE48)
(AT CRATE51 DEPOT2)
(ON CRATE51 CRATE45)
(AT CRATE52 DISTRIBUTOR0)
(ON CRATE52 CRATE50)
(AT CRATE53 DEPOT2)
(ON CRATE53 CRATE51)
(AT CRATE54 DEPOT2)
(ON CRATE54 CRATE53)
(AT CRATE55 DEPOT2)
(ON CRATE55 CRATE54)
(AT CRATE56 DISTRIBUTOR1)
(ON CRATE56 CRATE46)
(AT CRATE57 DISTRIBUTOR1)
(ON CRATE57 CRATE56)
(AT CRATE58 DISTRIBUTOR2)
(ON CRATE58 CRATE49)
(AT CRATE59 DEPOT0)
(ON CRATE59 CRATE44)
)
;;;
;;; goals
;;;
((achieve-goals
((ON CRATE0 CRATE47) (ON CRATE2 CRATE58) (ON CRATE3 CRATE9)
(ON CRATE5 CRATE35) (ON CRATE6 CRATE18) (ON CRATE7 CRATE24)
(ON CRATE8 CRATE53) (ON CRATE9 CRATE51) (ON CRATE10 CRATE15)
(ON CRATE11 CRATE41) (ON CRATE12 CRATE54) (ON CRATE13 CRATE29)
(ON CRATE14 CRATE56) (ON CRATE15 CRATE27) (ON CRATE18 CRATE34)
(ON CRATE19 CRATE32) (ON CRATE20 CRATE8) (ON CRATE21 CRATE0)
(ON CRATE22 CRATE7) (ON CRATE23 CRATE3) (ON CRATE24 CRATE46)
(ON CRATE25 PALLET3) (ON CRATE26 CRATE38) (ON CRATE27 CRATE2)
(ON CRATE29 CRATE42) (ON CRATE30 CRATE5) (ON CRATE31 CRATE25)
(ON CRATE32 PALLET4) (ON CRATE34 CRATE40) (ON CRATE35 CRATE12)
(ON CRATE37 CRATE20) (ON CRATE38 CRATE31) (ON CRATE39 CRATE30)
(ON CRATE40 PALLET2) (ON CRATE41 CRATE6) (ON CRATE42 CRATE49)
(ON CRATE43 CRATE10) (ON CRATE44 CRATE19) (ON CRATE45 CRATE57)
(ON CRATE46 CRATE14) (ON CRATE47 CRATE55) (ON CRATE48 CRATE22)
(ON CRATE49 PALLET5) (ON CRATE51 CRATE13) (ON CRATE52 CRATE26)
(ON CRATE53 CRATE44) (ON CRATE54 PALLET0) (ON CRATE55 CRATE52)
(ON CRATE56 CRATE43) (ON CRATE57 CRATE37) (ON CRATE58 PALLET1)
(ON CRATE59 CRATE11))
))
)
| null | https://raw.githubusercontent.com/cl-axon/shop2/9136e51f7845b46232cc17ca3618f515ddcf2787/examples/depots/pfile11.lisp | lisp |
facts
initial states
goals
| (in-package :shop2-user)
(defproblem pfile11 DEPOT
(
(DEPOT DEPOT0)
(DEPOT DEPOT1)
(DEPOT DEPOT2)
(DISTRIBUTOR DISTRIBUTOR0)
(DISTRIBUTOR DISTRIBUTOR1)
(DISTRIBUTOR DISTRIBUTOR2)
(TRUCK TRUCK0)
(TRUCK TRUCK1)
(TRUCK TRUCK2)
(TRUCK TRUCK3)
(PALLET PALLET0)
(PALLET PALLET1)
(PALLET PALLET2)
(PALLET PALLET3)
(PALLET PALLET4)
(PALLET PALLET5)
(CRATE CRATE0)
(CRATE CRATE1)
(CRATE CRATE2)
(CRATE CRATE3)
(CRATE CRATE4)
(CRATE CRATE5)
(CRATE CRATE6)
(CRATE CRATE7)
(CRATE CRATE8)
(CRATE CRATE9)
(CRATE CRATE10)
(CRATE CRATE11)
(CRATE CRATE12)
(CRATE CRATE13)
(CRATE CRATE14)
(CRATE CRATE15)
(CRATE CRATE16)
(CRATE CRATE17)
(CRATE CRATE18)
(CRATE CRATE19)
(CRATE CRATE20)
(CRATE CRATE21)
(CRATE CRATE22)
(CRATE CRATE23)
(CRATE CRATE24)
(CRATE CRATE25)
(CRATE CRATE26)
(CRATE CRATE27)
(CRATE CRATE28)
(CRATE CRATE29)
(CRATE CRATE30)
(CRATE CRATE31)
(CRATE CRATE32)
(CRATE CRATE33)
(CRATE CRATE34)
(CRATE CRATE35)
(CRATE CRATE36)
(CRATE CRATE37)
(CRATE CRATE38)
(CRATE CRATE39)
(CRATE CRATE40)
(CRATE CRATE41)
(CRATE CRATE42)
(CRATE CRATE43)
(CRATE CRATE44)
(CRATE CRATE45)
(CRATE CRATE46)
(CRATE CRATE47)
(CRATE CRATE48)
(CRATE CRATE49)
(CRATE CRATE50)
(CRATE CRATE51)
(CRATE CRATE52)
(CRATE CRATE53)
(CRATE CRATE54)
(CRATE CRATE55)
(CRATE CRATE56)
(CRATE CRATE57)
(CRATE CRATE58)
(CRATE CRATE59)
(HOIST HOIST0)
(HOIST HOIST1)
(HOIST HOIST2)
(HOIST HOIST3)
(HOIST HOIST4)
(HOIST HOIST5)
(AT PALLET0 DEPOT0)
(CLEAR CRATE59)
(AT PALLET1 DEPOT1)
(CLEAR CRATE35)
(AT PALLET2 DEPOT2)
(CLEAR CRATE55)
(AT PALLET3 DISTRIBUTOR0)
(CLEAR CRATE52)
(AT PALLET4 DISTRIBUTOR1)
(CLEAR CRATE57)
(AT PALLET5 DISTRIBUTOR2)
(CLEAR CRATE58)
(AT TRUCK0 DEPOT2)
(AT TRUCK1 DISTRIBUTOR0)
(AT TRUCK2 DEPOT1)
(AT TRUCK3 DEPOT1)
(AT HOIST0 DEPOT0)
(AVAILABLE HOIST0)
(AT HOIST1 DEPOT1)
(AVAILABLE HOIST1)
(AT HOIST2 DEPOT2)
(AVAILABLE HOIST2)
(AT HOIST3 DISTRIBUTOR0)
(AVAILABLE HOIST3)
(AT HOIST4 DISTRIBUTOR1)
(AVAILABLE HOIST4)
(AT HOIST5 DISTRIBUTOR2)
(AVAILABLE HOIST5)
(AT CRATE0 DEPOT1)
(ON CRATE0 PALLET1)
(AT CRATE1 DEPOT2)
(ON CRATE1 PALLET2)
(AT CRATE2 DEPOT2)
(ON CRATE2 CRATE1)
(AT CRATE3 DISTRIBUTOR2)
(ON CRATE3 PALLET5)
(AT CRATE4 DISTRIBUTOR2)
(ON CRATE4 CRATE3)
(AT CRATE5 DISTRIBUTOR2)
(ON CRATE5 CRATE4)
(AT CRATE6 DEPOT2)
(ON CRATE6 CRATE2)
(AT CRATE7 DEPOT2)
(ON CRATE7 CRATE6)
(AT CRATE8 DEPOT1)
(ON CRATE8 CRATE0)
(AT CRATE9 DEPOT2)
(ON CRATE9 CRATE7)
(AT CRATE10 DEPOT2)
(ON CRATE10 CRATE9)
(AT CRATE11 DISTRIBUTOR1)
(ON CRATE11 PALLET4)
(AT CRATE12 DISTRIBUTOR0)
(ON CRATE12 PALLET3)
(AT CRATE13 DISTRIBUTOR2)
(ON CRATE13 CRATE5)
(AT CRATE14 DISTRIBUTOR1)
(ON CRATE14 CRATE11)
(AT CRATE15 DEPOT2)
(ON CRATE15 CRATE10)
(AT CRATE16 DISTRIBUTOR2)
(ON CRATE16 CRATE13)
(AT CRATE17 DISTRIBUTOR0)
(ON CRATE17 CRATE12)
(AT CRATE18 DEPOT1)
(ON CRATE18 CRATE8)
(AT CRATE19 DEPOT0)
(ON CRATE19 PALLET0)
(AT CRATE20 DISTRIBUTOR1)
(ON CRATE20 CRATE14)
(AT CRATE21 DEPOT0)
(ON CRATE21 CRATE19)
(AT CRATE22 DISTRIBUTOR0)
(ON CRATE22 CRATE17)
(AT CRATE23 DISTRIBUTOR1)
(ON CRATE23 CRATE20)
(AT CRATE24 DEPOT2)
(ON CRATE24 CRATE15)
(AT CRATE25 DEPOT0)
(ON CRATE25 CRATE21)
(AT CRATE26 DEPOT2)
(ON CRATE26 CRATE24)
(AT CRATE27 DISTRIBUTOR0)
(ON CRATE27 CRATE22)
(AT CRATE28 DISTRIBUTOR1)
(ON CRATE28 CRATE23)
(AT CRATE29 DISTRIBUTOR1)
(ON CRATE29 CRATE28)
(AT CRATE30 DISTRIBUTOR1)
(ON CRATE30 CRATE29)
(AT CRATE31 DEPOT1)
(ON CRATE31 CRATE18)
(AT CRATE32 DEPOT0)
(ON CRATE32 CRATE25)
(AT CRATE33 DEPOT0)
(ON CRATE33 CRATE32)
(AT CRATE34 DISTRIBUTOR0)
(ON CRATE34 CRATE27)
(AT CRATE35 DEPOT1)
(ON CRATE35 CRATE31)
(AT CRATE36 DEPOT0)
(ON CRATE36 CRATE33)
(AT CRATE37 DISTRIBUTOR0)
(ON CRATE37 CRATE34)
(AT CRATE38 DISTRIBUTOR1)
(ON CRATE38 CRATE30)
(AT CRATE39 DISTRIBUTOR0)
(ON CRATE39 CRATE37)
(AT CRATE40 DISTRIBUTOR0)
(ON CRATE40 CRATE39)
(AT CRATE41 DISTRIBUTOR2)
(ON CRATE41 CRATE16)
(AT CRATE42 DEPOT2)
(ON CRATE42 CRATE26)
(AT CRATE43 DISTRIBUTOR2)
(ON CRATE43 CRATE41)
(AT CRATE44 DEPOT0)
(ON CRATE44 CRATE36)
(AT CRATE45 DEPOT2)
(ON CRATE45 CRATE42)
(AT CRATE46 DISTRIBUTOR1)
(ON CRATE46 CRATE38)
(AT CRATE47 DISTRIBUTOR0)
(ON CRATE47 CRATE40)
(AT CRATE48 DISTRIBUTOR0)
(ON CRATE48 CRATE47)
(AT CRATE49 DISTRIBUTOR2)
(ON CRATE49 CRATE43)
(AT CRATE50 DISTRIBUTOR0)
(ON CRATE50 CRATE48)
(AT CRATE51 DEPOT2)
(ON CRATE51 CRATE45)
(AT CRATE52 DISTRIBUTOR0)
(ON CRATE52 CRATE50)
(AT CRATE53 DEPOT2)
(ON CRATE53 CRATE51)
(AT CRATE54 DEPOT2)
(ON CRATE54 CRATE53)
(AT CRATE55 DEPOT2)
(ON CRATE55 CRATE54)
(AT CRATE56 DISTRIBUTOR1)
(ON CRATE56 CRATE46)
(AT CRATE57 DISTRIBUTOR1)
(ON CRATE57 CRATE56)
(AT CRATE58 DISTRIBUTOR2)
(ON CRATE58 CRATE49)
(AT CRATE59 DEPOT0)
(ON CRATE59 CRATE44)
)
((achieve-goals
((ON CRATE0 CRATE47) (ON CRATE2 CRATE58) (ON CRATE3 CRATE9)
(ON CRATE5 CRATE35) (ON CRATE6 CRATE18) (ON CRATE7 CRATE24)
(ON CRATE8 CRATE53) (ON CRATE9 CRATE51) (ON CRATE10 CRATE15)
(ON CRATE11 CRATE41) (ON CRATE12 CRATE54) (ON CRATE13 CRATE29)
(ON CRATE14 CRATE56) (ON CRATE15 CRATE27) (ON CRATE18 CRATE34)
(ON CRATE19 CRATE32) (ON CRATE20 CRATE8) (ON CRATE21 CRATE0)
(ON CRATE22 CRATE7) (ON CRATE23 CRATE3) (ON CRATE24 CRATE46)
(ON CRATE25 PALLET3) (ON CRATE26 CRATE38) (ON CRATE27 CRATE2)
(ON CRATE29 CRATE42) (ON CRATE30 CRATE5) (ON CRATE31 CRATE25)
(ON CRATE32 PALLET4) (ON CRATE34 CRATE40) (ON CRATE35 CRATE12)
(ON CRATE37 CRATE20) (ON CRATE38 CRATE31) (ON CRATE39 CRATE30)
(ON CRATE40 PALLET2) (ON CRATE41 CRATE6) (ON CRATE42 CRATE49)
(ON CRATE43 CRATE10) (ON CRATE44 CRATE19) (ON CRATE45 CRATE57)
(ON CRATE46 CRATE14) (ON CRATE47 CRATE55) (ON CRATE48 CRATE22)
(ON CRATE49 PALLET5) (ON CRATE51 CRATE13) (ON CRATE52 CRATE26)
(ON CRATE53 CRATE44) (ON CRATE54 PALLET0) (ON CRATE55 CRATE52)
(ON CRATE56 CRATE43) (ON CRATE57 CRATE37) (ON CRATE58 PALLET1)
(ON CRATE59 CRATE11))
))
)
|
eaae439eba89fe8737496d96fef13190270a7d1cad1120adebdcf5eae9c02b14 | ivankocienski/lspec | spec-group.lisp | (in-package :lspec)
(defparameter *spec-group-root* nil)
(defstruct spec-group
id
caption
around-callbacks
;; this should count all the sub entries?
entries
parent)
(defmethod print-object ((this spec-group) out)
(print-unreadable-object (this out)
(format out "SPEC-GROUP ")
(format out "id=~d " (spec-group-id this))
(format out "caption=~s " (spec-group-caption this))
(format out "around-callbacks=") (print-object (spec-group-around-callbacks this) out)
(format out " entries=") (print-object (spec-group-entries this) out)))
(defun alloc-new-group (caption parent)
(format t "alloc-new-group~%")
(let ((new-group (make-spec-group :caption caption
:parent parent
:id (1+ (length
(if parent
(spec-group-entries parent)
*spec-group-root*))))))
(if parent
(setf (spec-group-entries parent)
(al-insert (spec-group-entries parent) caption new-group))
(setf *spec-group-root*
(al-insert *spec-group-root* caption new-group)))
new-group))
(defmacro build-around-each (group &body body)
`(push (lambda (next-step)
(package-macrolet ((yield () `(funcall next-step)))
,@body))
(spec-group-around-callbacks ,group)))
(defmacro internal-group (caption parent &body body)
`(let ((new-group (alloc-new-group ,caption ,parent)))
(package-macrolet ((it (caption &body body)
`(internal-it ,caption new-group ,@body))
(context (caption &body body)
`(internal-group ,caption new-group ,@body))
(around-each (&body body)
`(build-around-each new-group ,@body)))
,@body)))
(defun run-group-entries (formatter entry-list)
(al-each-value (entry-list entry)
(typecase entry
;; run sub-group
(spec-group
(with-formatter-group-run (formatter entry)
(run-group-entries formatter
(spec-group-entries entry))))
;; run spec
(spec (invoke-spec formatter entry)))))
| null | https://raw.githubusercontent.com/ivankocienski/lspec/489346b7f53692f2ff9c86748a14ebea89eedfd6/src/spec-group.lisp | lisp | this should count all the sub entries?
run sub-group
run spec | (in-package :lspec)
(defparameter *spec-group-root* nil)
(defstruct spec-group
id
caption
around-callbacks
entries
parent)
(defmethod print-object ((this spec-group) out)
(print-unreadable-object (this out)
(format out "SPEC-GROUP ")
(format out "id=~d " (spec-group-id this))
(format out "caption=~s " (spec-group-caption this))
(format out "around-callbacks=") (print-object (spec-group-around-callbacks this) out)
(format out " entries=") (print-object (spec-group-entries this) out)))
(defun alloc-new-group (caption parent)
(format t "alloc-new-group~%")
(let ((new-group (make-spec-group :caption caption
:parent parent
:id (1+ (length
(if parent
(spec-group-entries parent)
*spec-group-root*))))))
(if parent
(setf (spec-group-entries parent)
(al-insert (spec-group-entries parent) caption new-group))
(setf *spec-group-root*
(al-insert *spec-group-root* caption new-group)))
new-group))
(defmacro build-around-each (group &body body)
`(push (lambda (next-step)
(package-macrolet ((yield () `(funcall next-step)))
,@body))
(spec-group-around-callbacks ,group)))
(defmacro internal-group (caption parent &body body)
`(let ((new-group (alloc-new-group ,caption ,parent)))
(package-macrolet ((it (caption &body body)
`(internal-it ,caption new-group ,@body))
(context (caption &body body)
`(internal-group ,caption new-group ,@body))
(around-each (&body body)
`(build-around-each new-group ,@body)))
,@body)))
(defun run-group-entries (formatter entry-list)
(al-each-value (entry-list entry)
(typecase entry
(spec-group
(with-formatter-group-run (formatter entry)
(run-group-entries formatter
(spec-group-entries entry))))
(spec (invoke-spec formatter entry)))))
|
696265e3132b1b0b458b10b14267b9ff2dfb04dd85fd55b48766625c15d6b307 | rtoy/cmucl | print.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
If you want to use this code or any part of CMU Common Lisp , please contact
or .
;;;
(ext:file-comment
"$Header: src/compiler/x86/print.lisp $")
;;;
;;; **********************************************************************
;;;
This file contains the print VOP , which is used while booting the kernel
;;; core to keep the user entertained.
;;;
Written by .
Enhancements / debugging by 1996 .
;;;
(in-package :x86)
(intl:textdomain "cmucl-x86-vm")
(define-vop (print)
(:args (object :scs (descriptor-reg any-reg)))
(:temporary (:sc unsigned-reg :offset eax-offset :target result
:from :eval :to :result) eax)
#+darwin
(:temporary (:sc unsigned-reg) temp)
(:results (result :scs (descriptor-reg)))
(:save-p t)
#-darwin
(:generator 100
(inst push object)
(inst lea eax (make-fixup (extern-alien-name "debug_print") :foreign))
(inst call (make-fixup (extern-alien-name "call_into_c") :foreign))
(inst add esp-tn word-bytes)
(move result eax))
#+darwin
(:generator 100
(inst mov temp esp-tn)
(inst sub esp-tn 8)
(inst and esp-tn #xfffffff0)
(inst mov (make-ea :dword :base esp-tn) object)
(inst mov (make-ea :dword :base esp-tn :disp 4) temp)
(inst lea eax (make-fixup (extern-alien-name "debug_print") :foreign))
(inst call (make-fixup (extern-alien-name "call_into_c") :foreign))
(inst mov esp-tn (make-ea :dword :base esp-tn :disp 4))
(move result eax)))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/x86/print.lisp | lisp | Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*-
**********************************************************************
**********************************************************************
core to keep the user entertained.
| This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
If you want to use this code or any part of CMU Common Lisp , please contact
or .
(ext:file-comment
"$Header: src/compiler/x86/print.lisp $")
This file contains the print VOP , which is used while booting the kernel
Written by .
Enhancements / debugging by 1996 .
(in-package :x86)
(intl:textdomain "cmucl-x86-vm")
(define-vop (print)
(:args (object :scs (descriptor-reg any-reg)))
(:temporary (:sc unsigned-reg :offset eax-offset :target result
:from :eval :to :result) eax)
#+darwin
(:temporary (:sc unsigned-reg) temp)
(:results (result :scs (descriptor-reg)))
(:save-p t)
#-darwin
(:generator 100
(inst push object)
(inst lea eax (make-fixup (extern-alien-name "debug_print") :foreign))
(inst call (make-fixup (extern-alien-name "call_into_c") :foreign))
(inst add esp-tn word-bytes)
(move result eax))
#+darwin
(:generator 100
(inst mov temp esp-tn)
(inst sub esp-tn 8)
(inst and esp-tn #xfffffff0)
(inst mov (make-ea :dword :base esp-tn) object)
(inst mov (make-ea :dword :base esp-tn :disp 4) temp)
(inst lea eax (make-fixup (extern-alien-name "debug_print") :foreign))
(inst call (make-fixup (extern-alien-name "call_into_c") :foreign))
(inst mov esp-tn (make-ea :dword :base esp-tn :disp 4))
(move result eax)))
|
f8eef4676a4e903ca578c02bc855d0591827bed64a87f9a58c4698e5bd42dffb | yesodweb/persistent | LargeNumberTest.hs | # LANGUAGE UndecidableInstances #
module LargeNumberTest where
import Data.Word
import Init
share [mkPersist sqlSettings { mpsGeneric = True }, mkMigrate "numberMigrate"] [persistLowerCase|
Number
intx Int
int32 Int32
word32 Word32
int64 Int64
word64 Word64
deriving Show Eq
|]
cleanDB
:: Runner backend m => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter (NumberGeneric backend)])
specsWith :: Runner backend m => RunDb backend m -> Spec
specsWith runDb = describe "Large Numbers" $ do
it "preserves their values in the database" $ runDb $ do
let go x = do
xid <- insert x
x' <- get xid
liftIO $ x' @?= Just x
go $ Number maxBound 0 0 0 0
go $ Number 0 maxBound 0 0 0
go $ Number 0 0 maxBound 0 0
go $ Number 0 0 0 maxBound 0
go $ Number 0 0 0 0 maxBound
go $ Number minBound 0 0 0 0
go $ Number 0 minBound 0 0 0
go $ Number 0 0 minBound 0 0
go $ Number 0 0 0 minBound 0
go $ Number 0 0 0 0 minBound
| null | https://raw.githubusercontent.com/yesodweb/persistent/bf4c3ae430d7e7ec0351a768783d73e6bd265890/persistent-test/src/LargeNumberTest.hs | haskell | # LANGUAGE UndecidableInstances #
module LargeNumberTest where
import Data.Word
import Init
share [mkPersist sqlSettings { mpsGeneric = True }, mkMigrate "numberMigrate"] [persistLowerCase|
Number
intx Int
int32 Int32
word32 Word32
int64 Int64
word64 Word64
deriving Show Eq
|]
cleanDB
:: Runner backend m => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter (NumberGeneric backend)])
specsWith :: Runner backend m => RunDb backend m -> Spec
specsWith runDb = describe "Large Numbers" $ do
it "preserves their values in the database" $ runDb $ do
let go x = do
xid <- insert x
x' <- get xid
liftIO $ x' @?= Just x
go $ Number maxBound 0 0 0 0
go $ Number 0 maxBound 0 0 0
go $ Number 0 0 maxBound 0 0
go $ Number 0 0 0 maxBound 0
go $ Number 0 0 0 0 maxBound
go $ Number minBound 0 0 0 0
go $ Number 0 minBound 0 0 0
go $ Number 0 0 minBound 0 0
go $ Number 0 0 0 minBound 0
go $ Number 0 0 0 0 minBound
| |
30201e22cc27569af35edf10a0f058c1c32ddde50f7c9d16fc68d38f2b627db4 | haskell-gi/gi-gtk-examples | Uzbl.hs | -- | This is program use uzbl embedded in window to render webpage.
-- Just simple model demo for view, haven't handle event or else.
--
You need install uzbl ( git clone git ) first .
--
-- How to use:
./Uzbl default open Google page .
-- ./Uzbl url will open url you input
--
module Main where
import Graphics.UI.Gtk
import System.Process
import System.Environment
main :: IO ()
main = do
Init .
initGUI
-- Get program arguments.
args <- getArgs
let url = case args of
[arg] -> arg -- get user input url
_ -> "" -- set default url
-- Create window.
window <- windowNew
windowSetDefaultSize window 900 600
windowSetPosition window WinPosCenter
this function need window - manager support Alpha channel in X11
-- Create socket.
socket <- socketNew
widgetShow socket -- must show before add to parent
window `containerAdd` socket
-- Get socket id.
socketId <- fmap (show . fromNativeWindowId) $ socketGetId socket
-- Start uzbl-core process.
runCommand $ "uzbl-core -s " ++ socketId ++ " -u " ++ url
-- Show.
window `onDestroy` mainQuit
widgetShowAll window
mainGUI
| null | https://raw.githubusercontent.com/haskell-gi/gi-gtk-examples/4c4f06dc91fbb9b9f50cdad295c8afe782e0bdec/embedded/Uzbl.hs | haskell | | This is program use uzbl embedded in window to render webpage.
Just simple model demo for view, haven't handle event or else.
How to use:
./Uzbl url will open url you input
Get program arguments.
get user input url
set default url
Create window.
Create socket.
must show before add to parent
Get socket id.
Start uzbl-core process.
Show. | You need install uzbl ( git clone git ) first .
./Uzbl default open Google page .
module Main where
import Graphics.UI.Gtk
import System.Process
import System.Environment
main :: IO ()
main = do
Init .
initGUI
args <- getArgs
let url = case args of
window <- windowNew
windowSetDefaultSize window 900 600
windowSetPosition window WinPosCenter
this function need window - manager support Alpha channel in X11
socket <- socketNew
window `containerAdd` socket
socketId <- fmap (show . fromNativeWindowId) $ socketGetId socket
runCommand $ "uzbl-core -s " ++ socketId ++ " -u " ++ url
window `onDestroy` mainQuit
widgetShowAll window
mainGUI
|
17ae455909ad9ca3dcfd636168d30981c1ca755c4e77eb127849a38d3cc09e61 | astrada/ocaml-extjs | example_data.ml | let () =
Ext.instance##require(
Js.array [|Js.string "Ext.data.*"|],
Js.undefined,
Js.undefined,
Js.undefined)
let math_floor number =
(Js.Unsafe.coerce Js.math)##floor(number)
let math_max n1 n2 =
(Js.Unsafe.coerce Js.math)##max(n1, n2)
let generateData ?(n = 12) ?(floor = 20.0) () =
let get_value floor =
math_floor (math_max (Js.to_float Js.math##random() *. 100.0) floor)
in
let data = jsnew Js.array_empty () in
for i = 0 to n do
ignore (data##push({|
name = Js.array_get (Ext_Date.instance##monthNames) (i mod 12);
data1 = get_value floor;
data2 = get_value floor;
data3 = get_value floor;
data4 = get_value floor;
data5 = get_value floor;
data6 = get_value floor;
data7 = get_value floor;
data8 = get_value floor;
data9 = get_value floor;
|}));
done;
data
let () =
Ext.instance##onReady(
Js.wrap_callback (fun () ->
let store1 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store1" store1;
let store3 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store3" store3;
let store4 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store4" store4;
),
ExtUtils.undef,
ExtUtils.undef)
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/examples/charts/area/example_data.ml | ocaml | let () =
Ext.instance##require(
Js.array [|Js.string "Ext.data.*"|],
Js.undefined,
Js.undefined,
Js.undefined)
let math_floor number =
(Js.Unsafe.coerce Js.math)##floor(number)
let math_max n1 n2 =
(Js.Unsafe.coerce Js.math)##max(n1, n2)
let generateData ?(n = 12) ?(floor = 20.0) () =
let get_value floor =
math_floor (math_max (Js.to_float Js.math##random() *. 100.0) floor)
in
let data = jsnew Js.array_empty () in
for i = 0 to n do
ignore (data##push({|
name = Js.array_get (Ext_Date.instance##monthNames) (i mod 12);
data1 = get_value floor;
data2 = get_value floor;
data3 = get_value floor;
data4 = get_value floor;
data5 = get_value floor;
data6 = get_value floor;
data7 = get_value floor;
data8 = get_value floor;
data9 = get_value floor;
|}));
done;
data
let () =
Ext.instance##onReady(
Js.wrap_callback (fun () ->
let store1 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store1" store1;
let store3 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store3" store3;
let store4 = Ext.instance##create(
Js.def (Js.string "Ext.data.JsonStore"),
Js.def {|
fields = Js.array [|
Js.string "name";
Js.string "data1";
Js.string "data2";
Js.string "data3";
Js.string "data4";
Js.string "data5";
Js.string "data6";
Js.string "data7";
Js.string "data8";
Js.string "data9"
|];
data = generateData ()
|}) in
ExtUtils.set_global "store4" store4;
),
ExtUtils.undef,
ExtUtils.undef)
| |
ddba2fe48506cc8c029b6d0377d9e70209ee9ba49a02512ab6bc4d5505c17dc9 | amnh/poy5 | block.ml | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let () = SadmanOutput.register "Block" "$Revision: 3663 $"
* Blocks are conserved areas between two chromosomes
* which do not require identical nucleotide segments but
* highly similar . Blocks are considered as homologus segments and used
* as milestones to divide chromosomes into sequences of loci
* which do not require identical nucleotide segments but
* highly similar. Blocks are considered as homologus segments and used
* as milestones to divide chromosomes into sequences of loci*)
type pairChromPam_t = ChromPam.chromPairAliPam_t
type seed_t = Seed.seed_t
type direction_t = ChromPam.direction_t
type order_t = ChromPam.order_t
type subseq_t = Subseq.subseq_t
let deref = Utl.deref
let fprintf = Printf.fprintf
module IntSet = All_sets.Integers
* Parameters are used to create blocks between two chromosomes
type blockPam_t = {
* Two consecutive blocks are connected if their distance and shift are
smaller than thresholds
smaller than thresholds *)
max_connecting_dis : int;
max_connecting_shift: int;
}
(** A block is created by connecting a list of seeds together*)
type block_t = {
mutable id : int; (** The block id *)
mutable is_dum : bool; (* Dummy blocks are used as boundary *)
sta1 is the start of block in the first chromosome
sta2 is the start of block in the second chromosome
end1 is the end of block in the first chromosome
end2 is the end of block in the second chromosome
mutable direction : direction_t; (* The direction of this block, either postive or negative *)
mutable cost : int; (* The alignment cost of this block *)
alied_seq1 and alied_seq2 are aligned sequences of this block
mutable alied_seq2 : Sequence.s option;
mutable seed_ls : seed_t list; (* The list of seeds constituted this block *)
(** A chromosome is divided into consecutive sub-sequences *)
The identification of this block in the first chromosome
The identification of this block in the second chromosome
}
let blockPam_default = {
max_connecting_dis = 30000;
max_connecting_shift = 3000;
}
let cloneBlockPam (donor : blockPam_t) = {
max_connecting_dis = donor.max_connecting_dis;
max_connecting_shift = donor.max_connecting_shift;
}
(** [create_from_seed] function returns a block
* with ID [block_id], and contains only one seed [seed] *)
let create_from_seed (block_id : int) (seed : seed_t) = {
id = block_id;
is_dum = false;
sta1 = seed.Seed.sta1;
sta2 = seed.Seed.sta2;
en1 = seed.Seed.sta1 + seed.Seed.len - 1;
en2 = seed.Seed.sta2 + seed.Seed.len - 1;
direction = `Positive;
cost = 0;
seed_ls = [seed];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let create_simple_block (block_id : int) (new_sta1 : int)
(new_en1 : int) (new_sta2 : int) (new_en2 : int) =
{ id = block_id;
is_dum = false;
sta1 = new_sta1;
sta2 = new_sta2;
en1 = new_en1;
en2 = new_en2;
direction = `Positive;
cost = 0;
seed_ls = [];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
(** [get_dum_first_block ali_pam] returns a dummy block which is used
* as a start point for dynamic programming to connect blocks together *)
let get_dum_first_block ali_pam = {
id = -1;
is_dum = true;
sta1 = ali_pam.ChromPam.min_pos1 - 1; en1 = ali_pam.ChromPam.min_pos1 - 1;
sta2 = ali_pam.ChromPam.min_pos2 - 1; en2 = ali_pam.ChromPam.min_pos2 - 1;
cost = ali_pam.ChromPam.sig_k * ali_pam.ChromPam.mat_cost;
direction = `Positive;
seed_ls = [Seed.get_dum_first_seed ali_pam.ChromPam.min_pos1 ali_pam.ChromPam.min_pos2];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
(** [get_dum_last_block ali_pam] returns a dummy block which is used
* as an end point for dynamic programming to connect blocks together *)
let get_dum_last_block ali_pam = {
id = -1;
is_dum = true;
sta1 = ali_pam.ChromPam.max_pos1 + 1; en1 = ali_pam.ChromPam.max_pos1 + 1;
sta2 = ali_pam.ChromPam.max_pos2 + 1; en2 = ali_pam.ChromPam.max_pos2 + 1;
cost = ali_pam.ChromPam.sig_k * ali_pam.ChromPam.mat_cost;
direction = `Positive;
seed_ls = [Seed.get_dum_last_seed ali_pam.ChromPam.max_pos1 ali_pam.ChromPam.max_pos2];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let max_len (b : block_t) =
max (b.en1 - b.sta1 + 1) (b.en2 - b.sta2 + 1)
* [ invert block min_pos2 max_pos2 ] returns [ block ' ]
* which is inverted from [ block ] due to the inversion
* from [ min_pos2 ] to [ max_pos2 ] in the second chromosome
* which is inverted from [block] due to the inversion
* from [min_pos2] to [max_pos2] in the second chromosome *)
let invert (block : block_t) (min_pos2 : int) (max_pos2 : int) =
let new_sta2 = min_pos2 + (max_pos2 - block.en2) in
let new_en2 = min_pos2 + (max_pos2 - block.sta2) in
block.sta2 <- new_sta2;
block.en2 <- new_en2;
(match block.direction with
| `Positive -> block.direction <- `Negative
| _ -> block.direction <- `Positive);
(match block.alied_seq2 with
| None -> ()
| Some seq -> Sequence.reverse_ip seq);
List.iter (fun seed -> Seed.invert min_pos2 max_pos2 seed) block.seed_ls
let get_pos (block : block_t) (order : order_t) =
match order with
| `First -> block.sta1, block.en1
| _ -> block.sta2, block.en2
let cmp_dia_dis (b1 : block_t) (b2 : block_t) =
abs ( (b1.en1 - b1.en2) - (b2.sta1 - b2.sta2) )
let print (block : block_t) =
let dir =
match block.direction with
| `Positive -> 1
| _ -> -1
in
fprintf stdout "id: %i, (%i, %i) <--> (%i, %i) --> len: (%i, %i), "
block.id block.sta1 block.en1
block.sta2 block.en2
(block.en1 - block.sta1 + 1)
(block.en2 - block.sta2 + 1);
fprintf stdout "num_seed: %i, subseq: (%i, %i), cost: %i, direction: %i \n"
(List.length block.seed_ls) block.subseq1_id block.subseq2_id block.cost
dir;
List.iter Seed.print block.seed_ls;
print_endline "-------------------------------------"
let add_seed (block : block_t) (seed : seed_t) =
block.sta1 <- seed.Seed.sta1;
block.sta2 <- seed.Seed.sta2;
block.seed_ls <- seed::block.seed_ls
(** [cmp_cost_based_seed block ali_pam] returns an integer
* number as the cost of this [block]. The cost is calculated from
* its seed list and chromosome parameters [ali_pam] *)
let cmp_cost_based_seed (block : block_t) (ali_pam : pairChromPam_t) =
let rec cmp (cur_seed : seed_t) (res_ls : seed_t list) (cost : int) =
match res_ls with
| [] -> cost
| next_seed::tail ->
let connecting_cost =
Seed.cmp_connecting_cost cur_seed next_seed ali_pam in
cmp next_seed tail (cost + connecting_cost +
next_seed.Seed.len *ali_pam.ChromPam.mat_cost)
in
let seed_ls = block.seed_ls in
match seed_ls with
| [] -> 0
| first_seed::tail ->
cmp first_seed tail
(first_seed.Seed.len * ali_pam.ChromPam.mat_cost)
* [ create_from_seed_ls block_id seed_ls ali_pam ] returns
* a new block whose ID is [ block_id ] . The new block is
* created from the [ seed_ls ]
* a new block whose ID is [block_id]. The new block is
* created from the [seed_ls] *)
let create_from_seed_ls (block_id : int) (seed_ls : seed_t list)
(ali_pam : pairChromPam_t) =
let head = List.hd seed_ls in
let tail = List.hd (List.rev seed_ls) in
let new_block = {
id = block_id;
is_dum = false;
sta1 = head.Seed.sta1;
sta2 = head.Seed.sta2;
en1 = tail.Seed.sta1 + tail.Seed.len - 1;
en2 = tail.Seed.sta2 + tail.Seed.len - 1;
direction = `Positive;
cost = 0;
seed_ls = seed_ls;
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1}
in
new_block.cost <- cmp_cost_based_seed new_block ali_pam;
new_block
* [ cmp_ali_cost alied_seq1 alied_seq2 direction ali_pam ] returns
* an integer number as the alignment cost between [ alied_seq1 ]
* and [ alied_seq2 ] based on chromosome parameters [ ali_pam ]
* an integer number as the alignment cost between [alied_seq1]
* and [alied_seq2] based on chromosome parameters [ali_pam] *)
let cmp_ali_cost (alied_seq1 : Sequence.s) (alied_seq2 : Sequence.s)
(direction : direction_t) (ali_pam : pairChromPam_t) =
let len = Sequence.length alied_seq1 in
let code1_arr = Sequence.to_array alied_seq1 in
let code2_arr = Sequence.to_array alied_seq2 in
(if direction = `Negative then Utl.invert_subarr code2_arr 0 (Array.length code2_arr));
let mat_cost = ali_pam.ChromPam.mat_cost in
let mismat_cost = ali_pam.ChromPam.mismat_cost in
let gap_opening_cost = ali_pam.ChromPam.gap_opening_cost in
let gap_ext_cost = ali_pam.ChromPam.gap_ext_cost in
let gap_code = Alphabet.get_gap Alphabet.nucleotides in
let rec count pos cost =
match pos >= len with
| true -> cost
| false ->
match code1_arr.(pos) land code2_arr.(pos) > 0 with
| true -> count (pos + 1) (cost + mat_cost)
| false ->
match (code1_arr.(pos) = gap_code) || (code2_arr.(pos) = gap_code) with
| false -> count (pos + 1) (cost + mismat_cost)
| true ->
if ( (code1_arr.(pos) = gap_code)
&& (code1_arr.(pos - 1) = gap_code) ) ||
( (code2_arr.(pos) = gap_code)
&& (code2_arr.(pos - 1) = gap_code) ) then
count (pos + 1) (cost + gap_ext_cost)
else count (pos + 1) (cost + gap_opening_cost)
in
if len = 0 then 0
else
match code1_arr.(0) = code2_arr.(0) with
| true -> count 1 mat_cost
| false ->
if (code1_arr.(0) = gap_code) || (code2_arr.(0) = gap_code) then
count 1 gap_opening_cost
else count 1 mismat_cost
(** [find_local_block seed_ls ali_pam] returns a list of blocks
* created by connecting seeds which are near each other *)
let find_local_block (seed_ls : seed_t list) (ali_pam : pairChromPam_t) =
let acc_cost_arr, back_arr, sorted_end_seed_arr =
Seed.create_local_connection seed_ls ali_pam in
let num_seed = List.length seed_ls in
let sorted_best_seed_arr = Array.copy sorted_end_seed_arr in
let cmp_seed (seed1 : seed_t) (seed2: seed_t) =
let id1 = seed1.Seed.id in
let id2 = seed2.Seed.id in
compare acc_cost_arr.(id1) acc_cost_arr.(id2)
in
Array.sort cmp_seed sorted_best_seed_arr;
let avail_seed_arr = Array.make num_seed true in
let num_block = ref 0 in
let rev_block_ls = ref [] in
for index = 0 to num_seed - 1 do
let seed = sorted_best_seed_arr.(index) in
let seed_id = seed.Seed.id in
if avail_seed_arr.(seed_id) then
begin
let seed_ls = ref [] in
let rec chase cur_seed_id =
if avail_seed_arr.(cur_seed_id) then
begin
let cur_seed = sorted_end_seed_arr.(cur_seed_id) in
seed_ls := cur_seed::!seed_ls;
avail_seed_arr.(cur_seed_id) <- false;
if back_arr.(cur_seed_id) != -1 then
chase back_arr.(cur_seed_id)
end
in
chase seed_id;
avail_seed_arr.(seed_id) <- false;
let new_block = create_from_seed_ls !num_block !seed_ls ali_pam in
num_block := !num_block + 1;
rev_block_ls := new_block::!rev_block_ls
end
done;
List.rev !rev_block_ls
* [ is_free b sig1_arr sig2_arr ] where
* - b : a block
* - sig1_arr : sig1_arr[i ] = -1 if position i
* in the first chromosome is not yet
* occupied by any block , otherwise occupied
* - sig2_arr : sig2_arr[i ] = -1 if position i
* in the second chromosome is not yet
* occupied by any block , otherwise occupied
* returns true if whole block [ b ] is not occupied , otherwise false
* - b: a block
* - sig1_arr: sig1_arr[i] = -1 if position i
* in the first chromosome is not yet
* occupied by any block, otherwise occupied
* - sig2_arr: sig2_arr[i] = -1 if position i
* in the second chromosome is not yet
* occupied by any block, otherwise occupied
* returns true if whole block [b] is not occupied, otherwise false *)
let is_free (b : block_t) (sig1_arr : int array) (sig2_arr : int array) =
let rec travel sig_arr pos en =
if pos > en then true
else
match sig_arr.(pos) = -1 with
| true -> travel sig_arr (pos + 1) en
| false -> false
in
if travel sig1_arr b.sta1 b.en1 = false then false
else travel sig2_arr b.sta2 b.en2
* [ assign block sig2_ar ] marks all positions
* of [ block ] as occupied position in both genomes
* of [block] as occupied position in both genomes *)
let assign block sig1_arr sig2_arr =
let assign_subseq block_id sig_arr (sta : int) (en : int) =
for pos = sta to en do
sig_arr.(pos) <- block_id
done
in
assign_subseq block.id sig1_arr block.sta1 block.en1;
assign_subseq block.id sig2_arr block.sta2 block.en2
* [ block_ls ali_pam ] returns
* two signiture arrays [ ] and [ sig2_arr ] where
* - sig1_arr[i ] is the block ID covering position i in the first chromosome
* - sig2_arr[i ] is the block ID covering position i in the second chromosome
* two signiture arrays [sig1_arr] and [sig2_arr] where
* - sig1_arr[i] is the block ID covering position i in the first chromosome
* - sig2_arr[i] is the block ID covering position i in the second chromosome *)
let create_sig_arr (block_ls : block_t list) ali_pam =
let _ = List.fold_left
(fun index block -> block.id <- index; index + 1) 0 block_ls in
let sig1_arr = Array.make (ali_pam.ChromPam.max_pos1 + 1) (-1) in
let sig2_arr = Array.make (ali_pam.ChromPam.max_pos2 + 1) (-1) in
List.iter (fun b -> assign b sig1_arr sig2_arr) block_ls;
sig1_arr, sig2_arr
(** [select_separated_block b_ls ali_pam] returns a list
* of blocks which are not overlaped each other. Blocks
* are selected according to their scores. Thus, higher score
* blocks are given higher selection priority *)
let select_separated_block b_ls ali_pam =
let b_arr = Array.of_list b_ls in
Array.sort (fun b1 b2 ->
let len1 : float = float (max_len b1) in
let len2 : float = float (max_len b2) in
let cost1 = float b1.cost in
let cost2 = float b2.cost in
int_of_float ( len1 *. log(-.cost1) -. len2 *. log(-.cost2) )
) b_arr;
let sig1_arr = Array.make (ali_pam.ChromPam.max_pos1 + 1) (-1) in
let sig2_arr = Array.make (ali_pam.ChromPam.max_pos2 + 1) (-1) in
List.fold_right
(fun b sep_bl_ls ->
match is_free b sig1_arr sig2_arr with
| true ->
assign b sig1_arr sig2_arr;
b::sep_bl_ls
| false -> sep_bl_ls
) (Array.to_list b_arr) []
* [ create_pos_alied_block block seq1 seq2 cost_mat ali_pam ]
* creates the alignment for [ block ] based on its seed_ls
* creates the alignment for [block] based on its seed_ls *)
let create_pos_alied_block (block : block_t) (seq1 : Sequence.s)
(seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m) ali_pam =
let rev_alied_subseq1_ls = ref [] in
let rev_alied_subseq2_ls = ref [] in
let total_ali_cost = ref 0 in
let rec create (pre_seed : seed_t) (cur_map_ls : seed_t list) =
let alied_pre_subseq1, alied_pre_subseq2, pre_cost =
Seed.create_alied_seed pre_seed seq1 seq2 cost_mat in
rev_alied_subseq1_ls := alied_pre_subseq1:: !rev_alied_subseq1_ls;
rev_alied_subseq2_ls := alied_pre_subseq2:: !rev_alied_subseq2_ls;
total_ali_cost := !total_ali_cost + pre_cost;
match cur_map_ls with
| [] -> ()
| head::tail ->
let alied_subseq1, alied_subseq2, cost =
Seed.create_alied_subseq pre_seed head seq1 seq2 cost_mat in
rev_alied_subseq1_ls := alied_subseq1::!rev_alied_subseq1_ls;
rev_alied_subseq2_ls := alied_subseq2::!rev_alied_subseq2_ls;
total_ali_cost := !total_ali_cost + cost;
create head tail
in
create (List.hd block.seed_ls) (List.tl block.seed_ls);
let alied_seq1 = Sequence.concat (List.rev !rev_alied_subseq1_ls) in
let alied_seq2 = Sequence.concat (List.rev !rev_alied_subseq2_ls) in
block.alied_seq1 <- Some alied_seq1;
block.alied_seq2 <- Some alied_seq2;
block.cost <- cmp_ali_cost alied_seq1 alied_seq2 block.direction ali_pam
(** [is_inide seed block] returns true if [seed]
* is in side [block], otherwise false *)
let is_inside (seed : seed_t) (block : block_t) =
(seed.Seed.sta1 >= block.sta1) &&
(seed.Seed.sta1 + seed.Seed.len - 1 <= block.en1) &&
(seed.Seed.sta2 >= block.sta2) &&
(seed.Seed.sta2 + seed.Seed.len - 1 <= block.en2)
* [ order max_pos subseq_type ] returns
* a list of separated subsequences which are created by
* using blocks as milestones . If order = First , the
* separated is for first chromosome , otherwise the second chromosome
* a list of separated subsequences which are created by
* using blocks as milestones. If order = First,the
* separated subseqs is for first chromosome, otherwise the second chromosome *)
let determine_separated_subseq (block_ls : block_t list) (order : order_t)
(max_pos : int) subseq_type : subseq_t list =
(* create the label_arr.(pos) -> list of blocks containing this position*)
let label_arr = Array.make (max_pos + 2) [] in
let rec create_label (block : block_t) =
if block.is_dum = false then
begin
let sta, en = get_pos block order in
let block_id = block.id in
stdout " % i % i % i " block_id sta en ; print_newline ( ) ;
for pos = sta to en do
label_arr.(pos) <- block_id::label_arr.(pos)
done
end
in
List.iter create_label block_ls;
let rev_sep_subseq_ls = ref [] in
let sta = ref 0 in
let num_sep_subseq = ref 0 in
for pos = 1 to max_pos + 1 do
let create_new_subseq (sta : int) (en : int) =
let new_subseq = {Subseq.id = !num_sep_subseq + 1;
Subseq.sta = sta;
Subseq.en = en;
Subseq.block_id_ls = label_arr.(sta)} in
rev_sep_subseq_ls := new_subseq::!rev_sep_subseq_ls;
num_sep_subseq := !num_sep_subseq + 1;
in
if (pos = max_pos + 1) ||
( (Utl.compare_non_dec_list label_arr.(pos) label_arr.(pos - 1)) = false) then
begin
if ( subseq_type = `Both) ||
( (subseq_type = `Alied) && (label_arr.(!sta) != []) ) ||
( (subseq_type = `Deleted) && (label_arr.(!sta) = []) )
then create_new_subseq !sta (pos - 1);
sta := pos
end
done;
List.rev !rev_sep_subseq_ls
* [ create_alied_block_ls block_ls ali_pam seq1 seq2 cost_mat ]
* creates the alignment for all blocks of [ block_ls ] based on their seed_ls
* creates the alignment for all blocks of [block_ls] based on their seed_ls *)
let create_alied_block_ls (block_ls : block_t list) (ali_pam : pairChromPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) cost_mat =
List.iter
(fun block ->
if block.direction = `Positive then
create_pos_alied_block block seq1 seq2 cost_mat ali_pam
) block_ls;
let min_pos2 = ali_pam.ChromPam.min_pos2 in
let max_pos2 = ali_pam.ChromPam.max_pos2 in
let com_seq2 = Sequence.complement_chrom Alphabet.nucleotides seq2 in
List.iter (fun block ->
if block.direction = `Negative then begin
invert block min_pos2 max_pos2;
create_pos_alied_block block seq1 com_seq2 cost_mat ali_pam;
invert block min_pos2 max_pos2;
end) block_ls
let check_sep_block (sep_block_ls : block_t list) =
let sep_block_arr = Array.of_list sep_block_ls in
let num_block = Array.length sep_block_arr in
for no1 = 0 to num_block - 2 do
for no2 = no1 + 1 to num_block - 1 do
if ((sep_block_arr.(no1).en1 <
sep_block_arr.(no2).sta1) ||
(sep_block_arr.(no2).en1 <
sep_block_arr.(no1).sta1) ) &&
( (sep_block_arr.(no1).en2 <
sep_block_arr.(no2).sta2) ||
(sep_block_arr.(no2).en2 <
sep_block_arr.(no1).sta2) )
then ()
else begin
print sep_block_arr.(no1);
print sep_block_arr.(no2);
failwith "Fucking diving block, they are still overlapped"
end
done
done;
print_endline "All block are separated!!!"
* [ prepen b1 b2 block_pam seq1 seq2 cost_mat ali_pam ] appends
block [ b2 ] to block [ b1 ]
block [b2] to block [b1] *)
let prepen (b1 : block_t) (b2 : block_t) (block_pam : blockPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m)
(ali_pam : pairChromPam_t) =
Block.ml and Seed.ml are with old annotation method , we do n't use them
* anymore . it does n't matter we use_ukk or not
* anymore. it doesn't matter we use_ukk or not*)
let use_ukk = false in
let alied_between_seq1, alied_between_seq2, cost =
Sequence.create_subalign2 seq1 seq2 cost_mat (b1.en1 + 1)
(b2.sta1 - 1) (b1.en2 + 1) (b2.sta2 - 1) use_ukk
in
let between_cost = cmp_ali_cost alied_between_seq1 alied_between_seq2
`Positive ali_pam
in
b2.sta1 <- b1.sta1;
b2.sta2 <- b1.sta2;
b2.cost <- b1.cost + between_cost + b2.cost;
b2.seed_ls <- b1.seed_ls @ b2.seed_ls;
b2.alied_seq1 <- Some (Sequence.concat [ (deref b1.alied_seq1);
alied_between_seq1;
(deref b2.alied_seq1)] );
b2.alied_seq2 <- Some (Sequence.concat [ (deref b1.alied_seq2);
alied_between_seq2;
(deref b2.alied_seq2)] )
* [ connect_pos_consecutive_block block_ls block_pam seq1 seq2 cost_mat ali_pam ]
* connect consecutive positive blocks together to create large blocks . This functions
* returns a concatenated blocks list
* connect consecutive positive blocks together to create large blocks. This functions
* returns a concatenated blocks list *)
let connect_pos_consecutive_block (block_ls : block_t list)
(block_pam : blockPam_t) (seq1 : Sequence.s) (seq2 : Sequence.s)
(cost_mat : Cost_matrix.Two_D.m) (ali_pam : pairChromPam_t) =
let sorted_block_arr = Array.of_list block_ls in
Array.sort (fun b1 b2 -> compare b1.en1 b2.en1) sorted_block_arr;
let _ = Array.fold_left
(fun id b -> b.id <- id; id + 1) 0 sorted_block_arr in
let marker1_set = ref IntSet.empty in
let marker2_set = ref IntSet.empty in
List.iter (fun b -> marker1_set := IntSet.add b.sta1 !marker1_set;
marker1_set := IntSet.add b.en1 !marker1_set;
marker2_set := IntSet.add b.sta2 !marker2_set;
marker2_set := IntSet.add b.en2 !marker2_set
) block_ls;
let marker1_arr = Array.of_list (IntSet.elements !marker1_set) in
let marker2_arr = Array.of_list (IntSet.elements !marker2_set) in
let max_pos1 = ali_pam.ChromPam.max_pos1 in
let max_pos2 = ali_pam.ChromPam.max_pos2 in
let sig1_arr = Array.make (max_pos1 + 1) [] in
let sig2_arr = Array.make (max_pos2 + 1) [] in
List.iter (fun b -> if b.direction = `Positive then
begin
sig1_arr.(b.sta1) <- b.id::sig1_arr.(b.sta1);
sig2_arr.(b.sta2) <- b.id::sig2_arr.(b.sta2);
end) block_ls;
let num_marker1 = Array.length marker1_arr in
let num_marker2 = Array.length marker2_arr in
let do_connection (b : block_t) =
let m1 = Utl.binary_index_search marker1_arr b.en1 in
let m2 = Utl.binary_index_search marker2_arr b.en2 in
if (m1 >= 0) && (m1 + 1 < num_marker1) &&
(m2 >= 0) && (m2 + 1 < num_marker2) then
begin
let e1 = marker1_arr.(m1 + 1) in
let e2 = marker2_arr.(m2 + 1) in
let dis1 = e1 - b.en1 in
let dis2 = e2 - b.en2 in
if (max dis1 dis2 <= block_pam.max_connecting_dis) &&
(abs (dis1 - dis2) <= block_pam.max_connecting_shift) then
begin
let com_block_id_ls = List.filter
(fun id -> List.mem id sig2_arr.(e2) ) sig1_arr.(e1) in
if List.length com_block_id_ls > 0 then
begin
List.iter (fun id -> prepen b sorted_block_arr.(id)
block_pam seq1 seq2 cost_mat ali_pam
) com_block_id_ls;
b.is_dum <- true
end
end
end
in
Array.iter (fun b -> if (b.is_dum = false) && (b.direction = `Positive) then
do_connection b) sorted_block_arr;
let pos_con_block_ls = Array.fold_left
(fun l b -> if b.is_dum then l else b::l) [] sorted_block_arr in
pos_con_block_ls
* [ connect_consecutive_block block_ls block_pam seq1 seq2 cost_mat ali_pam ]
* connect consecutive blocks together to create large blocks . This functions
* returns a concatenated blocks list
* connect consecutive blocks together to create large blocks. This functions
* returns a concatenated blocks list *)
let connect_consecutive_block (block_ls : block_t list) (block_pam : blockPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m)
(ali_pam : pairChromPam_t) =
let pos_con_block_ls = connect_pos_consecutive_block block_ls block_pam seq1
seq2 cost_mat ali_pam in
pos_con_block_ls
* [ create_subseq_id subseq_type sep_block_ls ali_pam ] returns
* two lists of separated subsequences for two chromosomes
* which are created by using [ sep_block_ls ] as milestones
* two lists of separated subsequences for two chromosomes
* which are created by using [sep_block_ls] as milestones *)
let create_subseq_id subseq_type (sep_block_ls : block_t list)
(ali_pam : pairChromPam_t) =
let _ = List.fold_left
(fun index block -> block.id <- index; index + 1) 0 sep_block_ls in
let sep_block_arr = Array.of_list sep_block_ls in
let subseq1_ls = determine_separated_subseq sep_block_ls
`First ali_pam.ChromPam.max_pos1 subseq_type in
let subseq2_ls = determine_separated_subseq sep_block_ls
`Second ali_pam.ChromPam.max_pos2 subseq_type in
List.iter (fun subseq -> List.iter
(fun block_id -> sep_block_arr.(block_id).subseq1_id <- subseq.Subseq.id
) subseq.Subseq.block_id_ls) subseq1_ls;
List.iter (fun subseq -> List.iter
(fun block_id -> sep_block_arr.(block_id).subseq2_id <- subseq.Subseq.id
) subseq.Subseq.block_id_ls) subseq2_ls;
sep_block_ls, subseq1_ls, subseq2_ls
(** [create_median] approx block cost_mat] returns
* the median sequence and the cost of [block] *)
let create_median ?(approx=`BothSeq) (block : block_t) cost_mat =
let alied_seq1 = Utl.deref block.alied_seq1 in
let alied_seq2 = Utl.deref block.alied_seq2 in
match block.direction = `Positive with
| true -> Sequence.create_median_seq ~approx:approx alied_seq1 alied_seq2 cost_mat
| false ->
Sequence.reverse_ip alied_seq2;
let med, cost = Sequence.create_median_seq ~approx:approx alied_seq1 alied_seq2 cost_mat in
Sequence.reverse_ip alied_seq2;
med, cost
* [ find_block block_ls subseq1_id subseq2_id ] returns
* the blocks whose subseq ids are [ subseq1_id ] and [ subseq2_id ]
* the blocks whose subseq ids are [subseq1_id] and [subseq2_id] *)
let find_block block_ls subseq1_id subseq2_id =
let rec check cur_block_ls =
match cur_block_ls with
| [] -> None
| hd::tl ->
if (hd.subseq1_id = subseq1_id)
&& (hd.subseq2_id = subseq2_id) then Some hd
else check tl
in
check block_ls
* [ find_subseq1 block_ls subseq1_id ] return the
* of the block whose is [ subseq1_id ]
* of the block whose subseq1 is [subseq1_id] *)
let find_subseq1 block_ls subseq1_id =
let rec check cur_block_ls =
match cur_block_ls with
| [] -> None
| hd::tl ->
if (hd.subseq1_id = subseq1_id) then Some hd
else check tl
in
check block_ls
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/block.ml | ocaml |
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.
* A block is created by connecting a list of seeds together
* The block id
Dummy blocks are used as boundary
The direction of this block, either postive or negative
The alignment cost of this block
The list of seeds constituted this block
* A chromosome is divided into consecutive sub-sequences
* [create_from_seed] function returns a block
* with ID [block_id], and contains only one seed [seed]
* [get_dum_first_block ali_pam] returns a dummy block which is used
* as a start point for dynamic programming to connect blocks together
* [get_dum_last_block ali_pam] returns a dummy block which is used
* as an end point for dynamic programming to connect blocks together
* [cmp_cost_based_seed block ali_pam] returns an integer
* number as the cost of this [block]. The cost is calculated from
* its seed list and chromosome parameters [ali_pam]
* [find_local_block seed_ls ali_pam] returns a list of blocks
* created by connecting seeds which are near each other
* [select_separated_block b_ls ali_pam] returns a list
* of blocks which are not overlaped each other. Blocks
* are selected according to their scores. Thus, higher score
* blocks are given higher selection priority
* [is_inide seed block] returns true if [seed]
* is in side [block], otherwise false
create the label_arr.(pos) -> list of blocks containing this position
* [create_median] approx block cost_mat] returns
* the median sequence and the cost of [block] | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let () = SadmanOutput.register "Block" "$Revision: 3663 $"
* Blocks are conserved areas between two chromosomes
* which do not require identical nucleotide segments but
* highly similar . Blocks are considered as homologus segments and used
* as milestones to divide chromosomes into sequences of loci
* which do not require identical nucleotide segments but
* highly similar. Blocks are considered as homologus segments and used
* as milestones to divide chromosomes into sequences of loci*)
type pairChromPam_t = ChromPam.chromPairAliPam_t
type seed_t = Seed.seed_t
type direction_t = ChromPam.direction_t
type order_t = ChromPam.order_t
type subseq_t = Subseq.subseq_t
let deref = Utl.deref
let fprintf = Printf.fprintf
module IntSet = All_sets.Integers
* Parameters are used to create blocks between two chromosomes
type blockPam_t = {
* Two consecutive blocks are connected if their distance and shift are
smaller than thresholds
smaller than thresholds *)
max_connecting_dis : int;
max_connecting_shift: int;
}
type block_t = {
sta1 is the start of block in the first chromosome
sta2 is the start of block in the second chromosome
end1 is the end of block in the first chromosome
end2 is the end of block in the second chromosome
alied_seq1 and alied_seq2 are aligned sequences of this block
mutable alied_seq2 : Sequence.s option;
The identification of this block in the first chromosome
The identification of this block in the second chromosome
}
let blockPam_default = {
max_connecting_dis = 30000;
max_connecting_shift = 3000;
}
let cloneBlockPam (donor : blockPam_t) = {
max_connecting_dis = donor.max_connecting_dis;
max_connecting_shift = donor.max_connecting_shift;
}
let create_from_seed (block_id : int) (seed : seed_t) = {
id = block_id;
is_dum = false;
sta1 = seed.Seed.sta1;
sta2 = seed.Seed.sta2;
en1 = seed.Seed.sta1 + seed.Seed.len - 1;
en2 = seed.Seed.sta2 + seed.Seed.len - 1;
direction = `Positive;
cost = 0;
seed_ls = [seed];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let create_simple_block (block_id : int) (new_sta1 : int)
(new_en1 : int) (new_sta2 : int) (new_en2 : int) =
{ id = block_id;
is_dum = false;
sta1 = new_sta1;
sta2 = new_sta2;
en1 = new_en1;
en2 = new_en2;
direction = `Positive;
cost = 0;
seed_ls = [];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let get_dum_first_block ali_pam = {
id = -1;
is_dum = true;
sta1 = ali_pam.ChromPam.min_pos1 - 1; en1 = ali_pam.ChromPam.min_pos1 - 1;
sta2 = ali_pam.ChromPam.min_pos2 - 1; en2 = ali_pam.ChromPam.min_pos2 - 1;
cost = ali_pam.ChromPam.sig_k * ali_pam.ChromPam.mat_cost;
direction = `Positive;
seed_ls = [Seed.get_dum_first_seed ali_pam.ChromPam.min_pos1 ali_pam.ChromPam.min_pos2];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let get_dum_last_block ali_pam = {
id = -1;
is_dum = true;
sta1 = ali_pam.ChromPam.max_pos1 + 1; en1 = ali_pam.ChromPam.max_pos1 + 1;
sta2 = ali_pam.ChromPam.max_pos2 + 1; en2 = ali_pam.ChromPam.max_pos2 + 1;
cost = ali_pam.ChromPam.sig_k * ali_pam.ChromPam.mat_cost;
direction = `Positive;
seed_ls = [Seed.get_dum_last_seed ali_pam.ChromPam.max_pos1 ali_pam.ChromPam.max_pos2];
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1;
}
let max_len (b : block_t) =
max (b.en1 - b.sta1 + 1) (b.en2 - b.sta2 + 1)
* [ invert block min_pos2 max_pos2 ] returns [ block ' ]
* which is inverted from [ block ] due to the inversion
* from [ min_pos2 ] to [ max_pos2 ] in the second chromosome
* which is inverted from [block] due to the inversion
* from [min_pos2] to [max_pos2] in the second chromosome *)
let invert (block : block_t) (min_pos2 : int) (max_pos2 : int) =
let new_sta2 = min_pos2 + (max_pos2 - block.en2) in
let new_en2 = min_pos2 + (max_pos2 - block.sta2) in
block.sta2 <- new_sta2;
block.en2 <- new_en2;
(match block.direction with
| `Positive -> block.direction <- `Negative
| _ -> block.direction <- `Positive);
(match block.alied_seq2 with
| None -> ()
| Some seq -> Sequence.reverse_ip seq);
List.iter (fun seed -> Seed.invert min_pos2 max_pos2 seed) block.seed_ls
let get_pos (block : block_t) (order : order_t) =
match order with
| `First -> block.sta1, block.en1
| _ -> block.sta2, block.en2
let cmp_dia_dis (b1 : block_t) (b2 : block_t) =
abs ( (b1.en1 - b1.en2) - (b2.sta1 - b2.sta2) )
let print (block : block_t) =
let dir =
match block.direction with
| `Positive -> 1
| _ -> -1
in
fprintf stdout "id: %i, (%i, %i) <--> (%i, %i) --> len: (%i, %i), "
block.id block.sta1 block.en1
block.sta2 block.en2
(block.en1 - block.sta1 + 1)
(block.en2 - block.sta2 + 1);
fprintf stdout "num_seed: %i, subseq: (%i, %i), cost: %i, direction: %i \n"
(List.length block.seed_ls) block.subseq1_id block.subseq2_id block.cost
dir;
List.iter Seed.print block.seed_ls;
print_endline "-------------------------------------"
let add_seed (block : block_t) (seed : seed_t) =
block.sta1 <- seed.Seed.sta1;
block.sta2 <- seed.Seed.sta2;
block.seed_ls <- seed::block.seed_ls
let cmp_cost_based_seed (block : block_t) (ali_pam : pairChromPam_t) =
let rec cmp (cur_seed : seed_t) (res_ls : seed_t list) (cost : int) =
match res_ls with
| [] -> cost
| next_seed::tail ->
let connecting_cost =
Seed.cmp_connecting_cost cur_seed next_seed ali_pam in
cmp next_seed tail (cost + connecting_cost +
next_seed.Seed.len *ali_pam.ChromPam.mat_cost)
in
let seed_ls = block.seed_ls in
match seed_ls with
| [] -> 0
| first_seed::tail ->
cmp first_seed tail
(first_seed.Seed.len * ali_pam.ChromPam.mat_cost)
* [ create_from_seed_ls block_id seed_ls ali_pam ] returns
* a new block whose ID is [ block_id ] . The new block is
* created from the [ seed_ls ]
* a new block whose ID is [block_id]. The new block is
* created from the [seed_ls] *)
let create_from_seed_ls (block_id : int) (seed_ls : seed_t list)
(ali_pam : pairChromPam_t) =
let head = List.hd seed_ls in
let tail = List.hd (List.rev seed_ls) in
let new_block = {
id = block_id;
is_dum = false;
sta1 = head.Seed.sta1;
sta2 = head.Seed.sta2;
en1 = tail.Seed.sta1 + tail.Seed.len - 1;
en2 = tail.Seed.sta2 + tail.Seed.len - 1;
direction = `Positive;
cost = 0;
seed_ls = seed_ls;
alied_seq1 = None;
alied_seq2 = None;
subseq1_id = -1;
subseq2_id = -1}
in
new_block.cost <- cmp_cost_based_seed new_block ali_pam;
new_block
* [ cmp_ali_cost alied_seq1 alied_seq2 direction ali_pam ] returns
* an integer number as the alignment cost between [ alied_seq1 ]
* and [ alied_seq2 ] based on chromosome parameters [ ali_pam ]
* an integer number as the alignment cost between [alied_seq1]
* and [alied_seq2] based on chromosome parameters [ali_pam] *)
let cmp_ali_cost (alied_seq1 : Sequence.s) (alied_seq2 : Sequence.s)
(direction : direction_t) (ali_pam : pairChromPam_t) =
let len = Sequence.length alied_seq1 in
let code1_arr = Sequence.to_array alied_seq1 in
let code2_arr = Sequence.to_array alied_seq2 in
(if direction = `Negative then Utl.invert_subarr code2_arr 0 (Array.length code2_arr));
let mat_cost = ali_pam.ChromPam.mat_cost in
let mismat_cost = ali_pam.ChromPam.mismat_cost in
let gap_opening_cost = ali_pam.ChromPam.gap_opening_cost in
let gap_ext_cost = ali_pam.ChromPam.gap_ext_cost in
let gap_code = Alphabet.get_gap Alphabet.nucleotides in
let rec count pos cost =
match pos >= len with
| true -> cost
| false ->
match code1_arr.(pos) land code2_arr.(pos) > 0 with
| true -> count (pos + 1) (cost + mat_cost)
| false ->
match (code1_arr.(pos) = gap_code) || (code2_arr.(pos) = gap_code) with
| false -> count (pos + 1) (cost + mismat_cost)
| true ->
if ( (code1_arr.(pos) = gap_code)
&& (code1_arr.(pos - 1) = gap_code) ) ||
( (code2_arr.(pos) = gap_code)
&& (code2_arr.(pos - 1) = gap_code) ) then
count (pos + 1) (cost + gap_ext_cost)
else count (pos + 1) (cost + gap_opening_cost)
in
if len = 0 then 0
else
match code1_arr.(0) = code2_arr.(0) with
| true -> count 1 mat_cost
| false ->
if (code1_arr.(0) = gap_code) || (code2_arr.(0) = gap_code) then
count 1 gap_opening_cost
else count 1 mismat_cost
let find_local_block (seed_ls : seed_t list) (ali_pam : pairChromPam_t) =
let acc_cost_arr, back_arr, sorted_end_seed_arr =
Seed.create_local_connection seed_ls ali_pam in
let num_seed = List.length seed_ls in
let sorted_best_seed_arr = Array.copy sorted_end_seed_arr in
let cmp_seed (seed1 : seed_t) (seed2: seed_t) =
let id1 = seed1.Seed.id in
let id2 = seed2.Seed.id in
compare acc_cost_arr.(id1) acc_cost_arr.(id2)
in
Array.sort cmp_seed sorted_best_seed_arr;
let avail_seed_arr = Array.make num_seed true in
let num_block = ref 0 in
let rev_block_ls = ref [] in
for index = 0 to num_seed - 1 do
let seed = sorted_best_seed_arr.(index) in
let seed_id = seed.Seed.id in
if avail_seed_arr.(seed_id) then
begin
let seed_ls = ref [] in
let rec chase cur_seed_id =
if avail_seed_arr.(cur_seed_id) then
begin
let cur_seed = sorted_end_seed_arr.(cur_seed_id) in
seed_ls := cur_seed::!seed_ls;
avail_seed_arr.(cur_seed_id) <- false;
if back_arr.(cur_seed_id) != -1 then
chase back_arr.(cur_seed_id)
end
in
chase seed_id;
avail_seed_arr.(seed_id) <- false;
let new_block = create_from_seed_ls !num_block !seed_ls ali_pam in
num_block := !num_block + 1;
rev_block_ls := new_block::!rev_block_ls
end
done;
List.rev !rev_block_ls
* [ is_free b sig1_arr sig2_arr ] where
* - b : a block
* - sig1_arr : sig1_arr[i ] = -1 if position i
* in the first chromosome is not yet
* occupied by any block , otherwise occupied
* - sig2_arr : sig2_arr[i ] = -1 if position i
* in the second chromosome is not yet
* occupied by any block , otherwise occupied
* returns true if whole block [ b ] is not occupied , otherwise false
* - b: a block
* - sig1_arr: sig1_arr[i] = -1 if position i
* in the first chromosome is not yet
* occupied by any block, otherwise occupied
* - sig2_arr: sig2_arr[i] = -1 if position i
* in the second chromosome is not yet
* occupied by any block, otherwise occupied
* returns true if whole block [b] is not occupied, otherwise false *)
let is_free (b : block_t) (sig1_arr : int array) (sig2_arr : int array) =
let rec travel sig_arr pos en =
if pos > en then true
else
match sig_arr.(pos) = -1 with
| true -> travel sig_arr (pos + 1) en
| false -> false
in
if travel sig1_arr b.sta1 b.en1 = false then false
else travel sig2_arr b.sta2 b.en2
* [ assign block sig2_ar ] marks all positions
* of [ block ] as occupied position in both genomes
* of [block] as occupied position in both genomes *)
let assign block sig1_arr sig2_arr =
let assign_subseq block_id sig_arr (sta : int) (en : int) =
for pos = sta to en do
sig_arr.(pos) <- block_id
done
in
assign_subseq block.id sig1_arr block.sta1 block.en1;
assign_subseq block.id sig2_arr block.sta2 block.en2
* [ block_ls ali_pam ] returns
* two signiture arrays [ ] and [ sig2_arr ] where
* - sig1_arr[i ] is the block ID covering position i in the first chromosome
* - sig2_arr[i ] is the block ID covering position i in the second chromosome
* two signiture arrays [sig1_arr] and [sig2_arr] where
* - sig1_arr[i] is the block ID covering position i in the first chromosome
* - sig2_arr[i] is the block ID covering position i in the second chromosome *)
let create_sig_arr (block_ls : block_t list) ali_pam =
let _ = List.fold_left
(fun index block -> block.id <- index; index + 1) 0 block_ls in
let sig1_arr = Array.make (ali_pam.ChromPam.max_pos1 + 1) (-1) in
let sig2_arr = Array.make (ali_pam.ChromPam.max_pos2 + 1) (-1) in
List.iter (fun b -> assign b sig1_arr sig2_arr) block_ls;
sig1_arr, sig2_arr
let select_separated_block b_ls ali_pam =
let b_arr = Array.of_list b_ls in
Array.sort (fun b1 b2 ->
let len1 : float = float (max_len b1) in
let len2 : float = float (max_len b2) in
let cost1 = float b1.cost in
let cost2 = float b2.cost in
int_of_float ( len1 *. log(-.cost1) -. len2 *. log(-.cost2) )
) b_arr;
let sig1_arr = Array.make (ali_pam.ChromPam.max_pos1 + 1) (-1) in
let sig2_arr = Array.make (ali_pam.ChromPam.max_pos2 + 1) (-1) in
List.fold_right
(fun b sep_bl_ls ->
match is_free b sig1_arr sig2_arr with
| true ->
assign b sig1_arr sig2_arr;
b::sep_bl_ls
| false -> sep_bl_ls
) (Array.to_list b_arr) []
* [ create_pos_alied_block block seq1 seq2 cost_mat ali_pam ]
* creates the alignment for [ block ] based on its seed_ls
* creates the alignment for [block] based on its seed_ls *)
let create_pos_alied_block (block : block_t) (seq1 : Sequence.s)
(seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m) ali_pam =
let rev_alied_subseq1_ls = ref [] in
let rev_alied_subseq2_ls = ref [] in
let total_ali_cost = ref 0 in
let rec create (pre_seed : seed_t) (cur_map_ls : seed_t list) =
let alied_pre_subseq1, alied_pre_subseq2, pre_cost =
Seed.create_alied_seed pre_seed seq1 seq2 cost_mat in
rev_alied_subseq1_ls := alied_pre_subseq1:: !rev_alied_subseq1_ls;
rev_alied_subseq2_ls := alied_pre_subseq2:: !rev_alied_subseq2_ls;
total_ali_cost := !total_ali_cost + pre_cost;
match cur_map_ls with
| [] -> ()
| head::tail ->
let alied_subseq1, alied_subseq2, cost =
Seed.create_alied_subseq pre_seed head seq1 seq2 cost_mat in
rev_alied_subseq1_ls := alied_subseq1::!rev_alied_subseq1_ls;
rev_alied_subseq2_ls := alied_subseq2::!rev_alied_subseq2_ls;
total_ali_cost := !total_ali_cost + cost;
create head tail
in
create (List.hd block.seed_ls) (List.tl block.seed_ls);
let alied_seq1 = Sequence.concat (List.rev !rev_alied_subseq1_ls) in
let alied_seq2 = Sequence.concat (List.rev !rev_alied_subseq2_ls) in
block.alied_seq1 <- Some alied_seq1;
block.alied_seq2 <- Some alied_seq2;
block.cost <- cmp_ali_cost alied_seq1 alied_seq2 block.direction ali_pam
let is_inside (seed : seed_t) (block : block_t) =
(seed.Seed.sta1 >= block.sta1) &&
(seed.Seed.sta1 + seed.Seed.len - 1 <= block.en1) &&
(seed.Seed.sta2 >= block.sta2) &&
(seed.Seed.sta2 + seed.Seed.len - 1 <= block.en2)
* [ order max_pos subseq_type ] returns
* a list of separated subsequences which are created by
* using blocks as milestones . If order = First , the
* separated is for first chromosome , otherwise the second chromosome
* a list of separated subsequences which are created by
* using blocks as milestones. If order = First,the
* separated subseqs is for first chromosome, otherwise the second chromosome *)
let determine_separated_subseq (block_ls : block_t list) (order : order_t)
(max_pos : int) subseq_type : subseq_t list =
let label_arr = Array.make (max_pos + 2) [] in
let rec create_label (block : block_t) =
if block.is_dum = false then
begin
let sta, en = get_pos block order in
let block_id = block.id in
stdout " % i % i % i " block_id sta en ; print_newline ( ) ;
for pos = sta to en do
label_arr.(pos) <- block_id::label_arr.(pos)
done
end
in
List.iter create_label block_ls;
let rev_sep_subseq_ls = ref [] in
let sta = ref 0 in
let num_sep_subseq = ref 0 in
for pos = 1 to max_pos + 1 do
let create_new_subseq (sta : int) (en : int) =
let new_subseq = {Subseq.id = !num_sep_subseq + 1;
Subseq.sta = sta;
Subseq.en = en;
Subseq.block_id_ls = label_arr.(sta)} in
rev_sep_subseq_ls := new_subseq::!rev_sep_subseq_ls;
num_sep_subseq := !num_sep_subseq + 1;
in
if (pos = max_pos + 1) ||
( (Utl.compare_non_dec_list label_arr.(pos) label_arr.(pos - 1)) = false) then
begin
if ( subseq_type = `Both) ||
( (subseq_type = `Alied) && (label_arr.(!sta) != []) ) ||
( (subseq_type = `Deleted) && (label_arr.(!sta) = []) )
then create_new_subseq !sta (pos - 1);
sta := pos
end
done;
List.rev !rev_sep_subseq_ls
* [ create_alied_block_ls block_ls ali_pam seq1 seq2 cost_mat ]
* creates the alignment for all blocks of [ block_ls ] based on their seed_ls
* creates the alignment for all blocks of [block_ls] based on their seed_ls *)
let create_alied_block_ls (block_ls : block_t list) (ali_pam : pairChromPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) cost_mat =
List.iter
(fun block ->
if block.direction = `Positive then
create_pos_alied_block block seq1 seq2 cost_mat ali_pam
) block_ls;
let min_pos2 = ali_pam.ChromPam.min_pos2 in
let max_pos2 = ali_pam.ChromPam.max_pos2 in
let com_seq2 = Sequence.complement_chrom Alphabet.nucleotides seq2 in
List.iter (fun block ->
if block.direction = `Negative then begin
invert block min_pos2 max_pos2;
create_pos_alied_block block seq1 com_seq2 cost_mat ali_pam;
invert block min_pos2 max_pos2;
end) block_ls
let check_sep_block (sep_block_ls : block_t list) =
let sep_block_arr = Array.of_list sep_block_ls in
let num_block = Array.length sep_block_arr in
for no1 = 0 to num_block - 2 do
for no2 = no1 + 1 to num_block - 1 do
if ((sep_block_arr.(no1).en1 <
sep_block_arr.(no2).sta1) ||
(sep_block_arr.(no2).en1 <
sep_block_arr.(no1).sta1) ) &&
( (sep_block_arr.(no1).en2 <
sep_block_arr.(no2).sta2) ||
(sep_block_arr.(no2).en2 <
sep_block_arr.(no1).sta2) )
then ()
else begin
print sep_block_arr.(no1);
print sep_block_arr.(no2);
failwith "Fucking diving block, they are still overlapped"
end
done
done;
print_endline "All block are separated!!!"
* [ prepen b1 b2 block_pam seq1 seq2 cost_mat ali_pam ] appends
block [ b2 ] to block [ b1 ]
block [b2] to block [b1] *)
let prepen (b1 : block_t) (b2 : block_t) (block_pam : blockPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m)
(ali_pam : pairChromPam_t) =
Block.ml and Seed.ml are with old annotation method , we do n't use them
* anymore . it does n't matter we use_ukk or not
* anymore. it doesn't matter we use_ukk or not*)
let use_ukk = false in
let alied_between_seq1, alied_between_seq2, cost =
Sequence.create_subalign2 seq1 seq2 cost_mat (b1.en1 + 1)
(b2.sta1 - 1) (b1.en2 + 1) (b2.sta2 - 1) use_ukk
in
let between_cost = cmp_ali_cost alied_between_seq1 alied_between_seq2
`Positive ali_pam
in
b2.sta1 <- b1.sta1;
b2.sta2 <- b1.sta2;
b2.cost <- b1.cost + between_cost + b2.cost;
b2.seed_ls <- b1.seed_ls @ b2.seed_ls;
b2.alied_seq1 <- Some (Sequence.concat [ (deref b1.alied_seq1);
alied_between_seq1;
(deref b2.alied_seq1)] );
b2.alied_seq2 <- Some (Sequence.concat [ (deref b1.alied_seq2);
alied_between_seq2;
(deref b2.alied_seq2)] )
* [ connect_pos_consecutive_block block_ls block_pam seq1 seq2 cost_mat ali_pam ]
* connect consecutive positive blocks together to create large blocks . This functions
* returns a concatenated blocks list
* connect consecutive positive blocks together to create large blocks. This functions
* returns a concatenated blocks list *)
let connect_pos_consecutive_block (block_ls : block_t list)
(block_pam : blockPam_t) (seq1 : Sequence.s) (seq2 : Sequence.s)
(cost_mat : Cost_matrix.Two_D.m) (ali_pam : pairChromPam_t) =
let sorted_block_arr = Array.of_list block_ls in
Array.sort (fun b1 b2 -> compare b1.en1 b2.en1) sorted_block_arr;
let _ = Array.fold_left
(fun id b -> b.id <- id; id + 1) 0 sorted_block_arr in
let marker1_set = ref IntSet.empty in
let marker2_set = ref IntSet.empty in
List.iter (fun b -> marker1_set := IntSet.add b.sta1 !marker1_set;
marker1_set := IntSet.add b.en1 !marker1_set;
marker2_set := IntSet.add b.sta2 !marker2_set;
marker2_set := IntSet.add b.en2 !marker2_set
) block_ls;
let marker1_arr = Array.of_list (IntSet.elements !marker1_set) in
let marker2_arr = Array.of_list (IntSet.elements !marker2_set) in
let max_pos1 = ali_pam.ChromPam.max_pos1 in
let max_pos2 = ali_pam.ChromPam.max_pos2 in
let sig1_arr = Array.make (max_pos1 + 1) [] in
let sig2_arr = Array.make (max_pos2 + 1) [] in
List.iter (fun b -> if b.direction = `Positive then
begin
sig1_arr.(b.sta1) <- b.id::sig1_arr.(b.sta1);
sig2_arr.(b.sta2) <- b.id::sig2_arr.(b.sta2);
end) block_ls;
let num_marker1 = Array.length marker1_arr in
let num_marker2 = Array.length marker2_arr in
let do_connection (b : block_t) =
let m1 = Utl.binary_index_search marker1_arr b.en1 in
let m2 = Utl.binary_index_search marker2_arr b.en2 in
if (m1 >= 0) && (m1 + 1 < num_marker1) &&
(m2 >= 0) && (m2 + 1 < num_marker2) then
begin
let e1 = marker1_arr.(m1 + 1) in
let e2 = marker2_arr.(m2 + 1) in
let dis1 = e1 - b.en1 in
let dis2 = e2 - b.en2 in
if (max dis1 dis2 <= block_pam.max_connecting_dis) &&
(abs (dis1 - dis2) <= block_pam.max_connecting_shift) then
begin
let com_block_id_ls = List.filter
(fun id -> List.mem id sig2_arr.(e2) ) sig1_arr.(e1) in
if List.length com_block_id_ls > 0 then
begin
List.iter (fun id -> prepen b sorted_block_arr.(id)
block_pam seq1 seq2 cost_mat ali_pam
) com_block_id_ls;
b.is_dum <- true
end
end
end
in
Array.iter (fun b -> if (b.is_dum = false) && (b.direction = `Positive) then
do_connection b) sorted_block_arr;
let pos_con_block_ls = Array.fold_left
(fun l b -> if b.is_dum then l else b::l) [] sorted_block_arr in
pos_con_block_ls
* [ connect_consecutive_block block_ls block_pam seq1 seq2 cost_mat ali_pam ]
* connect consecutive blocks together to create large blocks . This functions
* returns a concatenated blocks list
* connect consecutive blocks together to create large blocks. This functions
* returns a concatenated blocks list *)
let connect_consecutive_block (block_ls : block_t list) (block_pam : blockPam_t)
(seq1 : Sequence.s) (seq2 : Sequence.s) (cost_mat : Cost_matrix.Two_D.m)
(ali_pam : pairChromPam_t) =
let pos_con_block_ls = connect_pos_consecutive_block block_ls block_pam seq1
seq2 cost_mat ali_pam in
pos_con_block_ls
* [ create_subseq_id subseq_type sep_block_ls ali_pam ] returns
* two lists of separated subsequences for two chromosomes
* which are created by using [ sep_block_ls ] as milestones
* two lists of separated subsequences for two chromosomes
* which are created by using [sep_block_ls] as milestones *)
let create_subseq_id subseq_type (sep_block_ls : block_t list)
(ali_pam : pairChromPam_t) =
let _ = List.fold_left
(fun index block -> block.id <- index; index + 1) 0 sep_block_ls in
let sep_block_arr = Array.of_list sep_block_ls in
let subseq1_ls = determine_separated_subseq sep_block_ls
`First ali_pam.ChromPam.max_pos1 subseq_type in
let subseq2_ls = determine_separated_subseq sep_block_ls
`Second ali_pam.ChromPam.max_pos2 subseq_type in
List.iter (fun subseq -> List.iter
(fun block_id -> sep_block_arr.(block_id).subseq1_id <- subseq.Subseq.id
) subseq.Subseq.block_id_ls) subseq1_ls;
List.iter (fun subseq -> List.iter
(fun block_id -> sep_block_arr.(block_id).subseq2_id <- subseq.Subseq.id
) subseq.Subseq.block_id_ls) subseq2_ls;
sep_block_ls, subseq1_ls, subseq2_ls
let create_median ?(approx=`BothSeq) (block : block_t) cost_mat =
let alied_seq1 = Utl.deref block.alied_seq1 in
let alied_seq2 = Utl.deref block.alied_seq2 in
match block.direction = `Positive with
| true -> Sequence.create_median_seq ~approx:approx alied_seq1 alied_seq2 cost_mat
| false ->
Sequence.reverse_ip alied_seq2;
let med, cost = Sequence.create_median_seq ~approx:approx alied_seq1 alied_seq2 cost_mat in
Sequence.reverse_ip alied_seq2;
med, cost
* [ find_block block_ls subseq1_id subseq2_id ] returns
* the blocks whose subseq ids are [ subseq1_id ] and [ subseq2_id ]
* the blocks whose subseq ids are [subseq1_id] and [subseq2_id] *)
let find_block block_ls subseq1_id subseq2_id =
let rec check cur_block_ls =
match cur_block_ls with
| [] -> None
| hd::tl ->
if (hd.subseq1_id = subseq1_id)
&& (hd.subseq2_id = subseq2_id) then Some hd
else check tl
in
check block_ls
* [ find_subseq1 block_ls subseq1_id ] return the
* of the block whose is [ subseq1_id ]
* of the block whose subseq1 is [subseq1_id] *)
let find_subseq1 block_ls subseq1_id =
let rec check cur_block_ls =
match cur_block_ls with
| [] -> None
| hd::tl ->
if (hd.subseq1_id = subseq1_id) then Some hd
else check tl
in
check block_ls
|
c74122348fad7b42e3ccdf5caa24671e820124772d25c69f8f1becae88bde072 | pa-ba/compdata-param | Term.hs | # LANGUAGE EmptyDataDecls , GADTs , KindSignatures , ,
MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
--------------------------------------------------------------------------------
-- |
Module : Data . Comp . . Term
Copyright : ( c ) 2011 ,
-- License : BSD3
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC Extensions )
--
-- This module defines the central notion of /parametrised terms/ and their
-- generalisation to parametrised contexts.
--
--------------------------------------------------------------------------------
module Data.Comp.Param.Term
(
Cxt(..),
Hole,
NoHole,
Term(..),
Trm,
Context,
simpCxt,
toCxt,
cxtMap,
ParamFunctor(..)
) where
import Prelude hiding (mapM, sequence, foldl, foldl1, foldr, foldr1)
import Data.Comp.Param.Difunctor
import Unsafe.Coerce (unsafeCoerce)
import Data.Maybe (fromJust)
| This data type represents contexts over a signature . Contexts are terms
containing zero or more holes , and zero or more parameters . The first
parameter is a phantom type indicating whether the context has holes . The
second paramater is the signature of the context , in the form of a
" Data . Comp . . " . The third parameter is the type of parameters ,
and the fourth parameter is the type of holes .
containing zero or more holes, and zero or more parameters. The first
parameter is a phantom type indicating whether the context has holes. The
second paramater is the signature of the context, in the form of a
"Data.Comp.Param.Difunctor". The third parameter is the type of parameters,
and the fourth parameter is the type of holes. -}
data Cxt :: * -> (* -> * -> *) -> * -> * -> * where
In :: f a (Cxt h f a b) -> Cxt h f a b
Hole :: b -> Cxt Hole f a b
Var :: a -> Cxt h f a b
{-| Phantom type used to define 'Context'. -}
data Hole
{-| Phantom type used to define 'Term'. -}
data NoHole
{-| A context may contain holes. -}
type Context = Cxt Hole
{-| \"Preterms\" -}
type Trm f a = Cxt NoHole f a ()
{-| A term is a context with no holes, where all occurrences of the
contravariant parameter is fully parametric. -}
newtype Term f = Term{unTerm :: forall a. Trm f a}
{-| Convert a difunctorial value into a context. -}
simpCxt :: Difunctor f => f a b -> Cxt Hole f a b
# INLINE simpCxt #
simpCxt = In . difmap Hole
toCxt :: Difunctor f => Trm f a -> Cxt h f a b
{-# INLINE toCxt #-}
toCxt = unsafeCoerce
-- | This combinator maps a function over a context by applying the
-- function to each hole.
cxtMap :: Difunctor f => (b -> c) -> Context f a b -> Context f a c
cxtMap f (Hole x) = Hole (f x)
cxtMap _ (Var x) = Var x
cxtMap f (In t) = In (dimap id (cxtMap f) t)
| Monads for which embedded @Trm@ values , which are parametric at top level ,
can be made into monadic @Term@ values , i.e. \"pushing the parametricity
inwards\ " .
can be made into monadic @Term@ values, i.e. \"pushing the parametricity
inwards\". -}
class ParamFunctor m where
termM :: (forall a. m (Trm f a)) -> m (Term f)
coerceTermM :: ParamFunctor m => (forall a. m (Trm f a)) -> m (Term f)
# INLINE coerceTermM #
coerceTermM t = unsafeCoerce t
# RULES
" termM / coerce " termM = coerceTermM
#
"termM/coerce" termM = coerceTermM
#-}
instance ParamFunctor Maybe where
# NOINLINE [ 1 ] termM #
termM Nothing = Nothing
termM x = Just (Term $ fromJust x)
instance ParamFunctor (Either a) where
# NOINLINE [ 1 ] termM #
termM (Left x) = Left x
termM x = Right (Term $ fromRight x)
where fromRight :: Either a b -> b
fromRight (Right x) = x
fromRight _ = error "fromRight: Left"
instance ParamFunctor [] where
# NOINLINE [ 1 ] termM #
termM [] = []
termM l = Term (head l) : termM (tail l)
| null | https://raw.githubusercontent.com/pa-ba/compdata-param/5d6b0afa95a27fd3233f86e5efc6e6a6080f4236/src/Data/Comp/Param/Term.hs | haskell | ------------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
This module defines the central notion of /parametrised terms/ and their
generalisation to parametrised contexts.
------------------------------------------------------------------------------
| Phantom type used to define 'Context'.
| Phantom type used to define 'Term'.
| A context may contain holes.
| \"Preterms\"
| A term is a context with no holes, where all occurrences of the
contravariant parameter is fully parametric.
| Convert a difunctorial value into a context.
# INLINE toCxt #
| This combinator maps a function over a context by applying the
function to each hole. | # LANGUAGE EmptyDataDecls , GADTs , KindSignatures , ,
MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
Module : Data . Comp . . Term
Copyright : ( c ) 2011 ,
Maintainer : < >
Portability : non - portable ( GHC Extensions )
module Data.Comp.Param.Term
(
Cxt(..),
Hole,
NoHole,
Term(..),
Trm,
Context,
simpCxt,
toCxt,
cxtMap,
ParamFunctor(..)
) where
import Prelude hiding (mapM, sequence, foldl, foldl1, foldr, foldr1)
import Data.Comp.Param.Difunctor
import Unsafe.Coerce (unsafeCoerce)
import Data.Maybe (fromJust)
| This data type represents contexts over a signature . Contexts are terms
containing zero or more holes , and zero or more parameters . The first
parameter is a phantom type indicating whether the context has holes . The
second paramater is the signature of the context , in the form of a
" Data . Comp . . " . The third parameter is the type of parameters ,
and the fourth parameter is the type of holes .
containing zero or more holes, and zero or more parameters. The first
parameter is a phantom type indicating whether the context has holes. The
second paramater is the signature of the context, in the form of a
"Data.Comp.Param.Difunctor". The third parameter is the type of parameters,
and the fourth parameter is the type of holes. -}
data Cxt :: * -> (* -> * -> *) -> * -> * -> * where
In :: f a (Cxt h f a b) -> Cxt h f a b
Hole :: b -> Cxt Hole f a b
Var :: a -> Cxt h f a b
data Hole
data NoHole
type Context = Cxt Hole
type Trm f a = Cxt NoHole f a ()
newtype Term f = Term{unTerm :: forall a. Trm f a}
simpCxt :: Difunctor f => f a b -> Cxt Hole f a b
# INLINE simpCxt #
simpCxt = In . difmap Hole
toCxt :: Difunctor f => Trm f a -> Cxt h f a b
toCxt = unsafeCoerce
cxtMap :: Difunctor f => (b -> c) -> Context f a b -> Context f a c
cxtMap f (Hole x) = Hole (f x)
cxtMap _ (Var x) = Var x
cxtMap f (In t) = In (dimap id (cxtMap f) t)
| Monads for which embedded @Trm@ values , which are parametric at top level ,
can be made into monadic @Term@ values , i.e. \"pushing the parametricity
inwards\ " .
can be made into monadic @Term@ values, i.e. \"pushing the parametricity
inwards\". -}
class ParamFunctor m where
termM :: (forall a. m (Trm f a)) -> m (Term f)
coerceTermM :: ParamFunctor m => (forall a. m (Trm f a)) -> m (Term f)
# INLINE coerceTermM #
coerceTermM t = unsafeCoerce t
# RULES
" termM / coerce " termM = coerceTermM
#
"termM/coerce" termM = coerceTermM
#-}
instance ParamFunctor Maybe where
# NOINLINE [ 1 ] termM #
termM Nothing = Nothing
termM x = Just (Term $ fromJust x)
instance ParamFunctor (Either a) where
# NOINLINE [ 1 ] termM #
termM (Left x) = Left x
termM x = Right (Term $ fromRight x)
where fromRight :: Either a b -> b
fromRight (Right x) = x
fromRight _ = error "fromRight: Left"
instance ParamFunctor [] where
# NOINLINE [ 1 ] termM #
termM [] = []
termM l = Term (head l) : termM (tail l)
|
f764b3096e3d6b0a6bf4463b17e3fc5b152989bedbddd674e456a01b0405a9dd | Elzair/nazghul | treasury.scm | (mk-dungeon-room
'p_treasury2 "Lost Treasury of Luximene"
(list
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx ,T ,R ,E ,A ,S ,U ,R ,Y @@ xx xx xx xx xx "
"xx xx xx xx xx @@ @@ @@ ,O @@ ,F @@ @@ @@ xx xx xx xx xx "
"xx xx xx xx xx @@ ,L ,U ,X ,I ,M ,E ,N ,E xx xx xx xx xx "
"xx xx xx xx xx cc cc cc ,, cc ,, cc cc cc xx xx xx xx xx "
"xx xx xx xx xx cc pp ,, ,, ,, ,, ,, pp cc xx xx xx xx xx "
"xx xx xx xx xx cc ,, ,, ,, cc ,, ,, ,, cc xx xx xx xx xx "
"xx xx xx xx xx ,, ,, ,, cc cc cc ,, ,, ,, xx xx xx xx xx "
"xx xx xx xx xx ,, ,, cc cc ,, cc cc ,, ,, xx xx xx xx xx "
"xx xx xx xx xx ,, ,, ,, cc cc cc ,, ,, ,, xx xx xx xx xx "
"xx xx xx xx xx xx ,, ,, ,, cc ,, ,, ,, xx xx xx xx xx xx "
"xx xx xx xx xx xx xx ,, ,, ,, ,, ,, xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx ,, ,, ,, xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
)
(put (mk-ladder-down 'p_treasury 9 9) 9 9)
;; special treasures
(put (mk-chest
'bomb-trap
'((1 t_eldritch_blade)
(1 t_armor_plate_4)
(1 t_iron_helm_4)
(1 t_doom_staff)
(1 t_spell_book_force_magick_high_magick)
(1 t_spell_book_gate_magick)
(1 t_spell_book_illusion_2)
))
9 5)
)
(mk-place-music p_treasury2 'ml-dungeon-adventure)
(define (can-drop? loc)
(and (is-floor? loc)
(loc-is-empty? loc)))
;; piles of gold
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (kern-mk-obj t_gold_coins (kern-dice-roll "5d20")) loc))
20)
;; random mundane treasures
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (mk-treasure-chest) loc))
5)
;; some gems to add sparkle
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (kern-mk-obj t_gem 1) loc))
10)
;; a couple of corpses
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (mk-corpse-with-loot)
loc))
3)
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/treasury.scm | scheme | special treasures
piles of gold
random mundane treasures
some gems to add sparkle
a couple of corpses | (mk-dungeon-room
'p_treasury2 "Lost Treasury of Luximene"
(list
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx ,T ,R ,E ,A ,S ,U ,R ,Y @@ xx xx xx xx xx "
"xx xx xx xx xx @@ @@ @@ ,O @@ ,F @@ @@ @@ xx xx xx xx xx "
"xx xx xx xx xx @@ ,L ,U ,X ,I ,M ,E ,N ,E xx xx xx xx xx "
"xx xx xx xx xx cc cc cc ,, cc ,, cc cc cc xx xx xx xx xx "
"xx xx xx xx xx cc pp ,, ,, ,, ,, ,, pp cc xx xx xx xx xx "
"xx xx xx xx xx cc ,, ,, ,, cc ,, ,, ,, cc xx xx xx xx xx "
"xx xx xx xx xx ,, ,, ,, cc cc cc ,, ,, ,, xx xx xx xx xx "
"xx xx xx xx xx ,, ,, cc cc ,, cc cc ,, ,, xx xx xx xx xx "
"xx xx xx xx xx ,, ,, ,, cc cc cc ,, ,, ,, xx xx xx xx xx "
"xx xx xx xx xx xx ,, ,, ,, cc ,, ,, ,, xx xx xx xx xx xx "
"xx xx xx xx xx xx xx ,, ,, ,, ,, ,, xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx ,, ,, ,, xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
"xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx "
)
(put (mk-ladder-down 'p_treasury 9 9) 9 9)
(put (mk-chest
'bomb-trap
'((1 t_eldritch_blade)
(1 t_armor_plate_4)
(1 t_iron_helm_4)
(1 t_doom_staff)
(1 t_spell_book_force_magick_high_magick)
(1 t_spell_book_gate_magick)
(1 t_spell_book_illusion_2)
))
9 5)
)
(mk-place-music p_treasury2 'ml-dungeon-adventure)
(define (can-drop? loc)
(and (is-floor? loc)
(loc-is-empty? loc)))
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (kern-mk-obj t_gold_coins (kern-dice-roll "5d20")) loc))
20)
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (mk-treasure-chest) loc))
5)
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (kern-mk-obj t_gem 1) loc))
10)
(put-random-stuff p_treasury2
(mk-rect 5 5 9 9)
can-drop?
(lambda (loc)
(kern-obj-put-at (mk-corpse-with-loot)
loc))
3)
|
dc41ec1a3806b3f8ee3fbd100f41cc267a52969ca8869d1c018854bd62210917 | phadej/cabal-fmt | ExpandExposedModules.hs | -- |
-- License: GPL-3.0-or-later
Copyright :
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# OPTIONS_GHC -Wno - deprecations #
module CabalFmt.Refactoring.ExpandExposedModules (
refactoringExpandExposedModules,
) where
import qualified Distribution.Fields as C
import qualified Distribution.ModuleName as C
import CabalFmt.Prelude
import CabalFmt.Monad
import CabalFmt.Pragma
import CabalFmt.Refactoring.Type
refactoringExpandExposedModules :: FieldRefactoring
refactoringExpandExposedModules C.Section {} = pure Nothing
refactoringExpandExposedModules (C.Field name@(C.Name (_, pragmas) _n) fls) = do
dirs <- parse pragmas
files <- traverseOf (traverse . _1) getFiles dirs
let newModules :: [C.FieldLine CommentsPragmas]
newModules = catMaybes
[ return $ C.FieldLine mempty $ toUTF8BS $ intercalate "." parts
| (files', mns) <- files
, file <- files'
, let parts = splitDirectories $ dropExtension file
, all C.validModuleComponent parts
, let mn = C.fromComponents parts -- TODO: don't use fromComponents
, mn `notElem` mns
]
pure $ case newModules of
[] -> Nothing
_ -> Just (C.Field name (newModules ++ fls))
where
parse :: MonadCabalFmt r m => [FieldPragma] -> m [(FilePath, [C.ModuleName])]
parse = fmap mconcat . traverse go where
go (PragmaExpandModules fp mns) = return [ (fp, mns) ]
go p = do
displayWarning $ "Skipped pragma " ++ show p
return []
| null | https://raw.githubusercontent.com/phadej/cabal-fmt/f64e495b1a29f5d72f9b60ca313f854db3af33dc/src/CabalFmt/Refactoring/ExpandExposedModules.hs | haskell | |
License: GPL-3.0-or-later
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
TODO: don't use fromComponents | Copyright :
# OPTIONS_GHC -Wno - deprecations #
module CabalFmt.Refactoring.ExpandExposedModules (
refactoringExpandExposedModules,
) where
import qualified Distribution.Fields as C
import qualified Distribution.ModuleName as C
import CabalFmt.Prelude
import CabalFmt.Monad
import CabalFmt.Pragma
import CabalFmt.Refactoring.Type
refactoringExpandExposedModules :: FieldRefactoring
refactoringExpandExposedModules C.Section {} = pure Nothing
refactoringExpandExposedModules (C.Field name@(C.Name (_, pragmas) _n) fls) = do
dirs <- parse pragmas
files <- traverseOf (traverse . _1) getFiles dirs
let newModules :: [C.FieldLine CommentsPragmas]
newModules = catMaybes
[ return $ C.FieldLine mempty $ toUTF8BS $ intercalate "." parts
| (files', mns) <- files
, file <- files'
, let parts = splitDirectories $ dropExtension file
, all C.validModuleComponent parts
, mn `notElem` mns
]
pure $ case newModules of
[] -> Nothing
_ -> Just (C.Field name (newModules ++ fls))
where
parse :: MonadCabalFmt r m => [FieldPragma] -> m [(FilePath, [C.ModuleName])]
parse = fmap mconcat . traverse go where
go (PragmaExpandModules fp mns) = return [ (fp, mns) ]
go p = do
displayWarning $ "Skipped pragma " ++ show p
return []
|
79ec4ff2c0e4b54ff1fa87dcfdad72d65dfe34cee57f159efcea8f1fa2bef098 | liaopeiyuan/zeta | tensor.mli | type op =
| IntOp : (int -> int) -> op
| BoolOp : (bool -> bool) -> op
| FloatOp : (float -> float) -> op
type predicate =
| IntP : (int -> bool) -> predicate
| BoolP : (bool -> bool) -> predicate
| FloatP : (float -> bool) -> predicate
type 'a tensordata =
| IntScalar : int ref -> int tensordata
| FloatScalar : float ref -> float tensordata
| BoolScalar : bool ref -> bool tensordata
| IntTensor : int tensordata array -> int tensordata
| FloatTensor : float tensordata array -> float tensordata
| BoolTensor : bool tensordata array -> bool tensordata
type shape = int array
type index_selection = Range of (int * int) | Index of int | All
and slice = index_selection array
type index = int array
type 'a grad_fn = End | Fn of ('a tensor * op) array
and 'a gradient = Retain of bool | Grad of (bool * 'a tensordata)
and 'a parent = 'a tensor array
and 'a node = LeafNoGrad | LeafGrad of 'a gradient | Node of ('a parent * 'a gradient)
and 'a directed_acyclic_graph = Null | Graph of ('a grad_fn * 'a node)
and 'a tensor = (shape * 'a tensordata * 'a directed_acyclic_graph ) ref
exception TypeMismatch of string
exception TensorInvariantViolated
exception ShapeMismatch of string
exception IndexError of string
exception ZeroDimension
exception AutogradError of string
val is_leaf : 'a tensor -> bool
val requires_grad : 'a tensor -> bool -> unit
val retain_grad : 'a tensor -> bool -> unit
val detach : 'a tensor -> 'a tensor
val copy : ('a * 'b tensordata * 'c) ref -> ('a * 'b tensordata * 'c) ref
val slice : slice -> 'a tensor -> 'a tensor
val new_bool : shape -> bool -> bool tensor
val new_int : shape -> int -> int tensor
val new_float : shape -> float -> float tensor
val reduce : predicate -> (bool * bool -> bool) -> bool -> 'a tensor -> bool
val all : predicate -> 'a tensor -> bool
val any : predicate -> 'a tensor -> bool
val elem_apply : op -> 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val sigmoid : 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val abs : 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val new_t : shape -> 'a tensor -> bool -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val set : 'a tensor -> int array -> 'a -> unit
val get : 'a tensor -> int array -> 'a
val broadcast : (int array * 'a tensordata * 'b) ref -> int array -> bool -> (int array * 'a tensordata * 'b) ref
val (#*) : 'a tensor -> 'a tensor -> 'a tensor
| null | https://raw.githubusercontent.com/liaopeiyuan/zeta/2577721f81beff7d4d3a64ce027d20cd0e8c58aa/src/tensor.mli | ocaml | type op =
| IntOp : (int -> int) -> op
| BoolOp : (bool -> bool) -> op
| FloatOp : (float -> float) -> op
type predicate =
| IntP : (int -> bool) -> predicate
| BoolP : (bool -> bool) -> predicate
| FloatP : (float -> bool) -> predicate
type 'a tensordata =
| IntScalar : int ref -> int tensordata
| FloatScalar : float ref -> float tensordata
| BoolScalar : bool ref -> bool tensordata
| IntTensor : int tensordata array -> int tensordata
| FloatTensor : float tensordata array -> float tensordata
| BoolTensor : bool tensordata array -> bool tensordata
type shape = int array
type index_selection = Range of (int * int) | Index of int | All
and slice = index_selection array
type index = int array
type 'a grad_fn = End | Fn of ('a tensor * op) array
and 'a gradient = Retain of bool | Grad of (bool * 'a tensordata)
and 'a parent = 'a tensor array
and 'a node = LeafNoGrad | LeafGrad of 'a gradient | Node of ('a parent * 'a gradient)
and 'a directed_acyclic_graph = Null | Graph of ('a grad_fn * 'a node)
and 'a tensor = (shape * 'a tensordata * 'a directed_acyclic_graph ) ref
exception TypeMismatch of string
exception TensorInvariantViolated
exception ShapeMismatch of string
exception IndexError of string
exception ZeroDimension
exception AutogradError of string
val is_leaf : 'a tensor -> bool
val requires_grad : 'a tensor -> bool -> unit
val retain_grad : 'a tensor -> bool -> unit
val detach : 'a tensor -> 'a tensor
val copy : ('a * 'b tensordata * 'c) ref -> ('a * 'b tensordata * 'c) ref
val slice : slice -> 'a tensor -> 'a tensor
val new_bool : shape -> bool -> bool tensor
val new_int : shape -> int -> int tensor
val new_float : shape -> float -> float tensor
val reduce : predicate -> (bool * bool -> bool) -> bool -> 'a tensor -> bool
val all : predicate -> 'a tensor -> bool
val any : predicate -> 'a tensor -> bool
val elem_apply : op -> 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val sigmoid : 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val abs : 'a tensor -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val new_t : shape -> 'a tensor -> bool -> (shape * 'a tensordata * 'a directed_acyclic_graph) ref
val set : 'a tensor -> int array -> 'a -> unit
val get : 'a tensor -> int array -> 'a
val broadcast : (int array * 'a tensordata * 'b) ref -> int array -> bool -> (int array * 'a tensordata * 'b) ref
val (#*) : 'a tensor -> 'a tensor -> 'a tensor
| |
786ffff4a367fc759c814dfd9f37278e784ad0cffb761c5fa174b1db7606ffbb | tanakh/ICFP2011 | LTG.hs | {-# OPTIONS -Wall #-}
module LTG(Card(..), cards, right, left, ($<), ($>), (#)) where
import Data.Text (Text, pack)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Vector (Vector, fromList)
import System.IO
infixl 3 #
(#) :: Text -> Text -> Text
(#) = T.append
data Card = I | Zero | Succ | Dbl | Get | Put | S | K | Inc | Dec | Attack | Help | Copy | Revive | Zombie
cards :: Vector Card
cards = fromList [I , Zero , Succ , Dbl , Get , Put , S , K , Inc , Dec , Attack , Help , Copy , Revive , Zombie]
cardName :: Card -> Text
cardName I = pack "I"
cardName Zero = pack "zero"
cardName Succ = pack "succ"
cardName Dbl = pack "dbl"
cardName Get = pack "get"
cardName Put = pack "put"
cardName S = pack "S"
cardName K = pack "K"
cardName Inc = pack "inc"
cardName Dec = pack "dec"
cardName Attack = pack "attack"
cardName Help = pack "help"
cardName Copy = pack "copy"
cardName Revive = pack "revive"
cardName Zombie = pack "zombie"
infix 1 $<
infix 1 $>
right, ($<) :: Int -> Card -> IO ()
right s c = do
T.putStr $ T.unlines [pack "2", pack (show s), cardName c]
hFlush stdout
($<) = right
left, ($>) :: Card -> Int -> IO ()
left c s = do
T.putStr $ T.unlines [pack "1", cardName c, pack (show s)]
hFlush stdout
($>) = left
| null | https://raw.githubusercontent.com/tanakh/ICFP2011/db0d670cdbe12e9cef4242d6ab202a98c254412e/nushio/LTG.hs | haskell | # OPTIONS -Wall # | module LTG(Card(..), cards, right, left, ($<), ($>), (#)) where
import Data.Text (Text, pack)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Vector (Vector, fromList)
import System.IO
infixl 3 #
(#) :: Text -> Text -> Text
(#) = T.append
data Card = I | Zero | Succ | Dbl | Get | Put | S | K | Inc | Dec | Attack | Help | Copy | Revive | Zombie
cards :: Vector Card
cards = fromList [I , Zero , Succ , Dbl , Get , Put , S , K , Inc , Dec , Attack , Help , Copy , Revive , Zombie]
cardName :: Card -> Text
cardName I = pack "I"
cardName Zero = pack "zero"
cardName Succ = pack "succ"
cardName Dbl = pack "dbl"
cardName Get = pack "get"
cardName Put = pack "put"
cardName S = pack "S"
cardName K = pack "K"
cardName Inc = pack "inc"
cardName Dec = pack "dec"
cardName Attack = pack "attack"
cardName Help = pack "help"
cardName Copy = pack "copy"
cardName Revive = pack "revive"
cardName Zombie = pack "zombie"
infix 1 $<
infix 1 $>
right, ($<) :: Int -> Card -> IO ()
right s c = do
T.putStr $ T.unlines [pack "2", pack (show s), cardName c]
hFlush stdout
($<) = right
left, ($>) :: Card -> Int -> IO ()
left c s = do
T.putStr $ T.unlines [pack "1", cardName c, pack (show s)]
hFlush stdout
($>) = left
|
104cb4fc80b15bef71ba14620b216cbb49e93e16ef8d351b91c9839dd65838fd | binaryage/chromex | processes.clj | (ns chromex.ext.processes
"Use the chrome.processes API to interact with the browser's
processes.
* available since Chrome 87
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-process-id-for-tab
"Returns the ID of the renderer process for the specified tab.
|tab-id| - The ID of the tab for which the renderer process ID is to be returned.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [process-id] where:
|process-id| - Process ID of the tab's renderer process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getProcessIdForTab."
([tab-id] (gen-call :function ::get-process-id-for-tab &form tab-id)))
(defmacro terminate
"Terminates the specified renderer process. Equivalent to visiting about:crash, but without changing the tab's URL.
|process-id| - The ID of the process to be terminated.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [did-terminate] where:
|did-terminate| - True if terminating the process was successful, and false otherwise.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-terminate."
([process-id] (gen-call :function ::terminate &form process-id)))
(defmacro get-process-info
"Retrieves the process information for each process ID specified.
|process-ids| - The list of process IDs or single process ID for which to return the process information. An empty list
indicates all processes are requested.
|include-memory| - True if detailed memory usage is required. Note, collecting memory usage information incurs extra
CPU usage and should only be queried for when needed.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [processes] where:
|processes| - A dictionary of 'Process' objects for each requested process that is a live child process of the current
browser process, indexed by process ID. Metrics requiring aggregation over time will not be populated in
each Process object.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getProcessInfo."
([process-ids include-memory] (gen-call :function ::get-process-info &form process-ids include-memory)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-updated-events
"Fired each time the Task Manager updates its process statistics, providing the dictionary of updated Process objects,
indexed by process ID.
Events will be put on the |channel| with signature [::on-updated [processes]] where:
|processes| - A dictionary of updated 'Process' objects for each live process in the browser, indexed by process ID.
Metrics requiring aggregation over time will be populated in each Process object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUpdated."
([channel & args] (apply gen-call :event ::on-updated &form channel args)))
(defmacro tap-on-updated-with-memory-events
"Fired each time the Task Manager updates its process statistics, providing the dictionary of updated Process objects,
indexed by process ID. Identical to onUpdate, with the addition of memory usage details included in each Process object.
Note, collecting memory usage information incurs extra CPU usage and should only be listened for when needed.
Events will be put on the |channel| with signature [::on-updated-with-memory [processes]] where:
|processes| - A dictionary of updated 'Process' objects for each live process in the browser, indexed by process ID.
Memory usage details will be included in each Process object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUpdatedWithMemory."
([channel & args] (apply gen-call :event ::on-updated-with-memory &form channel args)))
(defmacro tap-on-created-events
"Fired each time a process is created, providing the corrseponding Process object.
Events will be put on the |channel| with signature [::on-created [process]] where:
|process| - Details of the process that was created. Metrics requiring aggregation over time will not be populated in the
object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onCreated."
([channel & args] (apply gen-call :event ::on-created &form channel args)))
(defmacro tap-on-unresponsive-events
"Fired each time a process becomes unresponsive, providing the corrseponding Process object.
Events will be put on the |channel| with signature [::on-unresponsive [process]] where:
|process| - Details of the unresponsive process. Metrics requiring aggregation over time will not be populated in the
object. Only available for renderer processes.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUnresponsive."
([channel & args] (apply gen-call :event ::on-unresponsive &form channel args)))
(defmacro tap-on-exited-events
"Fired each time a process is terminated, providing the type of exit.
Events will be put on the |channel| with signature [::on-exited [process-id exit-type exit-code]] where:
|process-id| - The ID of the process that exited.
|exit-type| - The type of exit that occurred for the process - normal, abnormal, killed, crashed. Only available for
renderer processes.
|exit-code| - The exit code if the process exited abnormally. Only available for renderer processes.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onExited."
([channel & args] (apply gen-call :event ::on-exited &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.processes namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.processes",
:since "87",
:functions
[{:id ::get-process-id-for-tab,
:name "getProcessIdForTab",
:callback? true,
:params
[{:name "tab-id", :type "integer"}
{:name "callback", :type :callback, :callback {:params [{:name "process-id", :type "integer"}]}}]}
{:id ::terminate,
:name "terminate",
:callback? true,
:params
[{:name "process-id", :type "integer"}
{:name "callback",
:optional? true,
:type :callback,
:callback {:params [{:name "did-terminate", :type "boolean"}]}}]}
{:id ::get-process-info,
:name "getProcessInfo",
:callback? true,
:params
[{:name "process-ids", :type "integer-or-[array-of-integers]"}
{:name "include-memory", :type "boolean"}
{:name "callback", :type :callback, :callback {:params [{:name "processes", :type "object"}]}}]}],
:events
[{:id ::on-updated, :name "onUpdated", :params [{:name "processes", :type "object"}]}
{:id ::on-updated-with-memory, :name "onUpdatedWithMemory", :params [{:name "processes", :type "object"}]}
{:id ::on-created, :name "onCreated", :params [{:name "process", :type "processes.Process"}]}
{:id ::on-unresponsive, :name "onUnresponsive", :params [{:name "process", :type "processes.Process"}]}
{:id ::on-exited,
:name "onExited",
:params
[{:name "process-id", :type "integer"}
{:name "exit-type", :type "integer"}
{:name "exit-code", :type "integer"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts/chromex/ext/processes.clj | clojure | -- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.ext.processes
"Use the chrome.processes API to interact with the browser's
processes.
* available since Chrome 87
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-process-id-for-tab
"Returns the ID of the renderer process for the specified tab.
|tab-id| - The ID of the tab for which the renderer process ID is to be returned.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [process-id] where:
|process-id| - Process ID of the tab's renderer process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getProcessIdForTab."
([tab-id] (gen-call :function ::get-process-id-for-tab &form tab-id)))
(defmacro terminate
"Terminates the specified renderer process. Equivalent to visiting about:crash, but without changing the tab's URL.
|process-id| - The ID of the process to be terminated.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [did-terminate] where:
|did-terminate| - True if terminating the process was successful, and false otherwise.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-terminate."
([process-id] (gen-call :function ::terminate &form process-id)))
(defmacro get-process-info
"Retrieves the process information for each process ID specified.
|process-ids| - The list of process IDs or single process ID for which to return the process information. An empty list
indicates all processes are requested.
|include-memory| - True if detailed memory usage is required. Note, collecting memory usage information incurs extra
CPU usage and should only be queried for when needed.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [processes] where:
|processes| - A dictionary of 'Process' objects for each requested process that is a live child process of the current
browser process, indexed by process ID. Metrics requiring aggregation over time will not be populated in
each Process object.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getProcessInfo."
([process-ids include-memory] (gen-call :function ::get-process-info &form process-ids include-memory)))
(defmacro tap-on-updated-events
"Fired each time the Task Manager updates its process statistics, providing the dictionary of updated Process objects,
indexed by process ID.
Events will be put on the |channel| with signature [::on-updated [processes]] where:
|processes| - A dictionary of updated 'Process' objects for each live process in the browser, indexed by process ID.
Metrics requiring aggregation over time will be populated in each Process object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUpdated."
([channel & args] (apply gen-call :event ::on-updated &form channel args)))
(defmacro tap-on-updated-with-memory-events
"Fired each time the Task Manager updates its process statistics, providing the dictionary of updated Process objects,
indexed by process ID. Identical to onUpdate, with the addition of memory usage details included in each Process object.
Note, collecting memory usage information incurs extra CPU usage and should only be listened for when needed.
Events will be put on the |channel| with signature [::on-updated-with-memory [processes]] where:
|processes| - A dictionary of updated 'Process' objects for each live process in the browser, indexed by process ID.
Memory usage details will be included in each Process object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUpdatedWithMemory."
([channel & args] (apply gen-call :event ::on-updated-with-memory &form channel args)))
(defmacro tap-on-created-events
"Fired each time a process is created, providing the corrseponding Process object.
Events will be put on the |channel| with signature [::on-created [process]] where:
|process| - Details of the process that was created. Metrics requiring aggregation over time will not be populated in the
object.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onCreated."
([channel & args] (apply gen-call :event ::on-created &form channel args)))
(defmacro tap-on-unresponsive-events
"Fired each time a process becomes unresponsive, providing the corrseponding Process object.
Events will be put on the |channel| with signature [::on-unresponsive [process]] where:
|process| - Details of the unresponsive process. Metrics requiring aggregation over time will not be populated in the
object. Only available for renderer processes.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onUnresponsive."
([channel & args] (apply gen-call :event ::on-unresponsive &form channel args)))
(defmacro tap-on-exited-events
"Fired each time a process is terminated, providing the type of exit.
Events will be put on the |channel| with signature [::on-exited [process-id exit-type exit-code]] where:
|process-id| - The ID of the process that exited.
|exit-type| - The type of exit that occurred for the process - normal, abnormal, killed, crashed. Only available for
renderer processes.
|exit-code| - The exit code if the process exited abnormally. Only available for renderer processes.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onExited."
([channel & args] (apply gen-call :event ::on-exited &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.processes namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.processes",
:since "87",
:functions
[{:id ::get-process-id-for-tab,
:name "getProcessIdForTab",
:callback? true,
:params
[{:name "tab-id", :type "integer"}
{:name "callback", :type :callback, :callback {:params [{:name "process-id", :type "integer"}]}}]}
{:id ::terminate,
:name "terminate",
:callback? true,
:params
[{:name "process-id", :type "integer"}
{:name "callback",
:optional? true,
:type :callback,
:callback {:params [{:name "did-terminate", :type "boolean"}]}}]}
{:id ::get-process-info,
:name "getProcessInfo",
:callback? true,
:params
[{:name "process-ids", :type "integer-or-[array-of-integers]"}
{:name "include-memory", :type "boolean"}
{:name "callback", :type :callback, :callback {:params [{:name "processes", :type "object"}]}}]}],
:events
[{:id ::on-updated, :name "onUpdated", :params [{:name "processes", :type "object"}]}
{:id ::on-updated-with-memory, :name "onUpdatedWithMemory", :params [{:name "processes", :type "object"}]}
{:id ::on-created, :name "onCreated", :params [{:name "process", :type "processes.Process"}]}
{:id ::on-unresponsive, :name "onUnresponsive", :params [{:name "process", :type "processes.Process"}]}
{:id ::on-exited,
:name "onExited",
:params
[{:name "process-id", :type "integer"}
{:name "exit-type", :type "integer"}
{:name "exit-code", :type "integer"}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
4f1e25dae0993d1c7234b13106f7c2257e04ccb3fef30bba33a8a927e1fad01f | ocaml-multicore/tezos | faked_client_context.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Tezos_client_base
let logger =
let log _channel msg = Lwt_fmt.printf "%s@." msg in
new Client_context.simple_printer log
class dummy_prompter : Client_context.prompter =
object
method prompt : type a. (a, string tzresult) Client_context.lwt_format -> a
=
fun _msg -> assert false
method prompt_password : type a.
(a, Bytes.t tzresult) Client_context.lwt_format -> a =
fun _msg -> assert false
method multiple_password_retries = false
end
let log _channel msg =
print_endline msg ;
Lwt.return_unit
class faked_ctxt (hooks : Faked_services.hooks) (chain_id : Chain_id.t) :
RPC_context.generic =
let local_ctxt =
let module Services = Faked_services.Make ((val hooks)) in
Tezos_mockup_proxy.RPC_client.local_ctxt (Services.directory chain_id)
in
object
method base = local_ctxt#base
method generic_media_type_call meth ?body uri =
local_ctxt#generic_media_type_call meth ?body uri
method call_service
: 'm 'p 'q 'i 'o.
(([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t ->
'p ->
'q ->
'i ->
'o tzresult Lwt.t =
fun service params query body ->
local_ctxt#call_service service params query body
method call_streamed_service
: 'm 'p 'q 'i 'o.
(([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t ->
on_chunk:('o -> unit) ->
on_close:(unit -> unit) ->
'p ->
'q ->
'i ->
(unit -> unit) tzresult Lwt.t =
fun service ~on_chunk ~on_close params query body ->
local_ctxt#call_streamed_service
service
~on_chunk
~on_close
params
query
body
end
class faked_wallet ~base_dir ~filesystem : Client_context.wallet =
object (self)
method load_passwords = None
method read_file fname =
match String.Hashtbl.find filesystem fname with
| None -> failwith "faked_wallet: cannot ead file (%s)" fname
| Some content -> return content
method private filename alias_name =
Filename.concat
base_dir
(String.map (function ' ' -> '_' | c -> c) alias_name ^ "s")
val lock_mutex = Lwt_mutex.create ()
method with_lock : type a. (unit -> a Lwt.t) -> a Lwt.t =
fun f -> Lwt_mutex.with_lock lock_mutex f
method get_base_dir = base_dir
method load : type a.
string -> default:a -> a Data_encoding.encoding -> a tzresult Lwt.t =
fun alias_name ~default encoding ->
let filename = self#filename alias_name in
if not (String.Hashtbl.mem filesystem filename) then return default
else
self#read_file filename >>=? fun content ->
let json = (Ezjsonm.from_string content :> Data_encoding.json) in
match Data_encoding.Json.destruct encoding json with
| exception e ->
failwith
"did not understand the %s alias file %s : %s"
alias_name
filename
(Printexc.to_string e)
| data -> return data
method write : type a.
string -> a -> a Data_encoding.encoding -> unit tzresult Lwt.t =
fun alias_name list encoding ->
let filename = self#filename alias_name in
let json = Data_encoding.Json.construct encoding list in
let str = Ezjsonm.value_to_string (json :> Ezjsonm.value) in
String.Hashtbl.replace filesystem filename str ;
return_unit
end
class faked_io_wallet ~base_dir ~filesystem : Client_context.io_wallet =
object
inherit Client_context.simple_printer log
inherit dummy_prompter
inherit faked_wallet ~base_dir ~filesystem
end
class unix_faked ~base_dir ~filesystem ~chain_id ~hooks : Client_context.full =
object
inherit faked_io_wallet ~base_dir ~filesystem
inherit faked_ctxt hooks chain_id
inherit Client_context_unix.unix_ui
method chain = `Hash chain_id
method block = `Head 0
method confirmations = None
end
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_delegate/test/mockup_simulator/faked_client_context.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Tezos_client_base
let logger =
let log _channel msg = Lwt_fmt.printf "%s@." msg in
new Client_context.simple_printer log
class dummy_prompter : Client_context.prompter =
object
method prompt : type a. (a, string tzresult) Client_context.lwt_format -> a
=
fun _msg -> assert false
method prompt_password : type a.
(a, Bytes.t tzresult) Client_context.lwt_format -> a =
fun _msg -> assert false
method multiple_password_retries = false
end
let log _channel msg =
print_endline msg ;
Lwt.return_unit
class faked_ctxt (hooks : Faked_services.hooks) (chain_id : Chain_id.t) :
RPC_context.generic =
let local_ctxt =
let module Services = Faked_services.Make ((val hooks)) in
Tezos_mockup_proxy.RPC_client.local_ctxt (Services.directory chain_id)
in
object
method base = local_ctxt#base
method generic_media_type_call meth ?body uri =
local_ctxt#generic_media_type_call meth ?body uri
method call_service
: 'm 'p 'q 'i 'o.
(([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t ->
'p ->
'q ->
'i ->
'o tzresult Lwt.t =
fun service params query body ->
local_ctxt#call_service service params query body
method call_streamed_service
: 'm 'p 'q 'i 'o.
(([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t ->
on_chunk:('o -> unit) ->
on_close:(unit -> unit) ->
'p ->
'q ->
'i ->
(unit -> unit) tzresult Lwt.t =
fun service ~on_chunk ~on_close params query body ->
local_ctxt#call_streamed_service
service
~on_chunk
~on_close
params
query
body
end
class faked_wallet ~base_dir ~filesystem : Client_context.wallet =
object (self)
method load_passwords = None
method read_file fname =
match String.Hashtbl.find filesystem fname with
| None -> failwith "faked_wallet: cannot ead file (%s)" fname
| Some content -> return content
method private filename alias_name =
Filename.concat
base_dir
(String.map (function ' ' -> '_' | c -> c) alias_name ^ "s")
val lock_mutex = Lwt_mutex.create ()
method with_lock : type a. (unit -> a Lwt.t) -> a Lwt.t =
fun f -> Lwt_mutex.with_lock lock_mutex f
method get_base_dir = base_dir
method load : type a.
string -> default:a -> a Data_encoding.encoding -> a tzresult Lwt.t =
fun alias_name ~default encoding ->
let filename = self#filename alias_name in
if not (String.Hashtbl.mem filesystem filename) then return default
else
self#read_file filename >>=? fun content ->
let json = (Ezjsonm.from_string content :> Data_encoding.json) in
match Data_encoding.Json.destruct encoding json with
| exception e ->
failwith
"did not understand the %s alias file %s : %s"
alias_name
filename
(Printexc.to_string e)
| data -> return data
method write : type a.
string -> a -> a Data_encoding.encoding -> unit tzresult Lwt.t =
fun alias_name list encoding ->
let filename = self#filename alias_name in
let json = Data_encoding.Json.construct encoding list in
let str = Ezjsonm.value_to_string (json :> Ezjsonm.value) in
String.Hashtbl.replace filesystem filename str ;
return_unit
end
class faked_io_wallet ~base_dir ~filesystem : Client_context.io_wallet =
object
inherit Client_context.simple_printer log
inherit dummy_prompter
inherit faked_wallet ~base_dir ~filesystem
end
class unix_faked ~base_dir ~filesystem ~chain_id ~hooks : Client_context.full =
object
inherit faked_io_wallet ~base_dir ~filesystem
inherit faked_ctxt hooks chain_id
inherit Client_context_unix.unix_ui
method chain = `Hash chain_id
method block = `Head 0
method confirmations = None
end
|
84fbbf39beae955aae6ea12378a78575a0fefc44f543a3b67c6b8010bfead23d | glebec/haskell-programming-allen-moronuki | MadLib.hs | module MadLib where
import Data.Monoid
type Verb = String
type Adjective = String
type Adverb = String
type Noun = String
type Exclamation = String
madlibbin' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbin' e adv noun adj =
e <> "! he said " <> adv <>
", as he jumped into his car " <> noun <>
" and drove off with his " <> adj <> " wife."
madlibbinBetter' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbinBetter' e adv noun adj = mconcat
[ e
, "! he said "
, adv
, ", as he jumped into his car "
, noun
, " and drove off with his "
, adj
, " wife."
]
| null | https://raw.githubusercontent.com/glebec/haskell-programming-allen-moronuki/99bd232f523e426d18a5e096f1cf771228c55f52/15-monoid-semigroup/projects/p0-scratch/src/MadLib.hs | haskell | module MadLib where
import Data.Monoid
type Verb = String
type Adjective = String
type Adverb = String
type Noun = String
type Exclamation = String
madlibbin' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbin' e adv noun adj =
e <> "! he said " <> adv <>
", as he jumped into his car " <> noun <>
" and drove off with his " <> adj <> " wife."
madlibbinBetter' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbinBetter' e adv noun adj = mconcat
[ e
, "! he said "
, adv
, ", as he jumped into his car "
, noun
, " and drove off with his "
, adj
, " wife."
]
| |
dcfd3142a1145fa0fd8ff9bd3e353598e7b33597f7d05389b50277444976287e | logicmoo/logicmoo_nlu | pred.lsp | Mini - PrologII
; pred.lsp
;
(defvar Ob_Micro_Log
'(|write| |nl| |tab| |read| |get| |get0|
|var| |nonvar| |atomic| |atom| |number|
! |fail| |true|
|divi| |mod| |plus| |minus| |mult| |le| |lt|
|name| |consult| |abolish| |cputime| |statistics|
|call| |freeze| |dif| |frozen_goals|))
(mapc #'(lambda (x) (setf (get x 'evaluable) t)) Ob_Micro_Log)
; !/0
(defun ! (n)
(setq BL (Cut CL) BG (if (zerop BL) BottomG (BG BL))
L (+ CL 4 n))) ; updates local stack
; call/1 (+term)
(defun |call| (x)
(if (var? x)
(let ((te (ultimate x PCE PCG))) ; dereferences it
(unless CP
applies LCO
(setq CP (CP CL) CL (CL CL))) ; new continuation
(push_cont) ; saves continuation
(vset Mem (+ L 2) (cdr te)) ; global env.
(vset Mem (+ L 3) Cut_pt) ; cut point
(setq CP (list (dec_goal (car te))) CL L)
(maj_L 0)) ; ends local block
adds it to CP
; freeze/2 (?var,+term)
(defun |freeze| (x p)
(let ((xte (ultimate x PCE PCG))) ; dereferences the var
(if (var? (car xte)) ; unbound
(let ((y (adr (car xte) (cdr xte))) ; the location
(pte (ultimate p PCE PCG))) ; dereferences the goal
(bindfg y (dec_goal (car pte)) (cdr pte) (fgblock y)))
(|call| p)))) ; else call p
; dif/2 (?term,?term)
(defun |dif| (x y)
(let ((BL L) (BG G) (str TR) (FRCP nil)) ; saves registers
(if (eq (uni x y) 'fail) ; unification fails
(poptrail str) ; restores env and succeeds
one var bound
selects one var
(v (if (numberp xv) xv (car xv))))
(poptrail str) ; restores env
(bindfg v PC PCG (fgblock v))) ; perpetuates the delaying
'fail)))) ; fails if equals
; statistics/0
(defun |statistics| ()
(format t " local stack : ~A (~A used)~%"
(- BottomTR BottomL) (- L BottomL))
(format t " global stack : ~A (~A used)~%"
(- BottomL BottomG) (- G BottomG))
(format t " trail : ~A (~A used)~%"
(- A BottomTR) (- TR BottomTR))
(format t " frozen-goals stack : ~A (~A used)~%"
BottomG (- FR BottomFR)))
; frozen_goals/0
(defun |frozen_goals| ()
(do ((i (- FR 4) (- i 4))) ; scans the frozen goals stack
((< i 0))
(if (eq (car (svref Mem (FGvar i))) 'LIBRE) ; unbound
(let ((b (if (numberp (FGgoal i)) (FGgoal i) i)))
(writesf (pred (FGgoal b)) (largs (FGgoal b)) (FGenv b))
(format t " frozen upon X~A~%" (FGvar i))))))
| null | https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/e2c/microPrologIIV4/pred.lsp | lisp | pred.lsp
!/0
updates local stack
call/1 (+term)
dereferences it
new continuation
saves continuation
global env.
cut point
ends local block
freeze/2 (?var,+term)
dereferences the var
unbound
the location
dereferences the goal
else call p
dif/2 (?term,?term)
saves registers
unification fails
restores env and succeeds
restores env
perpetuates the delaying
fails if equals
statistics/0
frozen_goals/0
scans the frozen goals stack
unbound | Mini - PrologII
(defvar Ob_Micro_Log
'(|write| |nl| |tab| |read| |get| |get0|
|var| |nonvar| |atomic| |atom| |number|
! |fail| |true|
|divi| |mod| |plus| |minus| |mult| |le| |lt|
|name| |consult| |abolish| |cputime| |statistics|
|call| |freeze| |dif| |frozen_goals|))
(mapc #'(lambda (x) (setf (get x 'evaluable) t)) Ob_Micro_Log)
(defun ! (n)
(setq BL (Cut CL) BG (if (zerop BL) BottomG (BG BL))
(defun |call| (x)
(if (var? x)
(unless CP
applies LCO
(setq CP (list (dec_goal (car te))) CL L)
adds it to CP
(defun |freeze| (x p)
(bindfg y (dec_goal (car pte)) (cdr pte) (fgblock y)))
(defun |dif| (x y)
one var bound
selects one var
(v (if (numberp xv) xv (car xv))))
(defun |statistics| ()
(format t " local stack : ~A (~A used)~%"
(- BottomTR BottomL) (- L BottomL))
(format t " global stack : ~A (~A used)~%"
(- BottomL BottomG) (- G BottomG))
(format t " trail : ~A (~A used)~%"
(- A BottomTR) (- TR BottomTR))
(format t " frozen-goals stack : ~A (~A used)~%"
BottomG (- FR BottomFR)))
(defun |frozen_goals| ()
((< i 0))
(let ((b (if (numberp (FGgoal i)) (FGgoal i) i)))
(writesf (pred (FGgoal b)) (largs (FGgoal b)) (FGenv b))
(format t " frozen upon X~A~%" (FGvar i))))))
|
2d69d14defb6b05bc3703843c3c7bfd965e8281391a0506117611d5302bfeaf4 | greglook/clj-cbor | tagged_test.clj | (ns clj-cbor.data.tagged-test
(:require
[clj-cbor.data.tagged :refer [->TaggedValue]]
[clojure.test :refer [deftest testing is]]))
(deftest tagged-values
(let [uri-value (->TaggedValue 32 "/" nil)
ratio-value (->TaggedValue 30 [1 3] nil)]
(testing "representation"
(is (= "32(/)" (str uri-value)))
(is (= "30([1 3])" (str ratio-value))))
(testing "equality"
(is (= uri-value uri-value)
"should be reflexive")
(is (= ratio-value (->TaggedValue 30 [1 3] nil))
"different instances of the same value should be equal")
(is (not= ratio-value (->TaggedValue 30 [1 4] nil))
"different values of the same tag should not be equal")
(is (not= uri-value ratio-value)
"different simple values should not be equal")
(is (not= uri-value :foo)
"different types should not be equal"))
(testing "hash code"
(is (integer? (hash uri-value)))
(is (= (hash uri-value) (hash uri-value))
"should be stable")
(is (= (hash ratio-value) (hash (->TaggedValue 30 [1 3] nil)))
"different instances of the same value should have the same hash")
(is (not= (hash uri-value) (hash ratio-value))
"different simple values should have different hashes"))
(testing "metadata"
(is (nil? (meta uri-value)))
(is (= uri-value (vary-meta uri-value assoc :x 123))
"should not affect equality")
(is (= (hash ratio-value) (hash (vary-meta ratio-value assoc :y true)))
"should not affect hash code")
(is (= {:x 123} (meta (vary-meta uri-value assoc :x 123)))
"metadata is preserved"))))
| null | https://raw.githubusercontent.com/greglook/clj-cbor/ff3ec660fe40789e2bf97b87b6a5e9be0361b0b2/test/clj_cbor/data/tagged_test.clj | clojure | (ns clj-cbor.data.tagged-test
(:require
[clj-cbor.data.tagged :refer [->TaggedValue]]
[clojure.test :refer [deftest testing is]]))
(deftest tagged-values
(let [uri-value (->TaggedValue 32 "/" nil)
ratio-value (->TaggedValue 30 [1 3] nil)]
(testing "representation"
(is (= "32(/)" (str uri-value)))
(is (= "30([1 3])" (str ratio-value))))
(testing "equality"
(is (= uri-value uri-value)
"should be reflexive")
(is (= ratio-value (->TaggedValue 30 [1 3] nil))
"different instances of the same value should be equal")
(is (not= ratio-value (->TaggedValue 30 [1 4] nil))
"different values of the same tag should not be equal")
(is (not= uri-value ratio-value)
"different simple values should not be equal")
(is (not= uri-value :foo)
"different types should not be equal"))
(testing "hash code"
(is (integer? (hash uri-value)))
(is (= (hash uri-value) (hash uri-value))
"should be stable")
(is (= (hash ratio-value) (hash (->TaggedValue 30 [1 3] nil)))
"different instances of the same value should have the same hash")
(is (not= (hash uri-value) (hash ratio-value))
"different simple values should have different hashes"))
(testing "metadata"
(is (nil? (meta uri-value)))
(is (= uri-value (vary-meta uri-value assoc :x 123))
"should not affect equality")
(is (= (hash ratio-value) (hash (vary-meta ratio-value assoc :y true)))
"should not affect hash code")
(is (= {:x 123} (meta (vary-meta uri-value assoc :x 123)))
"metadata is preserved"))))
| |
c729c25864cb73a1bbc36b35b31d16fac0546bfb4dca990d8156b1f35ee3f62c | Copilot-Language/copilot | Grey.hs | # LANGUAGE RebindableSyntax #
module Grey where
import Copilot.Language
import Copilot.Theorem
import Copilot.Theorem.Prover.Z3
import Prelude ()
import Data.String (fromString)
intCounter :: Stream Bool -> Stream Word64
intCounter reset = time
where
time = if reset then 0
else [0] ++ if time == 3 then 0 else time + 1
greyTick :: Stream Bool -> Stream Bool
greyTick reset = a && b
where
a = (not reset) && ([False] ++ not b)
b = (not reset) && ([False] ++ a)
spec = do
theorem "iResetOk" (forall $ r ==> (ic == 0)) induct
theorem "eqCounters" (forall $ it == gt) $ kinduct 3
where
ic = intCounter r
it = ic == 2
gt = greyTick r
r = extern "reset" Nothing
induct :: Proof Universal
induct = induction def { nraNLSat = False, debug = False }
kinduct :: Word32 -> Proof Universal
kinduct k = kInduction def { nraNLSat = False, startK = k, maxK = k, debug = False }
| null | https://raw.githubusercontent.com/Copilot-Language/copilot/17a9b45eea4e95a465d6e773c6fbcf9bf810b6cc/copilot-theorem/examples/Grey.hs | haskell | # LANGUAGE RebindableSyntax #
module Grey where
import Copilot.Language
import Copilot.Theorem
import Copilot.Theorem.Prover.Z3
import Prelude ()
import Data.String (fromString)
intCounter :: Stream Bool -> Stream Word64
intCounter reset = time
where
time = if reset then 0
else [0] ++ if time == 3 then 0 else time + 1
greyTick :: Stream Bool -> Stream Bool
greyTick reset = a && b
where
a = (not reset) && ([False] ++ not b)
b = (not reset) && ([False] ++ a)
spec = do
theorem "iResetOk" (forall $ r ==> (ic == 0)) induct
theorem "eqCounters" (forall $ it == gt) $ kinduct 3
where
ic = intCounter r
it = ic == 2
gt = greyTick r
r = extern "reset" Nothing
induct :: Proof Universal
induct = induction def { nraNLSat = False, debug = False }
kinduct :: Word32 -> Proof Universal
kinduct k = kInduction def { nraNLSat = False, startK = k, maxK = k, debug = False }
| |
7ed06335bbab4fad7976d1c39cef849743ad99cf129b17338b31d8a45da541a0 | Liqwid-Labs/liqwid-libs | Types.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE UndecidableInstances #
|
Module : ScriptExport . Types
Maintainer :
Description : and script types for generation .
and script types for generation .
Module : ScriptExport.Types
Maintainer :
Description: Param and script types for generation.
Param and script types for generation.
-}
module ScriptExport.Types (
ServeElement (..),
ScriptQuery (..),
Builders,
handleServe,
getBuilders,
runQuery,
insertBuilder,
insertStaticBuilder,
insertScriptExportWithLinker,
toList,
) where
import Control.Monad.Except
import Data.Aeson qualified as Aeson
import Data.ByteString.Lazy.Char8 qualified as LBS
import Data.Default.Class (Default (def))
import Data.Hashable (Hashable)
import Data.Kind (Type)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Text (Text, pack, unpack)
import GHC.Generics qualified as GHC
import Optics.TH (makeFieldLabelsNoPrefix)
import ScriptExport.ScriptInfo (
Linker,
RawScriptExport,
ScriptExport,
runLinker,
)
import Servant qualified
{- | Query data for getting script info.
@since 1.0.0
-}
data ScriptQuery = ScriptQuery
{ name :: Text
, param :: Maybe Aeson.Value
}
deriving anyclass
( -- | @since 1.0.0
Aeson.ToJSON
, -- | @since 1.0.0
Aeson.FromJSON
)
deriving stock
( -- | @since 1.0.0
Show
, -- | @since 1.0.0
Eq
, -- | @since 1.0.0
GHC.Generic
, -- | @since 1.0.0
Ord
)
deriving anyclass
( -- | @since 1.0.0
Hashable
)
{- | Run a query on Builders.
@since 1.0.0
-}
runQuery :: ScriptQuery -> Builders -> Servant.Handler Aeson.Value
runQuery (ScriptQuery name param) =
maybe
(Servant.throwError Servant.err404 {Servant.errBody = "Builder not found"})
(toServantErr . runExcept . handleServe param)
. Map.lookup name
. getBuilders
where
toServantErr (Left err) =
Servant.throwError
Servant.err400
{ Servant.errBody = (LBS.pack . unpack) err
}
toServantErr (Right x) = pure x
{- | Possible data to request.
@since 2.0.0
-}
data ServeElement where
ServeRawScriptExport ::
forall (a :: Type) (param :: Type).
(Aeson.FromJSON param, Aeson.ToJSON a) =>
RawScriptExport ->
Linker param (ScriptExport a) ->
ServeElement
ServeJSON ::
forall (s :: Type).
(Aeson.ToJSON s) =>
s ->
ServeElement
ServeJSONWithParam ::
forall (p :: Type) (s :: Type).
(Aeson.FromJSON p, Aeson.ToJSON s) =>
(p -> s) ->
ServeElement
{- | Handle `ServeElement` and returns JSON.
@since 2.0.0
-}
handleServe :: Maybe Aeson.Value -> ServeElement -> Except Text Aeson.Value
handleServe _ (ServeJSON x) = pure $ Aeson.toJSON x
handleServe (Just arg) (ServeJSONWithParam f) =
case Aeson.fromJSON arg of
Aeson.Error e ->
throwError $ pack e
Aeson.Success v' ->
pure . Aeson.toJSON $ f v'
handleServe (Just arg) (ServeRawScriptExport scr linker) =
case Aeson.fromJSON arg of
Aeson.Error e ->
throwError $ pack e
Aeson.Success v' ->
case runLinker linker scr v' of
Left e -> throwError . pack . show $ e
Right x -> pure . Aeson.toJSON $ x
handleServe Nothing (ServeRawScriptExport scr _) = pure $ Aeson.toJSON scr
handleServe Nothing (ServeJSONWithParam _) = throwError "Query expects an argument, but nothing is given"
{- | Represents a list of named pure functions.
@since 2.0.0
-}
newtype Builders
= Builders (Map Text ServeElement)
deriving
( -- | @since 1.0.0
Semigroup
, -- | @since 1.0.0
Monoid
)
via (Map Text ServeElement)
-- | @since 2.0.0
getBuilders ::
Builders ->
Map Text ServeElement
getBuilders (Builders b) = b
{- | Get a list of the available builders.
@since 2.0.0
-}
toList :: Builders -> [Text]
toList = Map.keys . getBuilders
-- | @since 2.0.0
instance Default Builders where
def = Builders Map.empty
{- | Insert a pure function into the Builders map.
@since 2.0.0
-}
insertBuilder ::
forall (p :: Type) (s :: Type).
(Aeson.FromJSON p, Aeson.ToJSON s) =>
Text ->
(p -> s) ->
Builders
insertBuilder k f =
Builders $ Map.insert k (ServeJSONWithParam f) mempty
insertStaticBuilder ::
forall (a :: Type).
(Aeson.ToJSON a) =>
Text ->
a ->
Builders
insertStaticBuilder k x =
Builders $ Map.insert k (ServeJSON x) mempty
| Insert a ' RawScriptExport ' and ' ScriptLinker ' to the Builders Map . The
builder will return applied ` ScriptExport ` with given parameter .
@since 2.0.0
builder will return applied `ScriptExport` with given parameter.
@since 2.0.0
-}
insertScriptExportWithLinker ::
forall (param :: Type) (a :: Type).
(Aeson.FromJSON param, Aeson.ToJSON a) =>
Text ->
RawScriptExport ->
Linker param (ScriptExport a) ->
Builders
insertScriptExportWithLinker k scr linker =
Builders $ Map.insert k (ServeRawScriptExport scr linker) mempty
----------------------------------------
-- Field Labels
-- | @since 2.0.0
makeFieldLabelsNoPrefix ''ScriptQuery
| null | https://raw.githubusercontent.com/Liqwid-Labs/liqwid-libs/8165d3a33daa5deb377db854b9c7b62aab9c2897/liqwid-script-export/src/ScriptExport/Types.hs | haskell | # LANGUAGE GADTs #
| Query data for getting script info.
@since 1.0.0
| @since 1.0.0
| @since 1.0.0
| @since 1.0.0
| @since 1.0.0
| @since 1.0.0
| @since 1.0.0
| @since 1.0.0
| Run a query on Builders.
@since 1.0.0
| Possible data to request.
@since 2.0.0
| Handle `ServeElement` and returns JSON.
@since 2.0.0
| Represents a list of named pure functions.
@since 2.0.0
| @since 1.0.0
| @since 1.0.0
| @since 2.0.0
| Get a list of the available builders.
@since 2.0.0
| @since 2.0.0
| Insert a pure function into the Builders map.
@since 2.0.0
--------------------------------------
Field Labels
| @since 2.0.0 | # LANGUAGE TemplateHaskell #
# LANGUAGE UndecidableInstances #
|
Module : ScriptExport . Types
Maintainer :
Description : and script types for generation .
and script types for generation .
Module : ScriptExport.Types
Maintainer :
Description: Param and script types for generation.
Param and script types for generation.
-}
module ScriptExport.Types (
ServeElement (..),
ScriptQuery (..),
Builders,
handleServe,
getBuilders,
runQuery,
insertBuilder,
insertStaticBuilder,
insertScriptExportWithLinker,
toList,
) where
import Control.Monad.Except
import Data.Aeson qualified as Aeson
import Data.ByteString.Lazy.Char8 qualified as LBS
import Data.Default.Class (Default (def))
import Data.Hashable (Hashable)
import Data.Kind (Type)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Text (Text, pack, unpack)
import GHC.Generics qualified as GHC
import Optics.TH (makeFieldLabelsNoPrefix)
import ScriptExport.ScriptInfo (
Linker,
RawScriptExport,
ScriptExport,
runLinker,
)
import Servant qualified
data ScriptQuery = ScriptQuery
{ name :: Text
, param :: Maybe Aeson.Value
}
deriving anyclass
Aeson.ToJSON
Aeson.FromJSON
)
deriving stock
Show
Eq
GHC.Generic
Ord
)
deriving anyclass
Hashable
)
runQuery :: ScriptQuery -> Builders -> Servant.Handler Aeson.Value
runQuery (ScriptQuery name param) =
maybe
(Servant.throwError Servant.err404 {Servant.errBody = "Builder not found"})
(toServantErr . runExcept . handleServe param)
. Map.lookup name
. getBuilders
where
toServantErr (Left err) =
Servant.throwError
Servant.err400
{ Servant.errBody = (LBS.pack . unpack) err
}
toServantErr (Right x) = pure x
data ServeElement where
ServeRawScriptExport ::
forall (a :: Type) (param :: Type).
(Aeson.FromJSON param, Aeson.ToJSON a) =>
RawScriptExport ->
Linker param (ScriptExport a) ->
ServeElement
ServeJSON ::
forall (s :: Type).
(Aeson.ToJSON s) =>
s ->
ServeElement
ServeJSONWithParam ::
forall (p :: Type) (s :: Type).
(Aeson.FromJSON p, Aeson.ToJSON s) =>
(p -> s) ->
ServeElement
handleServe :: Maybe Aeson.Value -> ServeElement -> Except Text Aeson.Value
handleServe _ (ServeJSON x) = pure $ Aeson.toJSON x
handleServe (Just arg) (ServeJSONWithParam f) =
case Aeson.fromJSON arg of
Aeson.Error e ->
throwError $ pack e
Aeson.Success v' ->
pure . Aeson.toJSON $ f v'
handleServe (Just arg) (ServeRawScriptExport scr linker) =
case Aeson.fromJSON arg of
Aeson.Error e ->
throwError $ pack e
Aeson.Success v' ->
case runLinker linker scr v' of
Left e -> throwError . pack . show $ e
Right x -> pure . Aeson.toJSON $ x
handleServe Nothing (ServeRawScriptExport scr _) = pure $ Aeson.toJSON scr
handleServe Nothing (ServeJSONWithParam _) = throwError "Query expects an argument, but nothing is given"
newtype Builders
= Builders (Map Text ServeElement)
deriving
Semigroup
Monoid
)
via (Map Text ServeElement)
getBuilders ::
Builders ->
Map Text ServeElement
getBuilders (Builders b) = b
toList :: Builders -> [Text]
toList = Map.keys . getBuilders
instance Default Builders where
def = Builders Map.empty
insertBuilder ::
forall (p :: Type) (s :: Type).
(Aeson.FromJSON p, Aeson.ToJSON s) =>
Text ->
(p -> s) ->
Builders
insertBuilder k f =
Builders $ Map.insert k (ServeJSONWithParam f) mempty
insertStaticBuilder ::
forall (a :: Type).
(Aeson.ToJSON a) =>
Text ->
a ->
Builders
insertStaticBuilder k x =
Builders $ Map.insert k (ServeJSON x) mempty
| Insert a ' RawScriptExport ' and ' ScriptLinker ' to the Builders Map . The
builder will return applied ` ScriptExport ` with given parameter .
@since 2.0.0
builder will return applied `ScriptExport` with given parameter.
@since 2.0.0
-}
insertScriptExportWithLinker ::
forall (param :: Type) (a :: Type).
(Aeson.FromJSON param, Aeson.ToJSON a) =>
Text ->
RawScriptExport ->
Linker param (ScriptExport a) ->
Builders
insertScriptExportWithLinker k scr linker =
Builders $ Map.insert k (ServeRawScriptExport scr linker) mempty
makeFieldLabelsNoPrefix ''ScriptQuery
|
c543baad22472caf1c76a8d2637204bad71ce5f467a8b38ed24a7e8b6249d0be | ninenines/gun | cookie_informational_h.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(cookie_informational_h).
-export([init/2]).
init(Req0, State) ->
cowboy_req:inform(103, #{<<"set-cookie">> => [<<"informational=1">>]}, Req0),
Req = cowboy_req:reply(204, #{<<"set-cookie">> => [<<"final=1">>]}, Req0),
{ok, Req, State}.
| null | https://raw.githubusercontent.com/ninenines/gun/fe25965f3a2f1347529fec8c7afa981313378e31/test/handlers/cookie_informational_h.erl | erlang | Feel free to use, reuse and abuse the code in this file. |
-module(cookie_informational_h).
-export([init/2]).
init(Req0, State) ->
cowboy_req:inform(103, #{<<"set-cookie">> => [<<"informational=1">>]}, Req0),
Req = cowboy_req:reply(204, #{<<"set-cookie">> => [<<"final=1">>]}, Req0),
{ok, Req, State}.
|
2845c1e0f7238fffe8f9fe46e42369b249950c1da3b78b118cda32f459b8e266 | Beluga-lang/Beluga | prover.ml | open Support
open Beluga
open Syntax.Int
module E = Error
module Command = Syntax.Ext.Harpoon
module S = Substitution
module P = Pretty.Int.DefaultPrinter
module CompS = Store.Cid.Comp
let dprintf, _, dprnt = Debug.(makeFunctions' (toFlags [13]))
open Debug.Fmt
module Error = struct
type t =
| NoSuchVariable of Name.t * [ `meta | `comp ]
exception E of t
let throw e = raise (E e)
let fmt_ppr ppf =
let open Format in
function
| NoSuchVariable (name, level) ->
let format_variable_kind ppf = function
| `meta -> fprintf ppf "metavariable"
| `comp -> fprintf ppf "computational variable"
in
fprintf ppf "No such %a %a."
format_variable_kind level
Name.pp name
let _ =
Error.register_printing_function
(function E e -> Some e | _ -> None)
fmt_ppr
end
(** High-level elaboration from external to internal syntax. *)
module Elab = struct
(** Elaborates a synthesizable expression in the given contexts. *)
let exp' mcid cIH cD cG mfs t =
let (hs, (i, tau)) =
Holes.catch
begin fun _ ->
let (i, (tau, theta)) =
Interactive.elaborate_exp' cD cG t
in
dprintf
begin fun p ->
p.fmt "[elaborate_exp'] @[<v>done:@,\
i = @[%a@] (internal)@]"
P.(fmt_ppr_cmp_exp cD cG l0) i
end;
let i = Whnf.cnormExp (i, Whnf.m_id) in
let _ = Check.Comp.syn mcid ~cIH: cIH cD cG mfs i in (* (tau, theta); *)
(i, Whnf.cnormCTyp (tau, theta))
end
in
(hs, i, tau)
(** Elaborates a checkable expression in the given contexts against the given type. *)
let exp mcid cIH cD cG mfs t ttau =
Holes.catch
begin fun _ ->
let e = Interactive.elaborate_exp cD cG t (Pair.map_left Total.strip ttau) in
let e = Whnf.cnormExp (e, Whnf.m_id) in
Check.Comp.check mcid ~cIH: cIH cD cG mfs e ttau;
e
end
let typ cD tau =
let (tau, k) = Interactive.elaborate_typ cD tau in
tau
(** Elaborates a metavariable. *)
let mvar cD loc name =
(* This is kind of sketchy since we don't parse a head, but rather
just a name (or a hash_name), and we do all the elaboration "by
hand" here instead of using Lfrecon and Index.
*)
let p (d, _) = Name.(LF.name_of_ctyp_decl d = name) in
match Context.find_with_index_rev' cD p with
| None -> Lfrecon.(throw loc (UnboundName name))
| Some LF.(Decl (_, cT, _, _), k) ->
let cT = Whnf.cnormMTyp (cT, LF.MShift k) in
dprintf
begin fun p ->
p.fmt "[harpoon] [Elab.mvar] @[<v>found index %d for metavariable@,\
@[<hov 2>%a :@ @[%a@]@]@]"
k
Name.pp name
P.(fmt_ppr_cmp_meta_typ cD) cT
end;
let mF =
let open LF in
match cT with
| ClTyp (mT, cPsi) ->
let psi_hat = Context.dctxToHat cPsi in
let obj =
match mT with
| MTyp _ -> MObj (MVar (Offset k, S.LF.id) |> head)
| PTyp _ -> PObj (PVar (k, S.LF.id))
| STyp _ -> SObj (SVar (k, 0, S.LF.id)) (* XXX not sure about 0 -je *)
in
ClObj (psi_hat, obj)
| LF.CTyp _ ->
let cPsi = LF.(CtxVar (CtxOffset k)) in
CObj cPsi
in
let i = Comp.AnnBox (Location.ghost, (loc, mF), cT)
and tau = Comp.TypBox (loc, cT) in
(i, tau)
| _ -> E.violation "[harpoon] [Elab] [mvar] cD decl has no type"
end
(*
(** Removes the theorem with a given name from the list of theorems. *)
let remove_theorem s name =
let n = DynArray.length s.theorems in
let rec loop = function
| i when i >= n -> ()
| i when Name.equal name (DynArray.get s.theorems i).Theorem.name ->
DynArray.delete s.theorems i
| i -> loop (i + 1)
in
loop 0
*)
let dump_proof t path =
let out = open_out path in
let ppf = Format.formatter_of_out_channel out in
Theorem.dump_proof ppf t;
Format.pp_print_newline ppf ();
close_out out
let process_command
(s : HarpoonState.t)
( (c, t, g) : HarpoonState.triple)
(cmd : Command.command)
: unit =
let mfs =
lazy
begin
let ds = Session.get_mutual_decs c in
dprintf
begin fun p ->
p.fmt "[harpoon] [mfs] @[<v>got mutual decs:\
@,-> @[<v>%a@]@]"
(Format.pp_print_list ~pp_sep: Format.pp_print_cut
P.fmt_ppr_cmp_total_dec)
ds
end;
ds
end
in
let open Comp in
let solve_hole (id, Holes.Exists (w, h)) =
let open Holes in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve_hole] processing hole %s"
(HoleId.string_of_name_or_id (h.Holes.name, id))
end;
let { name; Holes.cD = cDh; info; _ } = h in
match w with
| Holes.CompInfo ->
begin
let { compGoal; Holes.cG = cGh; compSolution } = h.info
in
assert (compSolution = None);
let typ = Whnf.cnormCTyp compGoal in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve] [holes] @[<v>goal: @[%a@]@]"
(P.fmt_ppr_cmp_typ cDh Pretty.Int.DefaultPrinter.l0) typ
end;
Logic.prepare ();
let (mquery, skinnyCTyp, mquerySub, instMMVars) =
let (typ', k) = Abstract.comptyp typ in
Logic.Convert.comptypToMQuery (typ', k)
in
try
Logic.CSolver.cgSolve cDh cGh LF.Empty mquery
begin
fun e ->
HarpoonState.printf s "found solution: @[%a@]@,@?"
(P.fmt_ppr_cmp_exp cDh cGh P.l0) e;
h.info.compSolution <- Some e;
raise Logic.Frontend.Done
end
(Some 999, None, 2) (skinnyCTyp, None, Lazy.force mfs)
with
| Logic.Frontend.Done ->
HarpoonState.printf s "logic programming finished@,@?"
end
| Holes.LFInfo ->
let { lfGoal; cPsi; lfSolution } = h.info in
assert (lfSolution = None);
let typ = Whnf.normTyp lfGoal in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve] [holes] @[<v>goal: @[%a@]@]"
(P.fmt_ppr_lf_typ cDh cPsi P.l0) typ
end;
Logic.prepare ();
let (query, skinnyTyp, querySub, instMVars) =
Logic.Convert.typToQuery cDh cPsi (typ, 0)
in
try
Logic.Solver.solve cDh cPsi query
begin fun (cPsi, tM) ->
HarpoonState.printf s "found solution: @[%a@]@,@?"
(P.fmt_ppr_lf_normal cDh cPsi P.l0) tM;
h.info.lfSolution <- Some (tM, LF.Shift 0);
raise Logic.Frontend.Done
end
(Some 100)
with
| Logic.Frontend.Done ->
HarpoonState.printf s "logic programming finished@,@?"
in
let { cD; cG; cIH } = g.context in
match cmd with
(* Administrative commands: *)
| Command.Theorem cmd ->
begin match cmd with
| `list ->
HarpoonState.printf s "@[<v>%a@,@,Current theorem is first.@]"
Session.fmt_ppr_theorem_list c
| `defer -> Session.defer_theorem c
| `show_ihs ->
let f i =
HarpoonState.printf s "%d. @[%a@]@,"
(i + 1)
(P.fmt_ppr_cmp_ih g.context.cD g.context.cG)
in
HarpoonState.printf s "@[<v>There are %d IHs:@,"
(Context.length g.context.cIH);
Context.to_list g.context.cIH |> List.iteri f;
HarpoonState.printf s "@]"
| `dump_proof path ->
dump_proof t path
| `show_proof ->
Theorem.show_proof t
end
| Command.Session cmd ->
begin match cmd with
| `list ->
HarpoonState.printf s "@[<v>%a@,@,Current session and theorem are first.@]"
HarpoonState.fmt_ppr_session_list s
| `defer -> HarpoonState.defer_session s
| `create -> ignore (HarpoonState.session_configuration_wizard s)
| `serialize -> HarpoonState.serialize s (c, t, g)
end
| Command.Subgoal cmd ->
begin match cmd with
| `list -> Theorem.show_subgoals t
| `defer -> Theorem.defer_subgoal t
end
| Command.SelectTheorem name ->
if Bool.not (HarpoonState.select_theorem s name) then
HarpoonState.printf s
"There is no theorem by name %a."
Name.pp name
| Command.Rename { rename_from=x_src; rename_to=x_dst; level } ->
if Bool.not (Theorem.rename_variable x_src x_dst level t g) then
Error.(throw (NoSuchVariable (x_src, level)))
| Command.ToggleAutomation (automation_kind, automation_change) ->
Automation.toggle
(HarpoonState.automation_state s)
automation_kind
automation_change
| Command.Type i ->
let (hs, i, tau) =
Elab.exp' (Some (Theorem.get_cid t))
cIH cD cG (Lazy.force mfs) i
in
HarpoonState.printf s
"- @[<hov 2>@[%a@] :@ @[%a@]@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
| Command.Info (k, n) ->
begin match k with
| `prog ->
let open Option in
begin match CompS.(index_of_name_opt n $> get) with
| None ->
HarpoonState.printf s
"- No such theorem by name %a" Name.pp n
| Some e ->
HarpoonState.printf s
"- @[%a@]"
P.fmt_ppr_cmp_comp_prog_info e
end
end
| Command.Translate n ->
let open Option in
begin match CompS.(index_of_name_opt n $> get) with
| Some e ->
HarpoonState.printf s "%a"
Translate.fmt_ppr_result (Translate.entry e)
| None ->
HarpoonState.printf s "No such theorem by name %a defined."
Name.pp n
end
| Command.Undo ->
if Bool.not Theorem.(history_step t Direction.backward) then
HarpoonState.printf s "Nothing to undo in the current theorem's timeline."
| Command.Redo ->
if Bool.not Theorem.(history_step t Direction.forward) then
HarpoonState.printf s "Nothing to redo in the current theorem's timeline."
| Command.History ->
let open Format in
let (past, future) = Theorem.get_history_names t in
let future = List.rev future in
let line ppf = function
| _ when List.nonempty future ->
fprintf ppf "@,-----@,"
| _ -> ()
in
let future_remark ppf = function
| _ when List.nonempty future ->
fprintf ppf "- @[%a@]"
pp_print_string
"Commands below the line would be undone. \
Commands above the line would be redone."
| _ -> ()
in
HarpoonState.printf s
"@[<v 2>History:\
@,@[<v>%a@]%a@[<v>%a@]@]@,%a@,"
(pp_print_list ~pp_sep: pp_print_cut pp_print_string)
future
line ()
(pp_print_list ~pp_sep: pp_print_cut pp_print_string)
past
future_remark ()
| Command.Help ->
HarpoonState.printf s
"@[<v>Built-in help is not implemented.\
@,See online documentation: -lang.readthedocs.io/@]"
(* Real tactics: *)
| Command.Unbox (i, name, modifier) ->
let (hs, m, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
Tactic.unbox m tau name modifier t g
| Command.Intros names ->
Tactic.intros names t g
| Command.Split (split_kind, i) ->
let (hs, m, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
Tactic.split split_kind m tau (Lazy.force mfs) t g
| Command.MSplit (loc, name) ->
let i, tau = Elab.mvar cD loc name in
Tactic.split `split i tau (Lazy.force mfs) t g
| Command.By (i, name) ->
let (hs, i, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
dprintf
begin fun p ->
p.fmt "@[<v>[harpoon-By] elaborated invocation:@,%a@ : %a@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
end;
if Whnf.closedExp i then
(List.iter solve_hole hs; Tactic.invoke i tau name t g)
else
HarpoonState.printf s
"@[<v>Elaborated expression\
@, @[%a@]\
@,of type\
@, @[%a@]\
@,is not closed.\
@,Both the expression and its type must be closed for use with `by`.@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
| Command.Suffices (i, tau_list) ->
let (hs, i, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
begin match Session.infer_invocation_kind c i with
| `ih ->
HarpoonState.printf s "inductive use of `suffices by ...` is not currently supported"
| `lemma ->
begin match hs with
| _ :: _ ->
Theorem.printf t "holes are not supported for `suffices by _ ...`"
| [] ->
let elab_suffices_typ tau_ext : suffices_typ =
map_suffices_typ (Elab.typ cD) tau_ext
in
let tau_list = List.map elab_suffices_typ tau_list in
Tactic.suffices i tau_list tau t g
end
end
| Command.Solve e ->
let cid = Theorem.get_cid t in
let (hs, e) =
Elab.exp (Some cid) cIH cD cG (Lazy.force mfs) e g.goal
in
dprnt "[harpoon] [solve] elaboration finished";
State.printf s " Found % d hole(s ) in solution@. " ( hs ) ;
List.iter solve_hole hs;
dprnt "[harpoon] [solve] double-check!";
Check.Comp.check (Some cid) cD cG (Lazy.force mfs) ~cIH: cIH e g.goal;
dprnt "[harpoon] [solve] double-check DONE";
let e = Whnf.cnormExp (e, Whnf.m_id) in
if Whnf.closedExp e then
(Comp.solve e |> Tactic.solve) t g
else
HarpoonState.printf s "Solution contains uninstantiated metavariables."
| Command.AutoInvertSolve d ->
let { cD; cG; cIH } = g.context in
let (tau, ms) = g.goal in
let tau = Whnf.cnormCTyp (tau, ms) in
let (mquery, _, _, instMMVars) =
let (typ',k) = Abstract.comptyp tau in
Logic.Convert.comptypToMQuery (typ',k)
in
let (theorem, _) = Theorem.get_statement t in
let cid = Theorem.get_cid t in
let opt_witness = Logic.Frontend.msolve_tactic (cD, cG, cIH)
(mquery, tau, instMMVars) d
(theorem, cid, 1, (Lazy.force mfs))
in
begin
match opt_witness with
| None ->
HarpoonState.printf s "cgSolve cannot find a proof in cD = %a, cG = %a, skinny = %a, inst size = %d."
P.(fmt_ppr_lf_mctx l0) cD
P.(fmt_ppr_cmp_gctx cD l0) cG
P.(fmt_ppr_cmp_typ cD l0) tau
(List.length(instMMVars))
| Some e ->
(Comp.solve e |> Tactic.solve) t g
end
| Command.InductiveAutoSolve d ->
let { cD; cG; cIH } = g.context in
let (tau, ms) = g.goal in
let tau = Whnf.cnormCTyp (tau, ms) in
let (mquery, _, _, instMMVars) =
let (typ',k) = Abstract.comptyp tau in
Logic.Convert.comptypToMQuery (typ',k)
in
let (theorem, _) = Theorem.get_statement t in
let cid = Theorem.get_cid t in
let opt_witness = Logic.Frontend.msolve_tactic (cD, cG, cIH)
(mquery, tau, instMMVars) d
(theorem, cid, 2, (Lazy.force mfs))
in
begin
match opt_witness with
| None ->
HarpoonState.printf s "cgSolve cannot find a proof in cD = %a, cG = %a, skinny = %a, inst size = %d."
P.(fmt_ppr_lf_mctx l0) cD
P.(fmt_ppr_cmp_gctx cD l0) cG
P.(fmt_ppr_cmp_typ cD l0) tau
(List.length(instMMVars))
| Some e ->
(Comp.solve e |> Tactic.solve) t g
end
| null | https://raw.githubusercontent.com/Beluga-lang/Beluga/9bd52d07eece2de0b96ea8ddb7aaf48b40250068/src/harpoon/prover.ml | ocaml | * High-level elaboration from external to internal syntax.
* Elaborates a synthesizable expression in the given contexts.
(tau, theta);
* Elaborates a checkable expression in the given contexts against the given type.
* Elaborates a metavariable.
This is kind of sketchy since we don't parse a head, but rather
just a name (or a hash_name), and we do all the elaboration "by
hand" here instead of using Lfrecon and Index.
XXX not sure about 0 -je
(** Removes the theorem with a given name from the list of theorems.
Administrative commands:
Real tactics: | open Support
open Beluga
open Syntax.Int
module E = Error
module Command = Syntax.Ext.Harpoon
module S = Substitution
module P = Pretty.Int.DefaultPrinter
module CompS = Store.Cid.Comp
let dprintf, _, dprnt = Debug.(makeFunctions' (toFlags [13]))
open Debug.Fmt
module Error = struct
type t =
| NoSuchVariable of Name.t * [ `meta | `comp ]
exception E of t
let throw e = raise (E e)
let fmt_ppr ppf =
let open Format in
function
| NoSuchVariable (name, level) ->
let format_variable_kind ppf = function
| `meta -> fprintf ppf "metavariable"
| `comp -> fprintf ppf "computational variable"
in
fprintf ppf "No such %a %a."
format_variable_kind level
Name.pp name
let _ =
Error.register_printing_function
(function E e -> Some e | _ -> None)
fmt_ppr
end
module Elab = struct
let exp' mcid cIH cD cG mfs t =
let (hs, (i, tau)) =
Holes.catch
begin fun _ ->
let (i, (tau, theta)) =
Interactive.elaborate_exp' cD cG t
in
dprintf
begin fun p ->
p.fmt "[elaborate_exp'] @[<v>done:@,\
i = @[%a@] (internal)@]"
P.(fmt_ppr_cmp_exp cD cG l0) i
end;
let i = Whnf.cnormExp (i, Whnf.m_id) in
(i, Whnf.cnormCTyp (tau, theta))
end
in
(hs, i, tau)
let exp mcid cIH cD cG mfs t ttau =
Holes.catch
begin fun _ ->
let e = Interactive.elaborate_exp cD cG t (Pair.map_left Total.strip ttau) in
let e = Whnf.cnormExp (e, Whnf.m_id) in
Check.Comp.check mcid ~cIH: cIH cD cG mfs e ttau;
e
end
let typ cD tau =
let (tau, k) = Interactive.elaborate_typ cD tau in
tau
let mvar cD loc name =
let p (d, _) = Name.(LF.name_of_ctyp_decl d = name) in
match Context.find_with_index_rev' cD p with
| None -> Lfrecon.(throw loc (UnboundName name))
| Some LF.(Decl (_, cT, _, _), k) ->
let cT = Whnf.cnormMTyp (cT, LF.MShift k) in
dprintf
begin fun p ->
p.fmt "[harpoon] [Elab.mvar] @[<v>found index %d for metavariable@,\
@[<hov 2>%a :@ @[%a@]@]@]"
k
Name.pp name
P.(fmt_ppr_cmp_meta_typ cD) cT
end;
let mF =
let open LF in
match cT with
| ClTyp (mT, cPsi) ->
let psi_hat = Context.dctxToHat cPsi in
let obj =
match mT with
| MTyp _ -> MObj (MVar (Offset k, S.LF.id) |> head)
| PTyp _ -> PObj (PVar (k, S.LF.id))
in
ClObj (psi_hat, obj)
| LF.CTyp _ ->
let cPsi = LF.(CtxVar (CtxOffset k)) in
CObj cPsi
in
let i = Comp.AnnBox (Location.ghost, (loc, mF), cT)
and tau = Comp.TypBox (loc, cT) in
(i, tau)
| _ -> E.violation "[harpoon] [Elab] [mvar] cD decl has no type"
end
let remove_theorem s name =
let n = DynArray.length s.theorems in
let rec loop = function
| i when i >= n -> ()
| i when Name.equal name (DynArray.get s.theorems i).Theorem.name ->
DynArray.delete s.theorems i
| i -> loop (i + 1)
in
loop 0
*)
let dump_proof t path =
let out = open_out path in
let ppf = Format.formatter_of_out_channel out in
Theorem.dump_proof ppf t;
Format.pp_print_newline ppf ();
close_out out
let process_command
(s : HarpoonState.t)
( (c, t, g) : HarpoonState.triple)
(cmd : Command.command)
: unit =
let mfs =
lazy
begin
let ds = Session.get_mutual_decs c in
dprintf
begin fun p ->
p.fmt "[harpoon] [mfs] @[<v>got mutual decs:\
@,-> @[<v>%a@]@]"
(Format.pp_print_list ~pp_sep: Format.pp_print_cut
P.fmt_ppr_cmp_total_dec)
ds
end;
ds
end
in
let open Comp in
let solve_hole (id, Holes.Exists (w, h)) =
let open Holes in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve_hole] processing hole %s"
(HoleId.string_of_name_or_id (h.Holes.name, id))
end;
let { name; Holes.cD = cDh; info; _ } = h in
match w with
| Holes.CompInfo ->
begin
let { compGoal; Holes.cG = cGh; compSolution } = h.info
in
assert (compSolution = None);
let typ = Whnf.cnormCTyp compGoal in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve] [holes] @[<v>goal: @[%a@]@]"
(P.fmt_ppr_cmp_typ cDh Pretty.Int.DefaultPrinter.l0) typ
end;
Logic.prepare ();
let (mquery, skinnyCTyp, mquerySub, instMMVars) =
let (typ', k) = Abstract.comptyp typ in
Logic.Convert.comptypToMQuery (typ', k)
in
try
Logic.CSolver.cgSolve cDh cGh LF.Empty mquery
begin
fun e ->
HarpoonState.printf s "found solution: @[%a@]@,@?"
(P.fmt_ppr_cmp_exp cDh cGh P.l0) e;
h.info.compSolution <- Some e;
raise Logic.Frontend.Done
end
(Some 999, None, 2) (skinnyCTyp, None, Lazy.force mfs)
with
| Logic.Frontend.Done ->
HarpoonState.printf s "logic programming finished@,@?"
end
| Holes.LFInfo ->
let { lfGoal; cPsi; lfSolution } = h.info in
assert (lfSolution = None);
let typ = Whnf.normTyp lfGoal in
dprintf
begin fun p ->
p.fmt "[harpoon] [solve] [holes] @[<v>goal: @[%a@]@]"
(P.fmt_ppr_lf_typ cDh cPsi P.l0) typ
end;
Logic.prepare ();
let (query, skinnyTyp, querySub, instMVars) =
Logic.Convert.typToQuery cDh cPsi (typ, 0)
in
try
Logic.Solver.solve cDh cPsi query
begin fun (cPsi, tM) ->
HarpoonState.printf s "found solution: @[%a@]@,@?"
(P.fmt_ppr_lf_normal cDh cPsi P.l0) tM;
h.info.lfSolution <- Some (tM, LF.Shift 0);
raise Logic.Frontend.Done
end
(Some 100)
with
| Logic.Frontend.Done ->
HarpoonState.printf s "logic programming finished@,@?"
in
let { cD; cG; cIH } = g.context in
match cmd with
| Command.Theorem cmd ->
begin match cmd with
| `list ->
HarpoonState.printf s "@[<v>%a@,@,Current theorem is first.@]"
Session.fmt_ppr_theorem_list c
| `defer -> Session.defer_theorem c
| `show_ihs ->
let f i =
HarpoonState.printf s "%d. @[%a@]@,"
(i + 1)
(P.fmt_ppr_cmp_ih g.context.cD g.context.cG)
in
HarpoonState.printf s "@[<v>There are %d IHs:@,"
(Context.length g.context.cIH);
Context.to_list g.context.cIH |> List.iteri f;
HarpoonState.printf s "@]"
| `dump_proof path ->
dump_proof t path
| `show_proof ->
Theorem.show_proof t
end
| Command.Session cmd ->
begin match cmd with
| `list ->
HarpoonState.printf s "@[<v>%a@,@,Current session and theorem are first.@]"
HarpoonState.fmt_ppr_session_list s
| `defer -> HarpoonState.defer_session s
| `create -> ignore (HarpoonState.session_configuration_wizard s)
| `serialize -> HarpoonState.serialize s (c, t, g)
end
| Command.Subgoal cmd ->
begin match cmd with
| `list -> Theorem.show_subgoals t
| `defer -> Theorem.defer_subgoal t
end
| Command.SelectTheorem name ->
if Bool.not (HarpoonState.select_theorem s name) then
HarpoonState.printf s
"There is no theorem by name %a."
Name.pp name
| Command.Rename { rename_from=x_src; rename_to=x_dst; level } ->
if Bool.not (Theorem.rename_variable x_src x_dst level t g) then
Error.(throw (NoSuchVariable (x_src, level)))
| Command.ToggleAutomation (automation_kind, automation_change) ->
Automation.toggle
(HarpoonState.automation_state s)
automation_kind
automation_change
| Command.Type i ->
let (hs, i, tau) =
Elab.exp' (Some (Theorem.get_cid t))
cIH cD cG (Lazy.force mfs) i
in
HarpoonState.printf s
"- @[<hov 2>@[%a@] :@ @[%a@]@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
| Command.Info (k, n) ->
begin match k with
| `prog ->
let open Option in
begin match CompS.(index_of_name_opt n $> get) with
| None ->
HarpoonState.printf s
"- No such theorem by name %a" Name.pp n
| Some e ->
HarpoonState.printf s
"- @[%a@]"
P.fmt_ppr_cmp_comp_prog_info e
end
end
| Command.Translate n ->
let open Option in
begin match CompS.(index_of_name_opt n $> get) with
| Some e ->
HarpoonState.printf s "%a"
Translate.fmt_ppr_result (Translate.entry e)
| None ->
HarpoonState.printf s "No such theorem by name %a defined."
Name.pp n
end
| Command.Undo ->
if Bool.not Theorem.(history_step t Direction.backward) then
HarpoonState.printf s "Nothing to undo in the current theorem's timeline."
| Command.Redo ->
if Bool.not Theorem.(history_step t Direction.forward) then
HarpoonState.printf s "Nothing to redo in the current theorem's timeline."
| Command.History ->
let open Format in
let (past, future) = Theorem.get_history_names t in
let future = List.rev future in
let line ppf = function
| _ when List.nonempty future ->
fprintf ppf "@,-----@,"
| _ -> ()
in
let future_remark ppf = function
| _ when List.nonempty future ->
fprintf ppf "- @[%a@]"
pp_print_string
"Commands below the line would be undone. \
Commands above the line would be redone."
| _ -> ()
in
HarpoonState.printf s
"@[<v 2>History:\
@,@[<v>%a@]%a@[<v>%a@]@]@,%a@,"
(pp_print_list ~pp_sep: pp_print_cut pp_print_string)
future
line ()
(pp_print_list ~pp_sep: pp_print_cut pp_print_string)
past
future_remark ()
| Command.Help ->
HarpoonState.printf s
"@[<v>Built-in help is not implemented.\
@,See online documentation: -lang.readthedocs.io/@]"
| Command.Unbox (i, name, modifier) ->
let (hs, m, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
Tactic.unbox m tau name modifier t g
| Command.Intros names ->
Tactic.intros names t g
| Command.Split (split_kind, i) ->
let (hs, m, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
Tactic.split split_kind m tau (Lazy.force mfs) t g
| Command.MSplit (loc, name) ->
let i, tau = Elab.mvar cD loc name in
Tactic.split `split i tau (Lazy.force mfs) t g
| Command.By (i, name) ->
let (hs, i, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
dprintf
begin fun p ->
p.fmt "@[<v>[harpoon-By] elaborated invocation:@,%a@ : %a@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
end;
if Whnf.closedExp i then
(List.iter solve_hole hs; Tactic.invoke i tau name t g)
else
HarpoonState.printf s
"@[<v>Elaborated expression\
@, @[%a@]\
@,of type\
@, @[%a@]\
@,is not closed.\
@,Both the expression and its type must be closed for use with `by`.@]"
(P.fmt_ppr_cmp_exp cD cG P.l0) i
(P.fmt_ppr_cmp_typ cD P.l0) tau
| Command.Suffices (i, tau_list) ->
let (hs, i, tau) =
let cid = Theorem.get_cid t in
Elab.exp' (Some cid) cIH cD cG (Lazy.force mfs) i
in
begin match Session.infer_invocation_kind c i with
| `ih ->
HarpoonState.printf s "inductive use of `suffices by ...` is not currently supported"
| `lemma ->
begin match hs with
| _ :: _ ->
Theorem.printf t "holes are not supported for `suffices by _ ...`"
| [] ->
let elab_suffices_typ tau_ext : suffices_typ =
map_suffices_typ (Elab.typ cD) tau_ext
in
let tau_list = List.map elab_suffices_typ tau_list in
Tactic.suffices i tau_list tau t g
end
end
| Command.Solve e ->
let cid = Theorem.get_cid t in
let (hs, e) =
Elab.exp (Some cid) cIH cD cG (Lazy.force mfs) e g.goal
in
dprnt "[harpoon] [solve] elaboration finished";
State.printf s " Found % d hole(s ) in solution@. " ( hs ) ;
List.iter solve_hole hs;
dprnt "[harpoon] [solve] double-check!";
Check.Comp.check (Some cid) cD cG (Lazy.force mfs) ~cIH: cIH e g.goal;
dprnt "[harpoon] [solve] double-check DONE";
let e = Whnf.cnormExp (e, Whnf.m_id) in
if Whnf.closedExp e then
(Comp.solve e |> Tactic.solve) t g
else
HarpoonState.printf s "Solution contains uninstantiated metavariables."
| Command.AutoInvertSolve d ->
let { cD; cG; cIH } = g.context in
let (tau, ms) = g.goal in
let tau = Whnf.cnormCTyp (tau, ms) in
let (mquery, _, _, instMMVars) =
let (typ',k) = Abstract.comptyp tau in
Logic.Convert.comptypToMQuery (typ',k)
in
let (theorem, _) = Theorem.get_statement t in
let cid = Theorem.get_cid t in
let opt_witness = Logic.Frontend.msolve_tactic (cD, cG, cIH)
(mquery, tau, instMMVars) d
(theorem, cid, 1, (Lazy.force mfs))
in
begin
match opt_witness with
| None ->
HarpoonState.printf s "cgSolve cannot find a proof in cD = %a, cG = %a, skinny = %a, inst size = %d."
P.(fmt_ppr_lf_mctx l0) cD
P.(fmt_ppr_cmp_gctx cD l0) cG
P.(fmt_ppr_cmp_typ cD l0) tau
(List.length(instMMVars))
| Some e ->
(Comp.solve e |> Tactic.solve) t g
end
| Command.InductiveAutoSolve d ->
let { cD; cG; cIH } = g.context in
let (tau, ms) = g.goal in
let tau = Whnf.cnormCTyp (tau, ms) in
let (mquery, _, _, instMMVars) =
let (typ',k) = Abstract.comptyp tau in
Logic.Convert.comptypToMQuery (typ',k)
in
let (theorem, _) = Theorem.get_statement t in
let cid = Theorem.get_cid t in
let opt_witness = Logic.Frontend.msolve_tactic (cD, cG, cIH)
(mquery, tau, instMMVars) d
(theorem, cid, 2, (Lazy.force mfs))
in
begin
match opt_witness with
| None ->
HarpoonState.printf s "cgSolve cannot find a proof in cD = %a, cG = %a, skinny = %a, inst size = %d."
P.(fmt_ppr_lf_mctx l0) cD
P.(fmt_ppr_cmp_gctx cD l0) cG
P.(fmt_ppr_cmp_typ cD l0) tau
(List.length(instMMVars))
| Some e ->
(Comp.solve e |> Tactic.solve) t g
end
|
d476f643aa0d715476c082d8d1f001724a40557efee5ed98736907583bde4f39 | hugoduncan/makejack | impl.clj | (ns makejack.deps-file.impl
(:require
[babashka.fs :as fs]
[rewrite-clj.node :as n]
[rewrite-clj.zip :as z]))
(defn kw=?
[kw]
(fn [z]
(when-let [node (z/node z)]
(and (= :token (n/tag node))
(= (str kw) (n/string node))))))
(defn string=?
[s]
(fn [z]
(when-let [node (z/node z)]
(and (= :token (n/tag node))
(= s (n/string node))))))
(defn- update-kv
[k v z]
(if-let [zz (z/get z k)]
(z/replace zz (n/token-node v))
z))
(defn- update-in-artifact
[z update-vals]
(loop [z z
update-vals update-vals]
(let [[[k v] & more] update-vals]
(if k
(recur (z/subedit-node z (partial update-kv k v)) more)
z))))
(defn- update-in-deps-val
[z artifact-name update-vals]
(if-let [zz (z/get z artifact-name)]
(z/subedit-node zz #(update-in-artifact % update-vals))
z))
(defn update-in-deps-keys
[src artifact-name update-vals]
(loop [z (z/of-string src)]
(if-let [zz (z/find-depth-first z (kw=? :deps))]
(recur
(->
(z/right zz)
(z/subedit-node
#(update-in-deps-val % artifact-name update-vals))
))
(z/root-string z))))
(defn project-edn-path
^java.nio.file.Path [{:keys [dir]}]
(fs/path (or dir ".") "project.edn"))
(defn deps-edn-path
^java.nio.file.Path [{:keys [dir]}]
(fs/path (or dir ".") "deps.edn"))
(defn update-dep
[{:keys [artifact-name] :as params}]
(assert artifact-name "must pass :artifact-name")
(assert (symbol? artifact-name) ":artifact-name must have a symbol as value")
(let [f (-> params deps-edn-path fs/file)
src (slurp f)
update-vals (select-keys params [:git/sha :git/tag :mvn/version])
new-s (update-in-deps-keys src artifact-name update-vals)]
(if new-s
(spit f new-s)
(throw (ex-info
"Failed to write deps.edn"
{:path (str f)})))))
| null | https://raw.githubusercontent.com/hugoduncan/makejack/a92d409233c46250f7c5a6b3e0a0aa6dd2211de6/components/deps-file/src/makejack/deps_file/impl.clj | clojure | (ns makejack.deps-file.impl
(:require
[babashka.fs :as fs]
[rewrite-clj.node :as n]
[rewrite-clj.zip :as z]))
(defn kw=?
[kw]
(fn [z]
(when-let [node (z/node z)]
(and (= :token (n/tag node))
(= (str kw) (n/string node))))))
(defn string=?
[s]
(fn [z]
(when-let [node (z/node z)]
(and (= :token (n/tag node))
(= s (n/string node))))))
(defn- update-kv
[k v z]
(if-let [zz (z/get z k)]
(z/replace zz (n/token-node v))
z))
(defn- update-in-artifact
[z update-vals]
(loop [z z
update-vals update-vals]
(let [[[k v] & more] update-vals]
(if k
(recur (z/subedit-node z (partial update-kv k v)) more)
z))))
(defn- update-in-deps-val
[z artifact-name update-vals]
(if-let [zz (z/get z artifact-name)]
(z/subedit-node zz #(update-in-artifact % update-vals))
z))
(defn update-in-deps-keys
[src artifact-name update-vals]
(loop [z (z/of-string src)]
(if-let [zz (z/find-depth-first z (kw=? :deps))]
(recur
(->
(z/right zz)
(z/subedit-node
#(update-in-deps-val % artifact-name update-vals))
))
(z/root-string z))))
(defn project-edn-path
^java.nio.file.Path [{:keys [dir]}]
(fs/path (or dir ".") "project.edn"))
(defn deps-edn-path
^java.nio.file.Path [{:keys [dir]}]
(fs/path (or dir ".") "deps.edn"))
(defn update-dep
[{:keys [artifact-name] :as params}]
(assert artifact-name "must pass :artifact-name")
(assert (symbol? artifact-name) ":artifact-name must have a symbol as value")
(let [f (-> params deps-edn-path fs/file)
src (slurp f)
update-vals (select-keys params [:git/sha :git/tag :mvn/version])
new-s (update-in-deps-keys src artifact-name update-vals)]
(if new-s
(spit f new-s)
(throw (ex-info
"Failed to write deps.edn"
{:path (str f)})))))
| |
2a1f88d66a29f6f12cb3cd410911c02d7a78764ea96eca988edd1b5a8ba6038c | MyDataFlow/ttalk-server | protobuffs_tests.erl | %%%-------------------------------------------------------------------
%%% File : protobuffs_tests.erl
Author : < >
%%% Description :
%%%
Created : 2 Aug 2010 by < >
%%%-------------------------------------------------------------------
-module(protobuffs_tests).
-compile(export_all).
-include("quickcheck_setup.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(DECODE, protobuffs:decode).
-define(ENCODE(A,B,C), iolist_to_binary(protobuffs:encode(A,B,C))).
-define(DECODE_PACKED, protobuffs:decode_packed).
-define(ENCODE_PACKED(A,B,C), iolist_to_binary(protobuffs:encode_packed(A,B,C))).
asciistring() ->
list(integer(0,127)).
bytestring() ->
list(integer(0,255)).
utf8char() ->
union([integer(0, 36095), integer(57344, 65533),
integer(65536, 1114111)]).
utf8string() -> list(utf8char()).
-ifdef(EQC).
eqc_module_test() ->
?assertEqual([], eqc:module(?MODULE)).
-endif.
-ifdef(PROPER).
proper_specs_test() ->
?assertEqual([],
(proper:check_specs(protobuffs, [long_result]))).
proper_module_test() ->
?assertEqual([],
(proper:module(?MODULE, [long_result]))).
-endif.
%%--------------------------------------------------------------------
%% Encode/Decode int32
%%--------------------------------------------------------------------
prop_int() ->
?FORALL({Id, Int}, {non_neg_integer(), integer()},
begin
{{Id, Int}, <<>>} =:=
(?DECODE((?ENCODE(Id, Int, int32)), int32))
end).
encode_int_test_() ->
[?_assertMatch(<<8, 150, 1>>, (?ENCODE(1, 150, int32))),
?_assertMatch(<<16, 145, 249, 255, 255, 255, 255, 255,
255, 255, 1>>,
(?ENCODE(2, (-879), int32)))].
decode_int_test_() ->
[?_assertMatch({{1, 150}, <<>>},
(?DECODE(<<8, 150, 1>>, int32))),
?_assertMatch({{2, -879}, <<>>},
(?DECODE(<<16, 145, 249, 255, 255, 255, 255, 255, 255,
255, 1>>,
int32)))].
%%--------------------------------------------------------------------
%% Encode/Decode string
%%--------------------------------------------------------------------
prop_string() ->
?FORALL({Id, String}, {non_neg_integer(), oneof([asciistring(), utf8string()])},
begin
{{Id, String}, <<>>} =:=
(?DECODE((?ENCODE(Id, String, string)), string))
end).
encode_string_test_() ->
[?_assertMatch(<<18, 7, 116, 101, 115, 116, 105, 110,
103>>,
(?ENCODE(2, "testing", string)))].
decode_string_test_() ->
[?_assertMatch({{2, "testing"}, <<>>},
(?DECODE(<<18, 7, 116, 101, 115, 116, 105, 110, 103>>,
string)))].
%%--------------------------------------------------------------------
%% Encode/Decode bool
%%--------------------------------------------------------------------
prop_bool() ->
?FORALL({Id, Bool},
{non_neg_integer(), oneof([boolean(), 0, 1])},
begin
Fun = fun (B) when B =:= 1; B =:= true -> true;
(B) when B =:= 0; B =:= false -> false
end,
{{Id, Fun(Bool)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Bool, bool)), bool))
end).
enclode_bool_test_() ->
[?_assertMatch(<<8, 1>>, (?ENCODE(1, true, bool))),
?_assertMatch(<<8, 0>>, (?ENCODE(1, false, bool))),
?_assertMatch(<<40, 1>>, (?ENCODE(5, 1, bool))),
?_assertMatch(<<40, 0>>, (?ENCODE(5, 0, bool)))].
decode_bool_test_() ->
[?_assertMatch({{1, true}, <<>>},
(?DECODE(<<8, 1>>, bool))),
?_assertMatch({{1, false}, <<>>},
(?DECODE(<<8, 0>>, bool)))].
%%--------------------------------------------------------------------
%% Encode/Decode enum
%%--------------------------------------------------------------------
prop_enum() ->
?FORALL({Id, Enum}, {non_neg_integer(), integer()},
begin
{{Id, Enum}, <<>>} =:=
(?DECODE((?ENCODE(Id, Enum, enum)), enum))
end).
encode_enum_test_() ->
[?_assertMatch(<<8, 5>>, (?ENCODE(1, 5, enum)))].
decode_enum_test_() ->
[?_assertMatch({{1, 5}, <<>>},
(?DECODE(<<8, 5>>, enum)))].
%%--------------------------------------------------------------------
%% Encode/Decode uint32
%%--------------------------------------------------------------------
prop_uint32() ->
?FORALL({Id, Uint32},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Uint32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Uint32, uint32)), uint32))
end).
encode_uint32_test_() ->
[?_assertMatch(<<32, 169, 18>>,
(?ENCODE(4, 2345, uint32)))].
decode_uint32_test_() ->
[?_assertMatch({{4, 2345}, <<>>},
(?DECODE(<<32, 169, 18>>, uint32)))].
%%--------------------------------------------------------------------
%% Encode/Decode sint32
%%--------------------------------------------------------------------
prop_sint32() ->
?FORALL({Id, Sint32}, {non_neg_integer(), integer()},
begin
{{Id, Sint32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sint32, sint32)), sint32))
end).
encode_sint32_test_() ->
[?_assertMatch(<<24, 137, 5>>,
(?ENCODE(3, (-325), sint32))),
?_assertMatch(<<32, 212, 3>>,
(?ENCODE(4, 234, sint32)))].
decode_sint32_test_() ->
[?_assertMatch({{3, -325}, <<>>},
(?DECODE(<<24, 137, 5>>, sint32))),
?_assertMatch({{4, 234}, <<>>},
(?DECODE(<<32, 212, 3>>, sint32)))].
%%--------------------------------------------------------------------
%% Encode/Decode int64
%%--------------------------------------------------------------------
prop_int64() ->
?FORALL({Id, Int64}, {non_neg_integer(), integer()},
begin
{{Id, Int64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Int64, int64)), int64))
end).
encode_int64_test_() ->
[?_assertMatch(<<16, 192, 212, 5>>,
(?ENCODE(2, 92736, int64)))].
decode_int64_test_() ->
[?_assertMatch({{2, 92736}, <<>>},
(?DECODE(<<16, 192, 212, 5>>, int64)))].
%%--------------------------------------------------------------------
Encode / Decode uint64
%%--------------------------------------------------------------------
prop_uint64() ->
?FORALL({Id, Uint64},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Uint64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Uint64, uint64)), uint64))
end).
encode_uint64_test_() ->
[?_assertMatch(<<40, 182, 141, 51>>,
(?ENCODE(5, 837302, uint64)))].
decode_uint64_test_() ->
[?_assertMatch({{5, 837302}, <<>>},
(?DECODE(<<40, 182, 141, 51>>, uint64)))].
%%--------------------------------------------------------------------
%% Encode/Decode sint64
%%--------------------------------------------------------------------
prop_sint64() ->
?FORALL({Id, Sint64}, {non_neg_integer(), integer()},
begin
{{Id, Sint64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sint64, sint64)), sint64))
end).
encode_sint64_test_() ->
[?_assertMatch(<<16, 189, 3>>,
(?ENCODE(2, (-223), sint64))),
?_assertMatch(<<32, 128, 8>>,
(?ENCODE(4, 512, sint64)))].
decode_sint64_test_() ->
[?_assertMatch({{2, -223}, <<>>},
(?DECODE(<<16, 189, 3>>, sint64))),
?_assertMatch({{4, 512}, <<>>},
(?DECODE(<<32, 128, 8>>, sint64)))].
%%--------------------------------------------------------------------
Encode / Decode fixed32
%%--------------------------------------------------------------------
prop_fixed32() ->
?FORALL({Id, Fixed32},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Fixed32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Fixed32, fixed32)), fixed32))
end).
encode_fixed32_test_() ->
[?_assertMatch(<<21, 172, 20, 0, 0>>,
(?ENCODE(2, 5292, fixed32)))].
decode_fixed32_test_() ->
[?_assertMatch({{2, 5292}, <<>>},
(?DECODE(<<21, 172, 20, 0, 0>>, fixed32)))].
%%--------------------------------------------------------------------
%% Encode/Decode sfixed32
%%--------------------------------------------------------------------
prop_sfixed32() ->
?FORALL({Id, Sfixed32}, {non_neg_integer(), integer()},
begin
{{Id, Sfixed32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sfixed32, sfixed32)), sfixed32))
end).
encode_sfixed32_test_() ->
[?_assertMatch(<<61, 182, 32, 0, 0>>,
(?ENCODE(7, 8374, sfixed32)))].
decode_sfixed32_test_() ->
[?_assertMatch({{7, 8374}, <<>>},
(?DECODE(<<61, 182, 32, 0, 0>>, sfixed32)))].
%%--------------------------------------------------------------------
%% Encode/Decode fixed64
%%--------------------------------------------------------------------
prop_fixed64() ->
?FORALL({Id, Fixed64},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Fixed64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Fixed64, fixed64)), fixed64))
end).
encode_fixed64_test_() ->
[?_assertMatch(<<161, 18, 83, 12, 0, 0, 0, 0, 0, 0>>,
(?ENCODE(292, 3155, fixed64)))].
decode_fixed64_test_() ->
[?_assertMatch({{292, 3155}, <<>>},
(?DECODE(<<161, 18, 83, 12, 0, 0, 0, 0, 0, 0>>,
fixed64)))].
%%--------------------------------------------------------------------
Encode / Decode sfixed64
%%--------------------------------------------------------------------
prop_sfixed64() ->
?FORALL({Id, Sfixed64}, {non_neg_integer(), integer()},
begin
{{Id, Sfixed64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sfixed64, sfixed64)), sfixed64))
end).
encode_sfixed64_test_() ->
[?_assertMatch(<<185, 1, 236, 1, 0, 0, 0, 0, 0, 0>>,
(?ENCODE(23, 492, sfixed64)))].
decode_sfixed64_test_() ->
[?_assertMatch({{23, 492}, <<>>},
(?DECODE(<<185, 1, 236, 1, 0, 0, 0, 0, 0, 0>>,
sfixed64)))].
%%--------------------------------------------------------------------
%% Encode/Decode bytes
%%--------------------------------------------------------------------
prop_bytes() ->
?FORALL({Id, Bytes},
{non_neg_integer(), oneof([bytestring(), binary()])},
begin
Fun = fun (B) when is_list(B) ->
list_to_binary(B);
(B) -> B
end,
{{Id, Fun(Bytes)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Bytes, bytes)), bytes))
end).
encode_bytes_test_() ->
[?_assertMatch(<<26, 3, 8, 150, 1>>,
(?ENCODE(3, <<8, 150, 1>>, bytes))),
?_assertMatch(<<34, 4, 84, 101, 115, 116>>,
(?ENCODE(4, "Test", bytes))),
?_assertMatch(<<34, 0>>, (?ENCODE(4, "", bytes))),
?_assertError(badarg, ?ENCODE(4, [256], bytes))].
decode_bytes_test_() ->
[?_assertMatch({{3, <<8, 150, 1>>}, <<>>},
(?DECODE(<<26, 3, 8, 150, 1>>, bytes))),
?_assertMatch({{4, <<"Test">>}, <<>>},
(?DECODE(<<34, 4, 84, 101, 115, 116>>, bytes))),
?_assertMatch({{4, <<>>}, <<>>},
(?DECODE(<<34, 0>>, bytes))),
?_assertMatch({{4, <<196, 128>>}, <<>>},
(?DECODE(<<34, 2, 196, 128>>, bytes)))].
%%--------------------------------------------------------------------
%% Encode/Decode float
%%--------------------------------------------------------------------
prop_float() ->
?FORALL({Id, Float},
{non_neg_integer(),
oneof([float(), integer(), nan, infinity,
'-infinity'])},
begin
Fun = fun (F) when is_float(F) ->
<<Return:32/little-float>> = <<F:32/little-float>>,
Return;
(F) when is_integer(F) -> F + 0.0;
(F) -> F
end,
{{Id, Fun(Float)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Float, float)), float))
end).
encode_float_test_() ->
[?_assertMatch(<<165, 5, 0, 0, 106, 67>>,
(?ENCODE(84, 234, float))),
?_assertMatch(<<29, 123, 148, 105, 68>>,
(?ENCODE(3, 9.3432e+2, float))),
?_assertMatch(<<45, 0, 0, 192, 255>>,
(?ENCODE(5, nan, float))),
?_assertMatch(<<69, 0, 0, 128, 127>>,
(?ENCODE(8, infinity, float))),
?_assertMatch(<<29, 0, 0, 128, 255>>,
(?ENCODE(3, '-infinity', float)))].
decode_float_test_() ->
[?_assertMatch({{84, 2.34e+2}, <<>>},
(?DECODE(<<165, 5, 0, 0, 106, 67>>, float))),
?_assertMatch({{5, nan}, <<>>},
(?DECODE(<<45, 0, 0, 192, 255>>, float))),
?_assertMatch({{8, infinity}, <<>>},
(?DECODE(<<69, 0, 0, 128, 127>>, float))),
?_assertMatch({{3, '-infinity'}, <<>>},
(?DECODE(<<29, 0, 0, 128, 255>>, float)))].
%%--------------------------------------------------------------------
%% Encode/Decode double
%%--------------------------------------------------------------------
prop_double() ->
?FORALL({Id, Double},
{non_neg_integer(),
oneof([float(), integer(), nan, infinity,
'-infinity'])},
begin
Fun = fun (D) when is_integer(D) -> D + 0.0;
(D) -> D
end,
{{Id, Fun(Double)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Double, double)), double))
end).
encode_double_test_() ->
[?_assertMatch(<<241, 1, 0, 0, 0, 0, 0, 44, 174, 64>>,
(?ENCODE(30, 3862, double))),
?_assertMatch(<<17, 0, 0, 0, 0, 0, 40, 138, 64>>,
(?ENCODE(2, 8.37e+2, double))),
?_assertMatch(<<41, 0, 0, 0, 0, 0, 0, 248, 255>>,
(?ENCODE(5, nan, double))),
?_assertMatch(<<65, 0, 0, 0, 0, 0, 0, 240, 127>>,
(?ENCODE(8, infinity, double))),
?_assertMatch(<<25, 0, 0, 0, 0, 0, 0, 240, 255>>,
(?ENCODE(3, '-infinity', double)))].
decode_double_test_() ->
[?_assertMatch({{2, 8.37e+2}, <<>>},
(?DECODE(<<17, 0, 0, 0, 0, 0, 40, 138, 64>>, double))),
?_assertMatch({{5, nan}, <<>>},
(?DECODE(<<41, 0, 0, 0, 0, 0, 0, 248, 255>>, double))),
?_assertMatch({{8, infinity}, <<>>},
(?DECODE(<<65, 0, 0, 0, 0, 0, 0, 240, 127>>, double))),
?_assertMatch({{3, '-infinity'}, <<>>},
(?DECODE(<<25, 0, 0, 0, 0, 0, 0, 240, 255>>, double)))].
%%--------------------------------------------------------------------
%% Encode/Decode packed repeated int32
%%--------------------------------------------------------------------
prop_packed_int32() ->
?FORALL({Id, Int32s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Int32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Int32s, int32)),
int32))
end).
encode_packed_int32_test_() ->
[?_assertMatch(<<34, 6, 3, 142, 2, 158, 167, 5>>,
(?ENCODE_PACKED(4, [3, 270, 86942], int32))),
?_assertMatch(<<>>, (?ENCODE_PACKED(4, [], int32)))].
decode_packed_int32_test_() ->
[?_assertMatch({{4, [3, 270, 86942]}, <<>>},
(?DECODE_PACKED(<<34, 6, 3, 142, 2, 158, 167, 5>>,
int32)))].
%%--------------------------------------------------------------------
%% Encode/Decode packed repeated bool
%%--------------------------------------------------------------------
prop_packed_bool() ->
?FORALL({Id, Bools},
{non_neg_integer(),
non_empty(list(oneof([boolean(), 0, 1])))},
begin
Fun = fun (1) -> true;
(0) -> false;
(B) -> B
end,
{{Id, lists:map(Fun, Bools)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Bools, bool)),
bool))
end).
prop_packed_enum() ->
?FORALL({Id, Enums},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Enums}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Enums, enum)),
enum))
end).
%%--------------------------------------------------------------------
%% Encode/Decode packed repeated enum
%%--------------------------------------------------------------------
encode_packed_enum_test_() ->
[?_assertMatch(<<2, 2, 0, 0>>,
(?ENCODE_PACKED(0, [0, 0], enum)))].
decode_packed_enum_test_() ->
[?_assertMatch({{_Id, [0, 0]}, <<>>},
(?DECODE_PACKED(<<2, 2, 0, 0>>, enum)))].
prop_packed_uint32() ->
?FORALL({Id, Uint32s},
{non_neg_integer(), non_empty(list(non_neg_integer()))},
begin
{{Id, Uint32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Uint32s, uint32)),
uint32))
end).
%%--------------------------------------------------------------------
Encode / Decode packed repeated sint32
%%--------------------------------------------------------------------
prop_packed_sint32() ->
?FORALL({Id, Sint32s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Sint32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Sint32s, sint32)),
sint32))
end).
%%--------------------------------------------------------------------
Encode / Decode packed repeated int64
%%--------------------------------------------------------------------
prop_packed_int64() ->
?FORALL({Id, Int64s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Int64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Int64s, int64)),
int64))
end).
%%--------------------------------------------------------------------
Encode / Decode packed repeated uint64
%%--------------------------------------------------------------------
prop_packed_uint64() ->
?FORALL({Id, Uint64s},
{non_neg_integer(), non_empty(list(non_neg_integer()))},
begin
{{Id, Uint64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Uint64s, uint64)),
uint64))
end).
%%--------------------------------------------------------------------
Encode / Decode packed repeated sint64
%%--------------------------------------------------------------------
prop_packed_sint64() ->
?FORALL({Id, Sint64s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Sint64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Sint64s, sint64)),
sint64))
end).
%%--------------------------------------------------------------------
%% Encode/Decode packed repeated float
%%--------------------------------------------------------------------
prop_packed_float() ->
?FORALL({Id, Floats},
{non_neg_integer(),
non_empty(list(oneof([float(), integer()])))},
begin
Fun = fun (F) when is_float(F) ->
<<Return:32/little-float>> = <<F:32/little-float>>,
Return;
(F) when is_integer(F) -> F + 0.0;
(F) -> F
end,
{{Id, lists:map(Fun, Floats)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Floats, float)),
float))
end).
%%--------------------------------------------------------------------
%% Encode/Decode packed repeated double
%%--------------------------------------------------------------------
prop_packed_double() ->
?FORALL({Id, Doubles},
{non_neg_integer(),
non_empty(list(oneof([float(), integer()])))},
begin
Fun = fun (D) when is_integer(D) -> D + 0.0;
(D) -> D
end,
{{Id, lists:map(Fun, Doubles)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Doubles, double)),
double))
end).
%%--------------------------------------------------------------------
%% Skip fields in stream
%%--------------------------------------------------------------------
skip_next_field_test_() ->
[
%% Skip a varint with no remainder
?_assertEqual({ok,<<>>}, protobuffs:skip_next_field(<<32,0>>)),
%% Skip a varint
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<32,0,8,1>>)),
%% Skip a string
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<18,3,102,111,111,8,1>>)),
Skip a 32 - bit
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<21,32,0,0,0,8,1>>)),
Skip a 64 - bit
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<17,32,0,0,0,0,0,0,0,8,1>>))
].
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/protobuffs/test/protobuffs_tests.erl | erlang | -------------------------------------------------------------------
File : protobuffs_tests.erl
Description :
-------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode int32
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode string
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode bool
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode enum
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode uint32
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode sint32
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode int64
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode sint64
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode sfixed32
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode fixed64
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode bytes
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode float
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode double
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode packed repeated int32
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode packed repeated bool
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode packed repeated enum
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode packed repeated float
--------------------------------------------------------------------
--------------------------------------------------------------------
Encode/Decode packed repeated double
--------------------------------------------------------------------
--------------------------------------------------------------------
Skip fields in stream
--------------------------------------------------------------------
Skip a varint with no remainder
Skip a varint
Skip a string | Author : < >
Created : 2 Aug 2010 by < >
-module(protobuffs_tests).
-compile(export_all).
-include("quickcheck_setup.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(DECODE, protobuffs:decode).
-define(ENCODE(A,B,C), iolist_to_binary(protobuffs:encode(A,B,C))).
-define(DECODE_PACKED, protobuffs:decode_packed).
-define(ENCODE_PACKED(A,B,C), iolist_to_binary(protobuffs:encode_packed(A,B,C))).
asciistring() ->
list(integer(0,127)).
bytestring() ->
list(integer(0,255)).
utf8char() ->
union([integer(0, 36095), integer(57344, 65533),
integer(65536, 1114111)]).
utf8string() -> list(utf8char()).
-ifdef(EQC).
eqc_module_test() ->
?assertEqual([], eqc:module(?MODULE)).
-endif.
-ifdef(PROPER).
proper_specs_test() ->
?assertEqual([],
(proper:check_specs(protobuffs, [long_result]))).
proper_module_test() ->
?assertEqual([],
(proper:module(?MODULE, [long_result]))).
-endif.
prop_int() ->
?FORALL({Id, Int}, {non_neg_integer(), integer()},
begin
{{Id, Int}, <<>>} =:=
(?DECODE((?ENCODE(Id, Int, int32)), int32))
end).
encode_int_test_() ->
[?_assertMatch(<<8, 150, 1>>, (?ENCODE(1, 150, int32))),
?_assertMatch(<<16, 145, 249, 255, 255, 255, 255, 255,
255, 255, 1>>,
(?ENCODE(2, (-879), int32)))].
decode_int_test_() ->
[?_assertMatch({{1, 150}, <<>>},
(?DECODE(<<8, 150, 1>>, int32))),
?_assertMatch({{2, -879}, <<>>},
(?DECODE(<<16, 145, 249, 255, 255, 255, 255, 255, 255,
255, 1>>,
int32)))].
prop_string() ->
?FORALL({Id, String}, {non_neg_integer(), oneof([asciistring(), utf8string()])},
begin
{{Id, String}, <<>>} =:=
(?DECODE((?ENCODE(Id, String, string)), string))
end).
encode_string_test_() ->
[?_assertMatch(<<18, 7, 116, 101, 115, 116, 105, 110,
103>>,
(?ENCODE(2, "testing", string)))].
decode_string_test_() ->
[?_assertMatch({{2, "testing"}, <<>>},
(?DECODE(<<18, 7, 116, 101, 115, 116, 105, 110, 103>>,
string)))].
prop_bool() ->
?FORALL({Id, Bool},
{non_neg_integer(), oneof([boolean(), 0, 1])},
begin
Fun = fun (B) when B =:= 1; B =:= true -> true;
(B) when B =:= 0; B =:= false -> false
end,
{{Id, Fun(Bool)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Bool, bool)), bool))
end).
enclode_bool_test_() ->
[?_assertMatch(<<8, 1>>, (?ENCODE(1, true, bool))),
?_assertMatch(<<8, 0>>, (?ENCODE(1, false, bool))),
?_assertMatch(<<40, 1>>, (?ENCODE(5, 1, bool))),
?_assertMatch(<<40, 0>>, (?ENCODE(5, 0, bool)))].
decode_bool_test_() ->
[?_assertMatch({{1, true}, <<>>},
(?DECODE(<<8, 1>>, bool))),
?_assertMatch({{1, false}, <<>>},
(?DECODE(<<8, 0>>, bool)))].
prop_enum() ->
?FORALL({Id, Enum}, {non_neg_integer(), integer()},
begin
{{Id, Enum}, <<>>} =:=
(?DECODE((?ENCODE(Id, Enum, enum)), enum))
end).
encode_enum_test_() ->
[?_assertMatch(<<8, 5>>, (?ENCODE(1, 5, enum)))].
decode_enum_test_() ->
[?_assertMatch({{1, 5}, <<>>},
(?DECODE(<<8, 5>>, enum)))].
prop_uint32() ->
?FORALL({Id, Uint32},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Uint32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Uint32, uint32)), uint32))
end).
encode_uint32_test_() ->
[?_assertMatch(<<32, 169, 18>>,
(?ENCODE(4, 2345, uint32)))].
decode_uint32_test_() ->
[?_assertMatch({{4, 2345}, <<>>},
(?DECODE(<<32, 169, 18>>, uint32)))].
prop_sint32() ->
?FORALL({Id, Sint32}, {non_neg_integer(), integer()},
begin
{{Id, Sint32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sint32, sint32)), sint32))
end).
encode_sint32_test_() ->
[?_assertMatch(<<24, 137, 5>>,
(?ENCODE(3, (-325), sint32))),
?_assertMatch(<<32, 212, 3>>,
(?ENCODE(4, 234, sint32)))].
decode_sint32_test_() ->
[?_assertMatch({{3, -325}, <<>>},
(?DECODE(<<24, 137, 5>>, sint32))),
?_assertMatch({{4, 234}, <<>>},
(?DECODE(<<32, 212, 3>>, sint32)))].
prop_int64() ->
?FORALL({Id, Int64}, {non_neg_integer(), integer()},
begin
{{Id, Int64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Int64, int64)), int64))
end).
encode_int64_test_() ->
[?_assertMatch(<<16, 192, 212, 5>>,
(?ENCODE(2, 92736, int64)))].
decode_int64_test_() ->
[?_assertMatch({{2, 92736}, <<>>},
(?DECODE(<<16, 192, 212, 5>>, int64)))].
Encode / Decode uint64
prop_uint64() ->
?FORALL({Id, Uint64},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Uint64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Uint64, uint64)), uint64))
end).
encode_uint64_test_() ->
[?_assertMatch(<<40, 182, 141, 51>>,
(?ENCODE(5, 837302, uint64)))].
decode_uint64_test_() ->
[?_assertMatch({{5, 837302}, <<>>},
(?DECODE(<<40, 182, 141, 51>>, uint64)))].
prop_sint64() ->
?FORALL({Id, Sint64}, {non_neg_integer(), integer()},
begin
{{Id, Sint64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sint64, sint64)), sint64))
end).
encode_sint64_test_() ->
[?_assertMatch(<<16, 189, 3>>,
(?ENCODE(2, (-223), sint64))),
?_assertMatch(<<32, 128, 8>>,
(?ENCODE(4, 512, sint64)))].
decode_sint64_test_() ->
[?_assertMatch({{2, -223}, <<>>},
(?DECODE(<<16, 189, 3>>, sint64))),
?_assertMatch({{4, 512}, <<>>},
(?DECODE(<<32, 128, 8>>, sint64)))].
Encode / Decode fixed32
prop_fixed32() ->
?FORALL({Id, Fixed32},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Fixed32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Fixed32, fixed32)), fixed32))
end).
encode_fixed32_test_() ->
[?_assertMatch(<<21, 172, 20, 0, 0>>,
(?ENCODE(2, 5292, fixed32)))].
decode_fixed32_test_() ->
[?_assertMatch({{2, 5292}, <<>>},
(?DECODE(<<21, 172, 20, 0, 0>>, fixed32)))].
prop_sfixed32() ->
?FORALL({Id, Sfixed32}, {non_neg_integer(), integer()},
begin
{{Id, Sfixed32}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sfixed32, sfixed32)), sfixed32))
end).
encode_sfixed32_test_() ->
[?_assertMatch(<<61, 182, 32, 0, 0>>,
(?ENCODE(7, 8374, sfixed32)))].
decode_sfixed32_test_() ->
[?_assertMatch({{7, 8374}, <<>>},
(?DECODE(<<61, 182, 32, 0, 0>>, sfixed32)))].
prop_fixed64() ->
?FORALL({Id, Fixed64},
{non_neg_integer(), non_neg_integer()},
begin
{{Id, Fixed64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Fixed64, fixed64)), fixed64))
end).
encode_fixed64_test_() ->
[?_assertMatch(<<161, 18, 83, 12, 0, 0, 0, 0, 0, 0>>,
(?ENCODE(292, 3155, fixed64)))].
decode_fixed64_test_() ->
[?_assertMatch({{292, 3155}, <<>>},
(?DECODE(<<161, 18, 83, 12, 0, 0, 0, 0, 0, 0>>,
fixed64)))].
Encode / Decode sfixed64
prop_sfixed64() ->
?FORALL({Id, Sfixed64}, {non_neg_integer(), integer()},
begin
{{Id, Sfixed64}, <<>>} =:=
(?DECODE((?ENCODE(Id, Sfixed64, sfixed64)), sfixed64))
end).
encode_sfixed64_test_() ->
[?_assertMatch(<<185, 1, 236, 1, 0, 0, 0, 0, 0, 0>>,
(?ENCODE(23, 492, sfixed64)))].
decode_sfixed64_test_() ->
[?_assertMatch({{23, 492}, <<>>},
(?DECODE(<<185, 1, 236, 1, 0, 0, 0, 0, 0, 0>>,
sfixed64)))].
prop_bytes() ->
?FORALL({Id, Bytes},
{non_neg_integer(), oneof([bytestring(), binary()])},
begin
Fun = fun (B) when is_list(B) ->
list_to_binary(B);
(B) -> B
end,
{{Id, Fun(Bytes)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Bytes, bytes)), bytes))
end).
encode_bytes_test_() ->
[?_assertMatch(<<26, 3, 8, 150, 1>>,
(?ENCODE(3, <<8, 150, 1>>, bytes))),
?_assertMatch(<<34, 4, 84, 101, 115, 116>>,
(?ENCODE(4, "Test", bytes))),
?_assertMatch(<<34, 0>>, (?ENCODE(4, "", bytes))),
?_assertError(badarg, ?ENCODE(4, [256], bytes))].
decode_bytes_test_() ->
[?_assertMatch({{3, <<8, 150, 1>>}, <<>>},
(?DECODE(<<26, 3, 8, 150, 1>>, bytes))),
?_assertMatch({{4, <<"Test">>}, <<>>},
(?DECODE(<<34, 4, 84, 101, 115, 116>>, bytes))),
?_assertMatch({{4, <<>>}, <<>>},
(?DECODE(<<34, 0>>, bytes))),
?_assertMatch({{4, <<196, 128>>}, <<>>},
(?DECODE(<<34, 2, 196, 128>>, bytes)))].
prop_float() ->
?FORALL({Id, Float},
{non_neg_integer(),
oneof([float(), integer(), nan, infinity,
'-infinity'])},
begin
Fun = fun (F) when is_float(F) ->
<<Return:32/little-float>> = <<F:32/little-float>>,
Return;
(F) when is_integer(F) -> F + 0.0;
(F) -> F
end,
{{Id, Fun(Float)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Float, float)), float))
end).
encode_float_test_() ->
[?_assertMatch(<<165, 5, 0, 0, 106, 67>>,
(?ENCODE(84, 234, float))),
?_assertMatch(<<29, 123, 148, 105, 68>>,
(?ENCODE(3, 9.3432e+2, float))),
?_assertMatch(<<45, 0, 0, 192, 255>>,
(?ENCODE(5, nan, float))),
?_assertMatch(<<69, 0, 0, 128, 127>>,
(?ENCODE(8, infinity, float))),
?_assertMatch(<<29, 0, 0, 128, 255>>,
(?ENCODE(3, '-infinity', float)))].
decode_float_test_() ->
[?_assertMatch({{84, 2.34e+2}, <<>>},
(?DECODE(<<165, 5, 0, 0, 106, 67>>, float))),
?_assertMatch({{5, nan}, <<>>},
(?DECODE(<<45, 0, 0, 192, 255>>, float))),
?_assertMatch({{8, infinity}, <<>>},
(?DECODE(<<69, 0, 0, 128, 127>>, float))),
?_assertMatch({{3, '-infinity'}, <<>>},
(?DECODE(<<29, 0, 0, 128, 255>>, float)))].
prop_double() ->
?FORALL({Id, Double},
{non_neg_integer(),
oneof([float(), integer(), nan, infinity,
'-infinity'])},
begin
Fun = fun (D) when is_integer(D) -> D + 0.0;
(D) -> D
end,
{{Id, Fun(Double)}, <<>>} =:=
(?DECODE((?ENCODE(Id, Double, double)), double))
end).
encode_double_test_() ->
[?_assertMatch(<<241, 1, 0, 0, 0, 0, 0, 44, 174, 64>>,
(?ENCODE(30, 3862, double))),
?_assertMatch(<<17, 0, 0, 0, 0, 0, 40, 138, 64>>,
(?ENCODE(2, 8.37e+2, double))),
?_assertMatch(<<41, 0, 0, 0, 0, 0, 0, 248, 255>>,
(?ENCODE(5, nan, double))),
?_assertMatch(<<65, 0, 0, 0, 0, 0, 0, 240, 127>>,
(?ENCODE(8, infinity, double))),
?_assertMatch(<<25, 0, 0, 0, 0, 0, 0, 240, 255>>,
(?ENCODE(3, '-infinity', double)))].
decode_double_test_() ->
[?_assertMatch({{2, 8.37e+2}, <<>>},
(?DECODE(<<17, 0, 0, 0, 0, 0, 40, 138, 64>>, double))),
?_assertMatch({{5, nan}, <<>>},
(?DECODE(<<41, 0, 0, 0, 0, 0, 0, 248, 255>>, double))),
?_assertMatch({{8, infinity}, <<>>},
(?DECODE(<<65, 0, 0, 0, 0, 0, 0, 240, 127>>, double))),
?_assertMatch({{3, '-infinity'}, <<>>},
(?DECODE(<<25, 0, 0, 0, 0, 0, 0, 240, 255>>, double)))].
prop_packed_int32() ->
?FORALL({Id, Int32s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Int32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Int32s, int32)),
int32))
end).
encode_packed_int32_test_() ->
[?_assertMatch(<<34, 6, 3, 142, 2, 158, 167, 5>>,
(?ENCODE_PACKED(4, [3, 270, 86942], int32))),
?_assertMatch(<<>>, (?ENCODE_PACKED(4, [], int32)))].
decode_packed_int32_test_() ->
[?_assertMatch({{4, [3, 270, 86942]}, <<>>},
(?DECODE_PACKED(<<34, 6, 3, 142, 2, 158, 167, 5>>,
int32)))].
prop_packed_bool() ->
?FORALL({Id, Bools},
{non_neg_integer(),
non_empty(list(oneof([boolean(), 0, 1])))},
begin
Fun = fun (1) -> true;
(0) -> false;
(B) -> B
end,
{{Id, lists:map(Fun, Bools)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Bools, bool)),
bool))
end).
prop_packed_enum() ->
?FORALL({Id, Enums},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Enums}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Enums, enum)),
enum))
end).
encode_packed_enum_test_() ->
[?_assertMatch(<<2, 2, 0, 0>>,
(?ENCODE_PACKED(0, [0, 0], enum)))].
decode_packed_enum_test_() ->
[?_assertMatch({{_Id, [0, 0]}, <<>>},
(?DECODE_PACKED(<<2, 2, 0, 0>>, enum)))].
prop_packed_uint32() ->
?FORALL({Id, Uint32s},
{non_neg_integer(), non_empty(list(non_neg_integer()))},
begin
{{Id, Uint32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Uint32s, uint32)),
uint32))
end).
Encode / Decode packed repeated sint32
prop_packed_sint32() ->
?FORALL({Id, Sint32s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Sint32s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Sint32s, sint32)),
sint32))
end).
Encode / Decode packed repeated int64
prop_packed_int64() ->
?FORALL({Id, Int64s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Int64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Int64s, int64)),
int64))
end).
Encode / Decode packed repeated uint64
prop_packed_uint64() ->
?FORALL({Id, Uint64s},
{non_neg_integer(), non_empty(list(non_neg_integer()))},
begin
{{Id, Uint64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Uint64s, uint64)),
uint64))
end).
Encode / Decode packed repeated sint64
prop_packed_sint64() ->
?FORALL({Id, Sint64s},
{non_neg_integer(), non_empty(list(integer()))},
begin
{{Id, Sint64s}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Sint64s, sint64)),
sint64))
end).
prop_packed_float() ->
?FORALL({Id, Floats},
{non_neg_integer(),
non_empty(list(oneof([float(), integer()])))},
begin
Fun = fun (F) when is_float(F) ->
<<Return:32/little-float>> = <<F:32/little-float>>,
Return;
(F) when is_integer(F) -> F + 0.0;
(F) -> F
end,
{{Id, lists:map(Fun, Floats)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Floats, float)),
float))
end).
prop_packed_double() ->
?FORALL({Id, Doubles},
{non_neg_integer(),
non_empty(list(oneof([float(), integer()])))},
begin
Fun = fun (D) when is_integer(D) -> D + 0.0;
(D) -> D
end,
{{Id, lists:map(Fun, Doubles)}, <<>>} =:=
(?DECODE_PACKED((?ENCODE_PACKED(Id, Doubles, double)),
double))
end).
skip_next_field_test_() ->
[
?_assertEqual({ok,<<>>}, protobuffs:skip_next_field(<<32,0>>)),
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<32,0,8,1>>)),
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<18,3,102,111,111,8,1>>)),
Skip a 32 - bit
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<21,32,0,0,0,8,1>>)),
Skip a 64 - bit
?_assertEqual({ok,<<8,1>>}, protobuffs:skip_next_field(<<17,32,0,0,0,0,0,0,0,8,1>>))
].
|
2211788e9629c286fdfe7a95a35cc92c127f779cdbb3b18122c6755e110ee0e8 | al3623/rippl | type_inference.ml | open Ast
open Tast
open Get_fresh_var
open Iast
open List
open Pretty_type_print
module SS = Set.Make(String);;
module SMap = Map.Make(String);;
module SubstMap = Map.Make(String);;
(* mappings from term variables to tforall *)
module TyEnvMap = Map.Make(String);;
(* returns a set of free type variables *)
let printEnv env =
print_string "[";
TyEnvMap.iter (fun key -> fun ty ->
print_string (key ^ " :: " ^ (ty_to_str ty)^", ")) env;
print_endline "]"
let rec ftv = function
| Tvar(n) -> SS.add n SS.empty
| Int -> SS.empty
| Bool -> SS.empty
| Float -> SS.empty
| Char -> SS.empty
| Tarrow (t1, t2) -> SS.union (ftv t1) (ftv t2)
| TconList (t) -> ftv t
| TconTuple (t1, t2) -> SS.union (ftv t1) (ftv t2)
| Tforall (stlst, t) -> SS.diff (ftv t) (SS.of_list stlst)
| Tmaybe (t) -> ftv t
let rec apply s = function
| Tvar(n) ->
(match SubstMap.find_opt n s with
| Some t -> apply s t
| None -> Tvar(n)
)
| Tarrow (t1, t2) -> Tarrow ( apply s t1, apply s t2 )
| TconList (t) -> TconList (apply s t)
| TconTuple (t1, t2) -> TconTuple (apply s t1, apply s t2)
| Tforall (stlst, t) -> Tforall (stlst,
apply (List.fold_right SubstMap.remove stlst s) t)
| Tmaybe(t) -> Tmaybe(apply s t)
| t -> t
let collision key e1 e2 = Some e1
let nullSubst : ty SubstMap.t = SubstMap.empty
let composeSubst (s1 : ty SubstMap.t) (s2 : ty SubstMap.t) =
SubstMap.union collision (SubstMap.map (apply s1) s2)
(SubstMap.map (apply s2) s1)
(* removes element from typing environment *)
let remove (env : ty SubstMap.t) var =
SubstMap.remove var env
let getElem = function
| (key, a) -> a
let getElems mp = List.map getElem (TyEnvMap.bindings mp)
let printSubst s = print_string "{" ;
SubstMap.iter
(fun key -> fun ty ->
print_string (key ^ ": " ^ (ty_to_str ty)^", ")) s;
print_endline "}"
(* get elements of the map (not the keys),
and map ftv over them then make a new set with those ftvs*)
let ftvenv env =
(List.fold_right ( SS.union ) (List.map ftv (getElems env)) SS.empty )
let applyenv subst env = (TyEnvMap.map (apply subst) env)
let generalize env t =
let vars = SS.elements (SS.diff (ftv t) (ftvenv env)) in Tforall(vars, t)
let newTyVar prefix =
let str = get_fresh prefix in Tvar(str)
let rec zip lst1 lst2 = match lst1, lst2 with
| [], _ -> []
| _, [] -> []
| (x :: xs), (y :: ys) -> (x, y) :: (zip xs ys)
let rec unzip = function
| (a,b)::xs -> let rest = unzip xs in
let resta = fst rest in
let restb = snd rest in
(a::resta,b::restb)
| [] -> ([],[])
let rec map_from_list = function
| [] -> SubstMap.empty
| (t1, t2) :: tl -> SubstMap.add t1 t2 (map_from_list tl)
let instantiate = function
| Tforall(vars, t) ->
let nvars = List.map (fun var -> newTyVar(var)) vars in
let s = map_from_list (zip vars nvars) in
apply s t
| t -> t
let varBind u t = match u, t with
| u, Tvar(x) -> if (String.equal u x)
then nullSubst
else SubstMap.add u (Tvar(x)) SubstMap.empty
| u, t when SS.mem u (ftv t) -> raise
(Failure ("Cannot bind "^u^" to "^(ty_to_str t)) )
| _,_ -> SubstMap.add u t SubstMap.empty
let rec mgu ty1 ty2 =
match ty1, ty2 with
| Tarrow(l, r), Tarrow(l', r') ->
let s1 = mgu l l' in
let s2 = mgu (apply s1 r) (apply s1 r') in
composeSubst s1 s2
| Tvar(u), t -> varBind u t
| t, Tvar(u) -> varBind u t
| Int, Int -> nullSubst
| Bool, Bool -> nullSubst
| Float, Float -> nullSubst
| Char, Char -> nullSubst
| TconList(t), TconList(t') -> mgu t t'
| Tmaybe(t), Tmaybe(t') -> mgu t t'
| TconTuple(l, r), TconTuple(l', r') ->
let s1 = mgu l l' in
let s2 = mgu (apply s1 r) (apply s1 r') in
composeSubst s1 s2
| t1, t2 -> raise(Failure ((ty_to_str ty1) ^ " types do not unify " ^
(ty_to_str ty2)))
(* Collects tvars in a list; doesn't work for tforalls because we
* shouldn't need to call it on a tforall *)
let collect_tvar =
let rec collect genlist = function
| (Tvar var) -> var::genlist
| (TconList ty) -> (collect genlist ty)
| (TconTuple (t1,t2)) -> let l1 = collect genlist t1 in
let l2 = collect l1 t2 in l2
| (Tarrow (t1,t2)) -> let l1 = collect genlist t1 in
let l2 = collect l1 t2 in l2
| (Tmaybe ty) -> (collect genlist ty)
| (Tforall _) -> raise (Failure "can't generalize tforalls")
| _ -> genlist
in collect []
(* Returns tforall if there are tvars, normal type if not *)
let simple_generalize ty =
let gen_list = collect_tvar ty in
if (List.length gen_list) = 0 then ty else (Tforall (gen_list,ty))
Takes an AST and returns a TAST ( typed AST )
let rec ti env expr =
let rec ti_vbinds env = function
| ((ListVBind(v,e))::xs) ->
let (s,ix,ty) as ixpr =
(match e with
| (ListComp _) as l -> ti env l
| (ListRange _) as l -> ti env l
| (ListLit _) as l -> ti env l
| (Var _) as l -> ti env l
| t -> raise (Failure(
"list comprehension variable "^v^" is not defined over list "
^(ast_to_str t))))
in (match ty with
| TconList _ -> (IListVBind(v,ixpr))::(ti_vbinds (applyenv s env) xs)
| Tvar t -> (IListVBind(v,ixpr))::(ti_vbinds (applyenv s env) xs)
| _ -> raise (Failure(
"list comprehension variable "^v^" is not defined over list")))
| [] -> []
| _ -> raise (Failure "Unexpected filter")
in
let rec ti_filters env = function
| ((Filter e)::xs) ->
let (s,ix,ty) as ixpr = ti env e in
(IFilter ixpr)::(ti_filters (applyenv s env) xs)
| [] -> []
| _ -> raise (Failure "Unexpected list vbind")
in
let collect_vbinds_filters mixed_list =
let rec collect l tuple =
match tuple with (vbinds,filters) ->
(match l with
| (ListVBind(t)::xs) -> collect xs ((ListVBind(t))::vbinds,filters)
| (Filter(t) ::xs) -> collect xs (vbinds,(Filter(t))::filters)
| [] -> (List.rev vbinds, List.rev filters))
in collect mixed_list ([],[])
in
let rec tys_from_vbinds = function
| (IListVBind(_,(_,_,(TconList ty))))::xs ->
(ty,nullSubst)::(tys_from_vbinds xs)
| (IListVBind(_,(_,_,(Tvar ty))))::xs ->
let oop = newTyVar "oop"
in (oop, mgu (TconList oop) (Tvar ty))::(tys_from_vbinds xs)
| [] -> []
| _ -> raise
(Failure "list comprehension variable is not defined over list")
in
let rec tys_from_filters = function
| (IFilter(_,_,ty))::xs -> ty::(tys_from_filters xs)
| [] -> []
| _ -> raise (Failure "error in tys_from_filters")
in
let rec substs_from_vbinds = function
| (IListVBind(_,(s,_,_)))::xs -> composeSubst s (substs_from_vbinds xs)
| [] -> nullSubst
| _ -> raise
(Failure "list comprehension variable is not defined over list")
in
let rec substs_from_filters = function
| (IFilter(s,_,_))::xs -> composeSubst s (substs_from_filters xs)
| [] -> nullSubst
| _ -> raise (Failure "error in tys_from_filters")
in
let rec merge_tys_filter tlist filter_ty = match tlist with
| (ty::xs) -> (match filter_ty with
| Tarrow(arg,ret) ->
let s1 = mgu arg ty in
let s2 = merge_tys_filter xs ret in
composeSubst s1 s2
| _ -> raise (Failure "improper filter type in list comprehension"))
| [] -> (mgu filter_ty Bool)
in
let rec merge_tys_expr tlist expr_ty = match tlist with
|(ty::xs) -> (match expr_ty with
| Tarrow(arg,ret) ->
let s1 = mgu arg ty in
let (s2,ret_ty) = merge_tys_expr xs ret in
let s3 = composeSubst s1 s2 in
(s3, apply s3 ret_ty)
| _ -> raise (Failure "improper variable bindings in list comp"))
| [] -> (nullSubst,expr_ty)
in
let type_listcomp env comp = match comp with
(ListComp(e,clauses)) ->
let (s,ix,ty) as ixpr = ti env e in
let (vbinds,filters) = collect_vbinds_filters clauses in
let (ivbinds,ifilters) =(ti_vbinds env vbinds,ti_filters env filters) in
let (vbind_tys,vbind_substs) = unzip (tys_from_vbinds ivbinds) in
let polyvbind_substs = List.fold_left
(fun s1 -> fun s2 -> composeSubst s1 s2)
(List.hd vbind_substs) vbind_substs in
let vsubsts = composeSubst polyvbind_substs
(substs_from_vbinds ivbinds) in
let fsubsts = substs_from_filters ifilters in
let filter_tys = tys_from_filters ifilters in
let filtsubst = composeSubst fsubsts (List.fold_left
(fun su -> fun t -> composeSubst (merge_tys_filter vbind_tys t) su)
nullSubst filter_tys) in
let (esubst,ety) = merge_tys_expr vbind_tys ty in
let allsubst = composeSubst vsubsts (composeSubst filtsubst esubst) in
print_string " COMP allsubst : " ; allsubst ;
let ret_ty = apply allsubst ety in
(* should we apply substs to the inferred vbinds and filters? prob ye *)
(allsubst,IListComp(allsubst,ixpr,(ivbinds@ifilters)), TconList(ret_ty))
| _ -> raise (Failure ("List comp expected"))
in
(****************************EXPRS******************************)
match expr with
| IntLit i -> (nullSubst, IIntLit i, Int)
| FloatLit f -> (nullSubst, IFloatLit f,Float)
| CharLit c -> (nullSubst, ICharLit c,Char)
| BoolLit b -> (nullSubst, IBoolLit b,Bool)
| Tuple (e1,e2) ->
let (s1,tex1,ty1) as ix1 = ti env e1 in
let (s2,tex2,ty2) as ix2 = ti (applyenv s1 env) e2 in
let s3 = composeSubst s1 s2 in
(s3
, ITuple(ix1,ix2)
, TconTuple(apply s3 ty1, apply s3 ty2))
| ListLit [] -> (nullSubst, IListLit [], TconList(newTyVar "a"))
| ListLit l -> let iexpr_list = List.map (ti env) l in
(match iexpr_list with
(* collect all substs; apply substs on elements and final type *)
| ix_list ->
let fullSubst =
fold_left (fun s1 (s2,_,_) -> composeSubst s1 s2) env ix_list in
let merged_ix_list = List.map
(fun (env,e,t) -> (env,e, apply fullSubst t)) ix_list in
let (_,_,ty) = List.hd merged_ix_list in
(fullSubst, IListLit(merged_ix_list), TconList ty))
| ListRange(e1, e2) ->
let (subst1, tex1, ty1) = ti env e1 in
let (subst2,tex2, ty2) = ti (applyenv subst1 env) e2 in
let subst3 = mgu (apply subst2 ty1) ty2 in
let subst4 = mgu (apply subst3 ty2) Int in
let fullsubst = composeSubst subst1 (composeSubst subst2
(composeSubst subst3 subst4)) in
(fullsubst
, IListRange(subst4,
(subst1,tex1,apply fullsubst ty1),
(subst2,tex2,apply fullsubst ty2))
, TconList Int)
| None -> let polyty = newTyVar "a" in
(nullSubst, INone, Tmaybe polyty)
| Just e -> let (s,ix,t) as ixpr = ti env e in
(s, IJust ixpr, Tmaybe t)
| ListComp(_) as comp -> type_listcomp env comp
| Var n -> let sigma = TyEnvMap.find_opt n env in
(match sigma with
| None -> raise(Failure("unbound variable " ^ n))
| Some si -> let t = instantiate si in
(nullSubst, IVar n, t)
)
| Let(Assign(x, e1), e2) ->
let (s1,tex1,t1) as ix1 = ti env e1 in
let t' = generalize (applyenv s1 env) t1 in
let env'' = (TyEnvMap.add x t' (applyenv s1 env)) in
let (s2, tex2, t2) as ix2 = ti (applyenv s1 env'') e2 in
(composeSubst s1 s2
, ILet(composeSubst s1 s2, IAssign(x, ix1), ix2)
, t2)
| Lambda( n, e ) ->
let tv = newTyVar n in
let env' = remove env n in
let env'' = SubstMap.union collision env'
(SubstMap.singleton n (Tforall([], tv)) ) in
let (s1, tex1, t1) as ix1 = ti env'' e in
(s1, ILambda (s1, n, ix1), Tarrow( (apply s1 tv), t1 ))
| App(e1,e2) ->
let tv = newTyVar "app" in
let (s1, tx1, t1) as ix1 = ti env e1 in
let (s2, tx2, t2) as ix2 = ti (applyenv s1 env) e2 in
let s3 = mgu (apply s2 t1) (Tarrow( t2, tv)) in
((composeSubst (composeSubst s1 s2) s3)
, IApp(s3,ix1,ix2)
, apply s3 tv)
| Ite(e1,e2,e3) ->
let (s1,tx1,t1) as ix1 = ti env e1 in
first expr must be boolean
let boolSubst = composeSubst (mgu Bool t1) s1 in
let (s2,tx2,t2) as ix2 = ti (applyenv boolSubst env) e2 in
let s' = composeSubst boolSubst s2 in
let (s3,tx2,t3) as ix3 = ti (applyenv s' env) e3 in
let s'' = mgu t2 t3 in
let fullSubst = composeSubst s' s'' in
(fullSubst
, IIte(fullSubst, ix1,ix2,ix3)
, apply fullSubst t2)
| Add -> (nullSubst, IAdd, Tarrow(Int, Tarrow(Int,Int)))
| Sub -> (nullSubst, ISub, Tarrow(Int, Tarrow(Int,Int)))
| Mult -> (nullSubst, IMult, Tarrow(Int, Tarrow(Int,Int)))
| Div -> (nullSubst, IDiv, Tarrow(Int, Tarrow(Int,Int)))
| Mod -> (nullSubst, IMod, Tarrow(Int,Tarrow(Int,Int)))
| Pow -> (nullSubst, IPow, Tarrow(Int,Tarrow(Int,Int)))
| AddF -> (nullSubst, IAddF, Tarrow(Float, Tarrow(Float,Float)))
| SubF -> (nullSubst, ISubF, Tarrow(Float, Tarrow(Float,Float)))
| MultF -> (nullSubst, IMultF, Tarrow(Float, Tarrow(Float,Float)))
| DivF -> (nullSubst, IDivF, Tarrow(Float,Tarrow(Float,Float)))
| PowF -> (nullSubst, IPowF, Tarrow(Float,Tarrow(Float,Float)))
| Neg -> (nullSubst, INeg, Tarrow(Int, Int))
| NegF -> (nullSubst, INegF, Tarrow(Float, Float))
| Eq -> (nullSubst, IEq, Tarrow(Int,Tarrow(Int,Bool)))
| EqF -> (nullSubst, IEqF, Tarrow(Float,Tarrow(Float,Bool)))
| Neq -> (nullSubst, INeq, Tarrow(Int,Tarrow(Int,Bool)))
| NeqF -> (nullSubst, INeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Geq -> (nullSubst, IGeq, Tarrow(Int,Tarrow(Int,Bool)))
| GeqF -> (nullSubst, IGeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Leq -> (nullSubst, ILeq, Tarrow(Int,Tarrow(Int,Bool)))
| LeqF -> (nullSubst, ILeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Less -> (nullSubst, ILess, Tarrow(Int,Tarrow(Int,Bool)))
| LessF -> (nullSubst, ILessF, Tarrow(Float,Tarrow(Float,Bool)))
| Greater -> (nullSubst, IGreater, Tarrow(Int,Tarrow(Int,Bool)))
| GreaterF -> (nullSubst, IGreaterF, Tarrow(Float,Tarrow(Float,Bool)))
| And -> (nullSubst, IAnd, Tarrow(Bool,Tarrow(Bool,Bool)))
| Or -> (nullSubst, IOr, Tarrow(Bool,Tarrow(Bool,Bool)))
| Not -> (nullSubst, INot, Tarrow(Bool,Bool))
| Int_to_float -> (nullSubst, IInt_to_float, Tarrow(Int,Float))
| Cons -> let polyty = newTyVar "a" in
(nullSubst, ICons, Tarrow(polyty,
Tarrow (TconList polyty, TconList polyty)))
| Cat -> let polyty = newTyVar "a" in
(nullSubst, ICat, Tarrow(TconList polyty,
Tarrow (TconList polyty, TconList polyty)))
| Len -> let polyty = newTyVar "a" in
(nullSubst, ILen, Tarrow(TconList polyty, Int))
| Head -> let polyty = newTyVar "a" in
(nullSubst, IHead,
(Tarrow(TconList polyty, polyty)))
| Tail -> let polyty = newTyVar "a" in
(nullSubst, ITail,
Tarrow(TconList polyty, TconList polyty))
| First -> let polyty1 = newTyVar "a" in
let polyty2 = newTyVar "b" in
(nullSubst, IFirst,
(Tarrow(TconTuple(polyty1,polyty2),polyty1)))
| Sec -> let polyty1 = newTyVar "a" in
let polyty2 = newTyVar "b" in
(nullSubst, ISec,
(Tarrow(TconTuple(polyty1,polyty2),polyty2)))
| Is_none -> let polyty = newTyVar "a" in
(nullSubst, IIs_none,
(Tarrow(Tmaybe polyty, Bool)))
| From_just -> let polyty = newTyVar "a" in
(nullSubst, IFrom_just,
(Tarrow(Tmaybe polyty, polyty)))
(* TODO: rest of add things *)
| _ -> raise (Failure "not yet implemented in type inference")
let rec type_clauses env = function
( * make sure that var is the same type as blist
(* make sure that var is the same type as blist *)
| ListVBind (var, blist) -> let (subst, tex, ty) = ti env blist
| Filter e -> let (subst, tex, ty) = ti env e in
let subst' = mgu (apply subst ty) Bool in
(subst', IFilter(subst', tex, apply subst' ty), apply subst' ty)*)
let rec typeUpdateEnv env = function
| ((a,Vdef(name,expr))::xs) ->
let (substs, ix, ty) = ti env expr in
let newTy = generalize env ty in
let oldTy =
(match TyEnvMap.find_opt name env with
| None -> raise(Failure("unbound variable " ^ name))
| Some si -> instantiate si) in
let newSubst = mgu newTy oldTy in
let newPair = (a, InferredVdef(name,
(composeSubst newSubst substs, ix, apply newSubst ty))) in
(newPair::(typeUpdateEnv (applyenv newSubst env) xs))
| [] -> []
| ((_,Annot(_))::xs) -> raise (Failure "cannot tiVdef on annotation")
let rec unzip_thruple l =
let f (l1,l2,l3) (x,y,z) = (x::l1,y::l2,z::l3) in
List.fold_left f ([],[],[]) (List.rev l)
let type_paired_program annotvdef_list =
let vdef_names = List.fold_left
(fun l -> fun pair -> (
match pair with ((Annot(n,_)),_) -> n::l
| _ -> raise (Failure "vdef where annot should be in pair")) )
[] annotvdef_list in
let moduleEnv = List.fold_left
(fun env -> fun name ->
let var = newTyVar name in
TyEnvMap.add name var env)
TyEnvMap.empty vdef_names in
let annotIVdefs = typeUpdateEnv moduleEnv annotvdef_list in
let substList = List.fold_left
(fun l -> fun (_, InferredVdef(_,(subst,_,_))) -> subst::l)
[] annotIVdefs in
let allSubsts = List.fold_left
(fun s1 -> fun s2 -> composeSubst s1 s2)
(List.hd substList) substList in
let annotIVdefs' = List.map
(fun x -> match x with
(Annot(na,tya), InferredVdef(n,(s,ix,ty))) ->
let finalUnion = mgu tya ty in
let fullUnion = composeSubst finalUnion allSubsts in
(Annot(na,tya),
InferredVdef(n,(s,ix, apply fullUnion ty)))
|_ -> raise (Failure("no"));
) annotIVdefs in
(allSubsts,annotIVdefs')
| null | https://raw.githubusercontent.com/al3623/rippl/a7e5c24f67935b3513324148279791042856a1fa/src/passes/type_inference.ml | ocaml | mappings from term variables to tforall
returns a set of free type variables
removes element from typing environment
get elements of the map (not the keys),
and map ftv over them then make a new set with those ftvs
Collects tvars in a list; doesn't work for tforalls because we
* shouldn't need to call it on a tforall
Returns tforall if there are tvars, normal type if not
should we apply substs to the inferred vbinds and filters? prob ye
***************************EXPRS*****************************
collect all substs; apply substs on elements and final type
TODO: rest of add things
make sure that var is the same type as blist | open Ast
open Tast
open Get_fresh_var
open Iast
open List
open Pretty_type_print
module SS = Set.Make(String);;
module SMap = Map.Make(String);;
module SubstMap = Map.Make(String);;
module TyEnvMap = Map.Make(String);;
let printEnv env =
print_string "[";
TyEnvMap.iter (fun key -> fun ty ->
print_string (key ^ " :: " ^ (ty_to_str ty)^", ")) env;
print_endline "]"
let rec ftv = function
| Tvar(n) -> SS.add n SS.empty
| Int -> SS.empty
| Bool -> SS.empty
| Float -> SS.empty
| Char -> SS.empty
| Tarrow (t1, t2) -> SS.union (ftv t1) (ftv t2)
| TconList (t) -> ftv t
| TconTuple (t1, t2) -> SS.union (ftv t1) (ftv t2)
| Tforall (stlst, t) -> SS.diff (ftv t) (SS.of_list stlst)
| Tmaybe (t) -> ftv t
let rec apply s = function
| Tvar(n) ->
(match SubstMap.find_opt n s with
| Some t -> apply s t
| None -> Tvar(n)
)
| Tarrow (t1, t2) -> Tarrow ( apply s t1, apply s t2 )
| TconList (t) -> TconList (apply s t)
| TconTuple (t1, t2) -> TconTuple (apply s t1, apply s t2)
| Tforall (stlst, t) -> Tforall (stlst,
apply (List.fold_right SubstMap.remove stlst s) t)
| Tmaybe(t) -> Tmaybe(apply s t)
| t -> t
let collision key e1 e2 = Some e1
let nullSubst : ty SubstMap.t = SubstMap.empty
let composeSubst (s1 : ty SubstMap.t) (s2 : ty SubstMap.t) =
SubstMap.union collision (SubstMap.map (apply s1) s2)
(SubstMap.map (apply s2) s1)
let remove (env : ty SubstMap.t) var =
SubstMap.remove var env
let getElem = function
| (key, a) -> a
let getElems mp = List.map getElem (TyEnvMap.bindings mp)
let printSubst s = print_string "{" ;
SubstMap.iter
(fun key -> fun ty ->
print_string (key ^ ": " ^ (ty_to_str ty)^", ")) s;
print_endline "}"
let ftvenv env =
(List.fold_right ( SS.union ) (List.map ftv (getElems env)) SS.empty )
let applyenv subst env = (TyEnvMap.map (apply subst) env)
let generalize env t =
let vars = SS.elements (SS.diff (ftv t) (ftvenv env)) in Tforall(vars, t)
let newTyVar prefix =
let str = get_fresh prefix in Tvar(str)
let rec zip lst1 lst2 = match lst1, lst2 with
| [], _ -> []
| _, [] -> []
| (x :: xs), (y :: ys) -> (x, y) :: (zip xs ys)
let rec unzip = function
| (a,b)::xs -> let rest = unzip xs in
let resta = fst rest in
let restb = snd rest in
(a::resta,b::restb)
| [] -> ([],[])
let rec map_from_list = function
| [] -> SubstMap.empty
| (t1, t2) :: tl -> SubstMap.add t1 t2 (map_from_list tl)
let instantiate = function
| Tforall(vars, t) ->
let nvars = List.map (fun var -> newTyVar(var)) vars in
let s = map_from_list (zip vars nvars) in
apply s t
| t -> t
let varBind u t = match u, t with
| u, Tvar(x) -> if (String.equal u x)
then nullSubst
else SubstMap.add u (Tvar(x)) SubstMap.empty
| u, t when SS.mem u (ftv t) -> raise
(Failure ("Cannot bind "^u^" to "^(ty_to_str t)) )
| _,_ -> SubstMap.add u t SubstMap.empty
let rec mgu ty1 ty2 =
match ty1, ty2 with
| Tarrow(l, r), Tarrow(l', r') ->
let s1 = mgu l l' in
let s2 = mgu (apply s1 r) (apply s1 r') in
composeSubst s1 s2
| Tvar(u), t -> varBind u t
| t, Tvar(u) -> varBind u t
| Int, Int -> nullSubst
| Bool, Bool -> nullSubst
| Float, Float -> nullSubst
| Char, Char -> nullSubst
| TconList(t), TconList(t') -> mgu t t'
| Tmaybe(t), Tmaybe(t') -> mgu t t'
| TconTuple(l, r), TconTuple(l', r') ->
let s1 = mgu l l' in
let s2 = mgu (apply s1 r) (apply s1 r') in
composeSubst s1 s2
| t1, t2 -> raise(Failure ((ty_to_str ty1) ^ " types do not unify " ^
(ty_to_str ty2)))
let collect_tvar =
let rec collect genlist = function
| (Tvar var) -> var::genlist
| (TconList ty) -> (collect genlist ty)
| (TconTuple (t1,t2)) -> let l1 = collect genlist t1 in
let l2 = collect l1 t2 in l2
| (Tarrow (t1,t2)) -> let l1 = collect genlist t1 in
let l2 = collect l1 t2 in l2
| (Tmaybe ty) -> (collect genlist ty)
| (Tforall _) -> raise (Failure "can't generalize tforalls")
| _ -> genlist
in collect []
let simple_generalize ty =
let gen_list = collect_tvar ty in
if (List.length gen_list) = 0 then ty else (Tforall (gen_list,ty))
Takes an AST and returns a TAST ( typed AST )
let rec ti env expr =
let rec ti_vbinds env = function
| ((ListVBind(v,e))::xs) ->
let (s,ix,ty) as ixpr =
(match e with
| (ListComp _) as l -> ti env l
| (ListRange _) as l -> ti env l
| (ListLit _) as l -> ti env l
| (Var _) as l -> ti env l
| t -> raise (Failure(
"list comprehension variable "^v^" is not defined over list "
^(ast_to_str t))))
in (match ty with
| TconList _ -> (IListVBind(v,ixpr))::(ti_vbinds (applyenv s env) xs)
| Tvar t -> (IListVBind(v,ixpr))::(ti_vbinds (applyenv s env) xs)
| _ -> raise (Failure(
"list comprehension variable "^v^" is not defined over list")))
| [] -> []
| _ -> raise (Failure "Unexpected filter")
in
let rec ti_filters env = function
| ((Filter e)::xs) ->
let (s,ix,ty) as ixpr = ti env e in
(IFilter ixpr)::(ti_filters (applyenv s env) xs)
| [] -> []
| _ -> raise (Failure "Unexpected list vbind")
in
let collect_vbinds_filters mixed_list =
let rec collect l tuple =
match tuple with (vbinds,filters) ->
(match l with
| (ListVBind(t)::xs) -> collect xs ((ListVBind(t))::vbinds,filters)
| (Filter(t) ::xs) -> collect xs (vbinds,(Filter(t))::filters)
| [] -> (List.rev vbinds, List.rev filters))
in collect mixed_list ([],[])
in
let rec tys_from_vbinds = function
| (IListVBind(_,(_,_,(TconList ty))))::xs ->
(ty,nullSubst)::(tys_from_vbinds xs)
| (IListVBind(_,(_,_,(Tvar ty))))::xs ->
let oop = newTyVar "oop"
in (oop, mgu (TconList oop) (Tvar ty))::(tys_from_vbinds xs)
| [] -> []
| _ -> raise
(Failure "list comprehension variable is not defined over list")
in
let rec tys_from_filters = function
| (IFilter(_,_,ty))::xs -> ty::(tys_from_filters xs)
| [] -> []
| _ -> raise (Failure "error in tys_from_filters")
in
let rec substs_from_vbinds = function
| (IListVBind(_,(s,_,_)))::xs -> composeSubst s (substs_from_vbinds xs)
| [] -> nullSubst
| _ -> raise
(Failure "list comprehension variable is not defined over list")
in
let rec substs_from_filters = function
| (IFilter(s,_,_))::xs -> composeSubst s (substs_from_filters xs)
| [] -> nullSubst
| _ -> raise (Failure "error in tys_from_filters")
in
let rec merge_tys_filter tlist filter_ty = match tlist with
| (ty::xs) -> (match filter_ty with
| Tarrow(arg,ret) ->
let s1 = mgu arg ty in
let s2 = merge_tys_filter xs ret in
composeSubst s1 s2
| _ -> raise (Failure "improper filter type in list comprehension"))
| [] -> (mgu filter_ty Bool)
in
let rec merge_tys_expr tlist expr_ty = match tlist with
|(ty::xs) -> (match expr_ty with
| Tarrow(arg,ret) ->
let s1 = mgu arg ty in
let (s2,ret_ty) = merge_tys_expr xs ret in
let s3 = composeSubst s1 s2 in
(s3, apply s3 ret_ty)
| _ -> raise (Failure "improper variable bindings in list comp"))
| [] -> (nullSubst,expr_ty)
in
let type_listcomp env comp = match comp with
(ListComp(e,clauses)) ->
let (s,ix,ty) as ixpr = ti env e in
let (vbinds,filters) = collect_vbinds_filters clauses in
let (ivbinds,ifilters) =(ti_vbinds env vbinds,ti_filters env filters) in
let (vbind_tys,vbind_substs) = unzip (tys_from_vbinds ivbinds) in
let polyvbind_substs = List.fold_left
(fun s1 -> fun s2 -> composeSubst s1 s2)
(List.hd vbind_substs) vbind_substs in
let vsubsts = composeSubst polyvbind_substs
(substs_from_vbinds ivbinds) in
let fsubsts = substs_from_filters ifilters in
let filter_tys = tys_from_filters ifilters in
let filtsubst = composeSubst fsubsts (List.fold_left
(fun su -> fun t -> composeSubst (merge_tys_filter vbind_tys t) su)
nullSubst filter_tys) in
let (esubst,ety) = merge_tys_expr vbind_tys ty in
let allsubst = composeSubst vsubsts (composeSubst filtsubst esubst) in
print_string " COMP allsubst : " ; allsubst ;
let ret_ty = apply allsubst ety in
(allsubst,IListComp(allsubst,ixpr,(ivbinds@ifilters)), TconList(ret_ty))
| _ -> raise (Failure ("List comp expected"))
in
match expr with
| IntLit i -> (nullSubst, IIntLit i, Int)
| FloatLit f -> (nullSubst, IFloatLit f,Float)
| CharLit c -> (nullSubst, ICharLit c,Char)
| BoolLit b -> (nullSubst, IBoolLit b,Bool)
| Tuple (e1,e2) ->
let (s1,tex1,ty1) as ix1 = ti env e1 in
let (s2,tex2,ty2) as ix2 = ti (applyenv s1 env) e2 in
let s3 = composeSubst s1 s2 in
(s3
, ITuple(ix1,ix2)
, TconTuple(apply s3 ty1, apply s3 ty2))
| ListLit [] -> (nullSubst, IListLit [], TconList(newTyVar "a"))
| ListLit l -> let iexpr_list = List.map (ti env) l in
(match iexpr_list with
| ix_list ->
let fullSubst =
fold_left (fun s1 (s2,_,_) -> composeSubst s1 s2) env ix_list in
let merged_ix_list = List.map
(fun (env,e,t) -> (env,e, apply fullSubst t)) ix_list in
let (_,_,ty) = List.hd merged_ix_list in
(fullSubst, IListLit(merged_ix_list), TconList ty))
| ListRange(e1, e2) ->
let (subst1, tex1, ty1) = ti env e1 in
let (subst2,tex2, ty2) = ti (applyenv subst1 env) e2 in
let subst3 = mgu (apply subst2 ty1) ty2 in
let subst4 = mgu (apply subst3 ty2) Int in
let fullsubst = composeSubst subst1 (composeSubst subst2
(composeSubst subst3 subst4)) in
(fullsubst
, IListRange(subst4,
(subst1,tex1,apply fullsubst ty1),
(subst2,tex2,apply fullsubst ty2))
, TconList Int)
| None -> let polyty = newTyVar "a" in
(nullSubst, INone, Tmaybe polyty)
| Just e -> let (s,ix,t) as ixpr = ti env e in
(s, IJust ixpr, Tmaybe t)
| ListComp(_) as comp -> type_listcomp env comp
| Var n -> let sigma = TyEnvMap.find_opt n env in
(match sigma with
| None -> raise(Failure("unbound variable " ^ n))
| Some si -> let t = instantiate si in
(nullSubst, IVar n, t)
)
| Let(Assign(x, e1), e2) ->
let (s1,tex1,t1) as ix1 = ti env e1 in
let t' = generalize (applyenv s1 env) t1 in
let env'' = (TyEnvMap.add x t' (applyenv s1 env)) in
let (s2, tex2, t2) as ix2 = ti (applyenv s1 env'') e2 in
(composeSubst s1 s2
, ILet(composeSubst s1 s2, IAssign(x, ix1), ix2)
, t2)
| Lambda( n, e ) ->
let tv = newTyVar n in
let env' = remove env n in
let env'' = SubstMap.union collision env'
(SubstMap.singleton n (Tforall([], tv)) ) in
let (s1, tex1, t1) as ix1 = ti env'' e in
(s1, ILambda (s1, n, ix1), Tarrow( (apply s1 tv), t1 ))
| App(e1,e2) ->
let tv = newTyVar "app" in
let (s1, tx1, t1) as ix1 = ti env e1 in
let (s2, tx2, t2) as ix2 = ti (applyenv s1 env) e2 in
let s3 = mgu (apply s2 t1) (Tarrow( t2, tv)) in
((composeSubst (composeSubst s1 s2) s3)
, IApp(s3,ix1,ix2)
, apply s3 tv)
| Ite(e1,e2,e3) ->
let (s1,tx1,t1) as ix1 = ti env e1 in
first expr must be boolean
let boolSubst = composeSubst (mgu Bool t1) s1 in
let (s2,tx2,t2) as ix2 = ti (applyenv boolSubst env) e2 in
let s' = composeSubst boolSubst s2 in
let (s3,tx2,t3) as ix3 = ti (applyenv s' env) e3 in
let s'' = mgu t2 t3 in
let fullSubst = composeSubst s' s'' in
(fullSubst
, IIte(fullSubst, ix1,ix2,ix3)
, apply fullSubst t2)
| Add -> (nullSubst, IAdd, Tarrow(Int, Tarrow(Int,Int)))
| Sub -> (nullSubst, ISub, Tarrow(Int, Tarrow(Int,Int)))
| Mult -> (nullSubst, IMult, Tarrow(Int, Tarrow(Int,Int)))
| Div -> (nullSubst, IDiv, Tarrow(Int, Tarrow(Int,Int)))
| Mod -> (nullSubst, IMod, Tarrow(Int,Tarrow(Int,Int)))
| Pow -> (nullSubst, IPow, Tarrow(Int,Tarrow(Int,Int)))
| AddF -> (nullSubst, IAddF, Tarrow(Float, Tarrow(Float,Float)))
| SubF -> (nullSubst, ISubF, Tarrow(Float, Tarrow(Float,Float)))
| MultF -> (nullSubst, IMultF, Tarrow(Float, Tarrow(Float,Float)))
| DivF -> (nullSubst, IDivF, Tarrow(Float,Tarrow(Float,Float)))
| PowF -> (nullSubst, IPowF, Tarrow(Float,Tarrow(Float,Float)))
| Neg -> (nullSubst, INeg, Tarrow(Int, Int))
| NegF -> (nullSubst, INegF, Tarrow(Float, Float))
| Eq -> (nullSubst, IEq, Tarrow(Int,Tarrow(Int,Bool)))
| EqF -> (nullSubst, IEqF, Tarrow(Float,Tarrow(Float,Bool)))
| Neq -> (nullSubst, INeq, Tarrow(Int,Tarrow(Int,Bool)))
| NeqF -> (nullSubst, INeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Geq -> (nullSubst, IGeq, Tarrow(Int,Tarrow(Int,Bool)))
| GeqF -> (nullSubst, IGeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Leq -> (nullSubst, ILeq, Tarrow(Int,Tarrow(Int,Bool)))
| LeqF -> (nullSubst, ILeqF, Tarrow(Float,Tarrow(Float,Bool)))
| Less -> (nullSubst, ILess, Tarrow(Int,Tarrow(Int,Bool)))
| LessF -> (nullSubst, ILessF, Tarrow(Float,Tarrow(Float,Bool)))
| Greater -> (nullSubst, IGreater, Tarrow(Int,Tarrow(Int,Bool)))
| GreaterF -> (nullSubst, IGreaterF, Tarrow(Float,Tarrow(Float,Bool)))
| And -> (nullSubst, IAnd, Tarrow(Bool,Tarrow(Bool,Bool)))
| Or -> (nullSubst, IOr, Tarrow(Bool,Tarrow(Bool,Bool)))
| Not -> (nullSubst, INot, Tarrow(Bool,Bool))
| Int_to_float -> (nullSubst, IInt_to_float, Tarrow(Int,Float))
| Cons -> let polyty = newTyVar "a" in
(nullSubst, ICons, Tarrow(polyty,
Tarrow (TconList polyty, TconList polyty)))
| Cat -> let polyty = newTyVar "a" in
(nullSubst, ICat, Tarrow(TconList polyty,
Tarrow (TconList polyty, TconList polyty)))
| Len -> let polyty = newTyVar "a" in
(nullSubst, ILen, Tarrow(TconList polyty, Int))
| Head -> let polyty = newTyVar "a" in
(nullSubst, IHead,
(Tarrow(TconList polyty, polyty)))
| Tail -> let polyty = newTyVar "a" in
(nullSubst, ITail,
Tarrow(TconList polyty, TconList polyty))
| First -> let polyty1 = newTyVar "a" in
let polyty2 = newTyVar "b" in
(nullSubst, IFirst,
(Tarrow(TconTuple(polyty1,polyty2),polyty1)))
| Sec -> let polyty1 = newTyVar "a" in
let polyty2 = newTyVar "b" in
(nullSubst, ISec,
(Tarrow(TconTuple(polyty1,polyty2),polyty2)))
| Is_none -> let polyty = newTyVar "a" in
(nullSubst, IIs_none,
(Tarrow(Tmaybe polyty, Bool)))
| From_just -> let polyty = newTyVar "a" in
(nullSubst, IFrom_just,
(Tarrow(Tmaybe polyty, polyty)))
| _ -> raise (Failure "not yet implemented in type inference")
let rec type_clauses env = function
( * make sure that var is the same type as blist
| ListVBind (var, blist) -> let (subst, tex, ty) = ti env blist
| Filter e -> let (subst, tex, ty) = ti env e in
let subst' = mgu (apply subst ty) Bool in
(subst', IFilter(subst', tex, apply subst' ty), apply subst' ty)*)
let rec typeUpdateEnv env = function
| ((a,Vdef(name,expr))::xs) ->
let (substs, ix, ty) = ti env expr in
let newTy = generalize env ty in
let oldTy =
(match TyEnvMap.find_opt name env with
| None -> raise(Failure("unbound variable " ^ name))
| Some si -> instantiate si) in
let newSubst = mgu newTy oldTy in
let newPair = (a, InferredVdef(name,
(composeSubst newSubst substs, ix, apply newSubst ty))) in
(newPair::(typeUpdateEnv (applyenv newSubst env) xs))
| [] -> []
| ((_,Annot(_))::xs) -> raise (Failure "cannot tiVdef on annotation")
let rec unzip_thruple l =
let f (l1,l2,l3) (x,y,z) = (x::l1,y::l2,z::l3) in
List.fold_left f ([],[],[]) (List.rev l)
let type_paired_program annotvdef_list =
let vdef_names = List.fold_left
(fun l -> fun pair -> (
match pair with ((Annot(n,_)),_) -> n::l
| _ -> raise (Failure "vdef where annot should be in pair")) )
[] annotvdef_list in
let moduleEnv = List.fold_left
(fun env -> fun name ->
let var = newTyVar name in
TyEnvMap.add name var env)
TyEnvMap.empty vdef_names in
let annotIVdefs = typeUpdateEnv moduleEnv annotvdef_list in
let substList = List.fold_left
(fun l -> fun (_, InferredVdef(_,(subst,_,_))) -> subst::l)
[] annotIVdefs in
let allSubsts = List.fold_left
(fun s1 -> fun s2 -> composeSubst s1 s2)
(List.hd substList) substList in
let annotIVdefs' = List.map
(fun x -> match x with
(Annot(na,tya), InferredVdef(n,(s,ix,ty))) ->
let finalUnion = mgu tya ty in
let fullUnion = composeSubst finalUnion allSubsts in
(Annot(na,tya),
InferredVdef(n,(s,ix, apply fullUnion ty)))
|_ -> raise (Failure("no"));
) annotIVdefs in
(allSubsts,annotIVdefs')
|
138a89f4755519ddb0f25f56ee2ab4064302a9123cf7d8db1d4d34e3d6c71e4e | jeapostrophe/exp | gt5-events.rkt | #lang racket
(require net/url
racket/pretty
(planet neil/html-parsing/html-parsing)
(planet clements/sxml2))
(define (table-display l)
(define how-many-cols (length (first l)))
(define max-widths
(for/list ([col (in-range how-many-cols)])
(apply max (map (compose string-length (curryr list-ref col)) l))))
(for ([row (in-list l)])
(for ([col (in-list row)]
[i (in-naturals 1)]
[width (in-list max-widths)])
(printf "~a~a"
col
(if (= i how-many-cols)
""
(make-string (+ (- width (string-length col)) 4) #\space))))
(printf "\n")))
(module+ main
(define u "")
(define x (call/input-url (string->url u) get-pure-port html->xexp))
(define-values
(evts cat)
(for/fold ([evts empty]
[cat #f])
([r (in-list (rest ((sxpath "//tr") x)))])
(define rx (list '*TOP* r))
(match*
[((sxpath "/tr/@class/text()") rx)
((sxpath "/tr/td[1]/@class/text()") rx)]
[((list (regexp #rx"^cl ")) _)
(define lvl (first ((sxpath "/tr/td[1]/text()") rx)))
(define evt (first ((sxpath "/tr/td[2]/text()") rx)))
(values (cons (list lvl cat evt) evts)
cat)]
[((list) (list (or "bg_fondgris" "bspec")))
(values evts
cat)]
[((list) (list "e_ong"))
(values evts
(first ((sxpath "/tr/td[1]/text()") rx)))]
[(x y)
(error "failed on ~e" r)])))
(table-display
(sort evts <= #:key (compose string->number first))))
| null | https://raw.githubusercontent.com/jeapostrophe/exp/43615110fd0439d2ef940c42629fcdc054c370f9/gt5-events.rkt | racket | #lang racket
(require net/url
racket/pretty
(planet neil/html-parsing/html-parsing)
(planet clements/sxml2))
(define (table-display l)
(define how-many-cols (length (first l)))
(define max-widths
(for/list ([col (in-range how-many-cols)])
(apply max (map (compose string-length (curryr list-ref col)) l))))
(for ([row (in-list l)])
(for ([col (in-list row)]
[i (in-naturals 1)]
[width (in-list max-widths)])
(printf "~a~a"
col
(if (= i how-many-cols)
""
(make-string (+ (- width (string-length col)) 4) #\space))))
(printf "\n")))
(module+ main
(define u "")
(define x (call/input-url (string->url u) get-pure-port html->xexp))
(define-values
(evts cat)
(for/fold ([evts empty]
[cat #f])
([r (in-list (rest ((sxpath "//tr") x)))])
(define rx (list '*TOP* r))
(match*
[((sxpath "/tr/@class/text()") rx)
((sxpath "/tr/td[1]/@class/text()") rx)]
[((list (regexp #rx"^cl ")) _)
(define lvl (first ((sxpath "/tr/td[1]/text()") rx)))
(define evt (first ((sxpath "/tr/td[2]/text()") rx)))
(values (cons (list lvl cat evt) evts)
cat)]
[((list) (list (or "bg_fondgris" "bspec")))
(values evts
cat)]
[((list) (list "e_ong"))
(values evts
(first ((sxpath "/tr/td[1]/text()") rx)))]
[(x y)
(error "failed on ~e" r)])))
(table-display
(sort evts <= #:key (compose string->number first))))
| |
674e353df5454cebcc1e458856f4a256813d3d0393f089d834e4262b419df1a0 | qrilka/xlsx | Formatted.hs | -- | Higher level interface for creating styled worksheets
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE DeriveGeneric #
module Codec.Xlsx.Formatted
( FormattedCell(..)
, Formatted(..)
, Format(..)
, formatted
, formatWorkbook
, toFormattedCells
, CondFormatted(..)
, conditionallyFormatted
-- * Lenses
-- ** Format
, formatAlignment
, formatBorder
, formatFill
, formatFont
, formatNumberFormat
, formatProtection
, formatPivotButton
, formatQuotePrefix
* * FormattedCell
, formattedCell
, formattedFormat
, formattedColSpan
, formattedRowSpan
-- ** FormattedCondFmt
, condfmtCondition
, condfmtDxf
, condfmtPriority
, condfmtStopIfTrue
) where
#ifdef USE_MICROLENS
import Lens.Micro
import Lens.Micro.Mtl
import Lens.Micro.TH
import Lens.Micro.GHC ()
#else
import Control.Lens
#endif
import Control.Monad (forM, guard)
import Control.Monad.State hiding (forM_, mapM)
import Data.Default
import Data.Foldable (asum, forM_)
import Data.Function (on)
import Data.List (foldl', groupBy, sortBy, sortBy)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.Text (Text)
import Data.Traversable (mapM)
import Data.Tuple (swap)
import GHC.Generics (Generic)
import Prelude hiding (mapM)
import Safe (headNote, fromJustNote)
import Codec.Xlsx.Types
{-------------------------------------------------------------------------------
Internal: formatting state
-------------------------------------------------------------------------------}
data FormattingState = FormattingState {
_formattingBorders :: Map Border Int
, _formattingCellXfs :: Map CellXf Int
, _formattingFills :: Map Fill Int
, _formattingFonts :: Map Font Int
, _formattingNumFmts :: Map Text Int
, _formattingMerges :: [Range] -- ^ In reverse order
}
makeLenses ''FormattingState
stateFromStyleSheet :: StyleSheet -> FormattingState
stateFromStyleSheet StyleSheet{..} = FormattingState{
_formattingBorders = fromValueList _styleSheetBorders
, _formattingCellXfs = fromValueList _styleSheetCellXfs
, _formattingFills = fromValueList _styleSheetFills
, _formattingFonts = fromValueList _styleSheetFonts
, _formattingNumFmts = M.fromList . map swap $ M.toList _styleSheetNumFmts
, _formattingMerges = []
}
fromValueList :: Ord a => [a] -> Map a Int
fromValueList = M.fromList . (`zip` [0..])
toValueList :: Map a Int -> [a]
toValueList = map snd . sortBy (comparing fst) . map swap . M.toList
updateStyleSheetFromState :: StyleSheet -> FormattingState -> StyleSheet
updateStyleSheetFromState sSheet FormattingState{..} = sSheet
{ _styleSheetBorders = toValueList _formattingBorders
, _styleSheetCellXfs = toValueList _formattingCellXfs
, _styleSheetFills = toValueList _formattingFills
, _styleSheetFonts = toValueList _formattingFonts
, _styleSheetNumFmts = M.fromList . map swap $ M.toList _formattingNumFmts
}
getId :: Ord a => Lens' FormattingState (Map a Int) -> a -> State FormattingState Int
getId = getId' 0
getId' :: Ord a
=> Int
-> Lens' FormattingState (Map a Int)
-> a
-> State FormattingState Int
getId' k f v = do
aMap <- use f
case M.lookup v aMap of
Just anId -> return anId
Nothing -> do let anId = k + M.size aMap
f %= M.insert v anId
return anId
{-------------------------------------------------------------------------------
Unwrapped cell conditional formatting
-------------------------------------------------------------------------------}
data FormattedCondFmt = FormattedCondFmt
{ _condfmtCondition :: Condition
, _condfmtDxf :: Dxf
, _condfmtPriority :: Int
, _condfmtStopIfTrue :: Maybe Bool
} deriving (Eq, Show, Generic)
makeLenses ''FormattedCondFmt
{-------------------------------------------------------------------------------
Cell with formatting
-------------------------------------------------------------------------------}
-- | Formatting options used to format cells
--
TODOs :
--
* Add a number format ( ' _ cellXfApplyNumberFormat ' , ' _ cellXfNumFmtId ' )
-- * Add references to the named style sheets ('_cellXfId')
data Format = Format
{ _formatAlignment :: Maybe Alignment
, _formatBorder :: Maybe Border
, _formatFill :: Maybe Fill
, _formatFont :: Maybe Font
, _formatNumberFormat :: Maybe NumberFormat
, _formatProtection :: Maybe Protection
, _formatPivotButton :: Maybe Bool
, _formatQuotePrefix :: Maybe Bool
} deriving (Eq, Show, Generic)
makeLenses ''Format
| Cell with formatting . ' _ ' property of ' _ formattedCell ' is ignored
--
-- See 'formatted' for more details.
data FormattedCell = FormattedCell
{ _formattedCell :: Cell
, _formattedFormat :: Format
, _formattedColSpan :: Int
, _formattedRowSpan :: Int
} deriving (Eq, Show, Generic)
makeLenses ''FormattedCell
{-------------------------------------------------------------------------------
Default instances
-------------------------------------------------------------------------------}
instance Default FormattedCell where
def = FormattedCell
{ _formattedCell = def
, _formattedFormat = def
, _formattedColSpan = 1
, _formattedRowSpan = 1
}
instance Default Format where
def = Format
{ _formatAlignment = Nothing
, _formatBorder = Nothing
, _formatFill = Nothing
, _formatFont = Nothing
, _formatNumberFormat = Nothing
, _formatProtection = Nothing
, _formatPivotButton = Nothing
, _formatQuotePrefix = Nothing
}
instance Default FormattedCondFmt where
def = FormattedCondFmt ContainsBlanks def topCfPriority Nothing
{-------------------------------------------------------------------------------
Client-facing API
-------------------------------------------------------------------------------}
-- | Result of formatting
--
-- See 'formatted'
data Formatted = Formatted {
| The final ' CellMap ' ; see ' _ wsCells '
formattedCellMap :: CellMap
-- | The final stylesheet; see '_xlStyles' (and 'renderStyleSheet')
, formattedStyleSheet :: StyleSheet
-- | The final list of cell merges; see '_wsMerges'
, formattedMerges :: [Range]
} deriving (Eq, Show, Generic)
-- | Higher level API for creating formatted documents
--
Creating formatted Excel spreadsheets using the ' Cell ' datatype directly ,
even with the support for the ' StyleSheet ' datatype , is fairly painful .
-- This has a number of causes:
--
-- * The 'Cell' datatype wants an 'Int' for the style, which is supposed to
-- point into the '_styleSheetCellXfs' part of a stylesheet. However, this can
-- be difficult to work with, as it requires manual tracking of cell style
-- IDs, which in turns requires manual tracking of font IDs, border IDs, etc.
-- * Row-span and column-span properties are set on the worksheet as a whole
-- ('wsMerges') rather than on individual cells.
-- * Excel does not correctly deal with borders on cells that span multiple
-- columns or rows. Instead, these rows must be set on all the edge cells
-- in the block. Again, this means that this becomes a global property of
-- the spreadsheet rather than properties of individual cells.
--
This function deals with all these problems . Given a map of ' FormattedCell 's ,
which refer directly to ' 's , ' Border 's , etc . ( rather than font IDs ,
-- border IDs, etc.), and an initial stylesheet, it recovers all possible
sharing , constructs IDs , and then constructs the final ' CellMap ' , as well as
-- the final stylesheet and list of merges.
--
-- If you don't already have a 'StyleSheet' you want to use as starting point
-- then 'minimalStyleSheet' is a good choice.
formatted :: Map (RowIndex, ColumnIndex) FormattedCell -> StyleSheet -> Formatted
formatted cs styleSheet =
let initSt = stateFromStyleSheet styleSheet
(cs', finalSt) = runState (mapM (uncurry formatCell) (M.toList cs)) initSt
styleSheet' = updateStyleSheetFromState styleSheet finalSt
in Formatted {
formattedCellMap = M.fromList (concat cs')
, formattedStyleSheet = styleSheet'
, formattedMerges = reverse (finalSt ^. formattingMerges)
}
-- | Build an 'Xlsx', render provided cells as per the 'StyleSheet'.
formatWorkbook ::
[(Text, Map (RowIndex, ColumnIndex) FormattedCell)] -> StyleSheet -> Xlsx
formatWorkbook nfcss initStyle = extract go
where
initSt = stateFromStyleSheet initStyle
go = flip runState initSt $
forM nfcss $ \(name, fcs) -> do
cs' <- forM (M.toList fcs) $ \(rc, fc) -> formatCell rc fc
merges <- reverse . _formattingMerges <$> get
return ( name
, def & wsCells .~ M.fromList (concat cs')
& wsMerges .~ merges)
extract (sheets, st) =
def & xlSheets .~ sheets
& xlStyles .~ renderStyleSheet (updateStyleSheetFromState initStyle st)
-- | reverse to 'formatted' which allows to get a map of formatted cells
-- from an existing worksheet and its workbook's style sheet
toFormattedCells :: CellMap -> [Range] -> StyleSheet -> Map (RowIndex, ColumnIndex) FormattedCell
toFormattedCells m merges StyleSheet{..} = applyMerges $ M.map toFormattedCell m
where
toFormattedCell cell@Cell{..} =
FormattedCell
{ _formattedCell = cell{ _cellStyle = Nothing } -- just to remove confusion
, _formattedFormat = maybe def formatFromStyle $ flip M.lookup cellXfs =<< _cellStyle
, _formattedColSpan = 1
, _formattedRowSpan = 1 }
formatFromStyle cellXf =
Format
{ _formatAlignment = applied _cellXfApplyAlignment _cellXfAlignment cellXf
, _formatBorder = flip M.lookup borders =<<
applied _cellXfApplyBorder _cellXfBorderId cellXf
, _formatFill = flip M.lookup fills =<<
applied _cellXfApplyFill _cellXfFillId cellXf
, _formatFont = flip M.lookup fonts =<<
applied _cellXfApplyFont _cellXfFontId cellXf
, _formatNumberFormat = lookupNumFmt =<<
applied _cellXfApplyNumberFormat _cellXfNumFmtId cellXf
, _formatProtection = _cellXfProtection cellXf
, _formatPivotButton = _cellXfPivotButton cellXf
, _formatQuotePrefix = _cellXfQuotePrefix cellXf }
idMapped :: [a] -> Map Int a
idMapped = M.fromList . zip [0..]
cellXfs = idMapped _styleSheetCellXfs
borders = idMapped _styleSheetBorders
fills = idMapped _styleSheetFills
fonts = idMapped _styleSheetFonts
lookupNumFmt fId = asum
[ StdNumberFormat <$> idToStdNumberFormat fId
, UserNumberFormat <$> M.lookup fId _styleSheetNumFmts]
applied :: (CellXf -> Maybe Bool) -> (CellXf -> Maybe a) -> CellXf -> Maybe a
applied applyProp prop cXf = do
apply <- applyProp cXf
if apply then prop cXf else fail "not applied"
applyMerges cells = foldl' onlyTopLeft cells merges
onlyTopLeft cells range = flip execState cells $ do
let ((r1, c1), (r2, c2)) =
fromJustNote "fromRange" $ fromRange range
nonTopLeft = tail [(r, c) | r<-[r1..r2], c<-[c1..c2]]
forM_ nonTopLeft (modify . M.delete)
at (r1, c1) . non def . formattedRowSpan .=
(unRowIndex r2 - unRowIndex r1 + 1)
at (r1, c1) . non def . formattedColSpan .=
(unColumnIndex c2 - unColumnIndex c1 + 1)
data CondFormatted = CondFormatted {
-- | The resulting stylesheet
condformattedStyleSheet :: StyleSheet
-- | The final map of conditional formatting rules applied to ranges
, condformattedFormattings :: Map SqRef ConditionalFormatting
} deriving (Eq, Show, Generic)
conditionallyFormatted :: Map CellRef [FormattedCondFmt] -> StyleSheet -> CondFormatted
conditionallyFormatted cfs styleSheet = CondFormatted
{ condformattedStyleSheet = styleSheet & styleSheetDxfs .~ finalDxfs
, condformattedFormattings = fmts
}
where
(cellFmts, dxf2id) = runState (mapM (mapM mapDxf) cfs) dxf2id0
dxf2id0 = fromValueList (styleSheet ^. styleSheetDxfs)
fmts = M.fromList . map mergeSqRef . groupBy ((==) `on` snd) .
sortBy (comparing snd) $ M.toList cellFmts
mergeSqRef cellRefs2fmt =
(SqRef (map fst cellRefs2fmt),
headNote "fmt group should not be empty" (map snd cellRefs2fmt))
finalDxfs = toValueList dxf2id
{-------------------------------------------------------------------------------
Implementation details
-------------------------------------------------------------------------------}
| Format a cell with ( potentially ) rowspan or colspan
formatCell :: (RowIndex, ColumnIndex) -> FormattedCell
-> State FormattingState [((RowIndex, ColumnIndex), Cell)]
formatCell (row, col) cell = do
let (block, mMerge) = cellBlock (row, col) cell
forM_ mMerge $ \merge -> formattingMerges %= (:) merge
mapM go block
where
go :: ((RowIndex, ColumnIndex), FormattedCell)
-> State FormattingState ((RowIndex, ColumnIndex), Cell)
go (pos, c@FormattedCell{..}) = do
styleId <- cellStyleId c
return (pos, _formattedCell{_cellStyle = styleId})
| Cell block corresponding to a single ' FormattedCell '
--
A single ' FormattedCell ' might have a colspan or rowspan greater than 1 .
Although Excel obviously supports cell merges , it does not correctly apply
borders to the cells covered by the rowspan or colspan . Therefore we create
-- a block of cells in this function; the top-left is the cell proper, and the
-- remaining cells are the cells covered by the rowspan/colspan.
--
-- Also returns the cell merge instruction, if any.
cellBlock :: (RowIndex, ColumnIndex) -> FormattedCell
-> ([((RowIndex, ColumnIndex), FormattedCell)], Maybe Range)
cellBlock (row, col) cell@FormattedCell{..} = (block, merge)
where
block :: [((RowIndex, ColumnIndex), FormattedCell)]
block = [ ((row', col'), cellAt (row', col'))
| row' <- [topRow .. bottomRow]
, col' <- [leftCol .. rightCol]
]
merge :: Maybe Range
merge = do guard (topRow /= bottomRow || leftCol /= rightCol)
return $ mkRange (topRow, leftCol) (bottomRow, rightCol)
cellAt :: (RowIndex, ColumnIndex) -> FormattedCell
cellAt (row', col') =
if row' == row && col == col'
then cell
else def & formattedFormat . formatBorder ?~ borderAt (row', col')
border = _formatBorder _formattedFormat
borderAt :: (RowIndex, ColumnIndex) -> Border
borderAt (row', col') = def
& borderTop .~ do guard (row' == topRow) ; _borderTop =<< border
& borderBottom .~ do guard (row' == bottomRow) ; _borderBottom =<< border
& borderLeft .~ do guard (col' == leftCol) ; _borderLeft =<< border
& borderRight .~ do guard (col' == rightCol) ; _borderRight =<< border
topRow, bottomRow :: RowIndex
leftCol, rightCol :: ColumnIndex
topRow = row
bottomRow = RowIndex $ unRowIndex row + _formattedRowSpan - 1
leftCol = col
rightCol = ColumnIndex $ unColumnIndex col + _formattedColSpan - 1
cellStyleId :: FormattedCell -> State FormattingState (Maybe Int)
cellStyleId c = mapM (getId formattingCellXfs) =<< constructCellXf c
constructCellXf :: FormattedCell -> State FormattingState (Maybe CellXf)
constructCellXf FormattedCell{_formattedFormat=Format{..}} = do
mBorderId <- getId formattingBorders `mapM` _formatBorder
mFillId <- getId formattingFills `mapM` _formatFill
mFontId <- getId formattingFonts `mapM` _formatFont
let getFmtId :: Lens' FormattingState (Map Text Int) -> NumberFormat -> State FormattingState Int
getFmtId _ (StdNumberFormat fmt) = return (stdNumberFormatId fmt)
getFmtId l (UserNumberFormat fmt) = getId' firstUserNumFmtId l fmt
mNumFmtId <- getFmtId formattingNumFmts `mapM` _formatNumberFormat
let xf = CellXf {
_cellXfApplyAlignment = apply _formatAlignment
, _cellXfApplyBorder = apply mBorderId
, _cellXfApplyFill = apply mFillId
, _cellXfApplyFont = apply mFontId
, _cellXfApplyNumberFormat = apply _formatNumberFormat
, _cellXfApplyProtection = apply _formatProtection
, _cellXfBorderId = mBorderId
, _cellXfFillId = mFillId
, _cellXfFontId = mFontId
, _cellXfNumFmtId = mNumFmtId
, _cellXfPivotButton = _formatPivotButton
, _cellXfQuotePrefix = _formatQuotePrefix
TODO
, _cellXfAlignment = _formatAlignment
, _cellXfProtection = _formatProtection
}
return $ if xf == def then Nothing else Just xf
where
-- If we have formatting instructions, we want to set the corresponding
-- applyXXX properties
apply :: Maybe a -> Maybe Bool
apply Nothing = Nothing
apply (Just _) = Just True
mapDxf :: FormattedCondFmt -> State (Map Dxf Int) CfRule
mapDxf FormattedCondFmt{..} = do
dxf2id <- get
dxfId <- case M.lookup _condfmtDxf dxf2id of
Just i ->
return i
Nothing -> do
let newId = M.size dxf2id
modify $ M.insert _condfmtDxf newId
return newId
return CfRule
{ _cfrCondition = _condfmtCondition
, _cfrDxfId = Just dxfId
, _cfrPriority = _condfmtPriority
, _cfrStopIfTrue = _condfmtStopIfTrue
}
| null | https://raw.githubusercontent.com/qrilka/xlsx/e6004bd4fb7f87c2c964e7bd7bd5da0a5e09836c/src/Codec/Xlsx/Formatted.hs | haskell | | Higher level interface for creating styled worksheets
# LANGUAGE CPP #
# LANGUAGE RankNTypes #
* Lenses
** Format
** FormattedCondFmt
------------------------------------------------------------------------------
Internal: formatting state
------------------------------------------------------------------------------
^ In reverse order
------------------------------------------------------------------------------
Unwrapped cell conditional formatting
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Cell with formatting
------------------------------------------------------------------------------
| Formatting options used to format cells
* Add references to the named style sheets ('_cellXfId')
See 'formatted' for more details.
------------------------------------------------------------------------------
Default instances
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Client-facing API
------------------------------------------------------------------------------
| Result of formatting
See 'formatted'
| The final stylesheet; see '_xlStyles' (and 'renderStyleSheet')
| The final list of cell merges; see '_wsMerges'
| Higher level API for creating formatted documents
This has a number of causes:
* The 'Cell' datatype wants an 'Int' for the style, which is supposed to
point into the '_styleSheetCellXfs' part of a stylesheet. However, this can
be difficult to work with, as it requires manual tracking of cell style
IDs, which in turns requires manual tracking of font IDs, border IDs, etc.
* Row-span and column-span properties are set on the worksheet as a whole
('wsMerges') rather than on individual cells.
* Excel does not correctly deal with borders on cells that span multiple
columns or rows. Instead, these rows must be set on all the edge cells
in the block. Again, this means that this becomes a global property of
the spreadsheet rather than properties of individual cells.
border IDs, etc.), and an initial stylesheet, it recovers all possible
the final stylesheet and list of merges.
If you don't already have a 'StyleSheet' you want to use as starting point
then 'minimalStyleSheet' is a good choice.
| Build an 'Xlsx', render provided cells as per the 'StyleSheet'.
| reverse to 'formatted' which allows to get a map of formatted cells
from an existing worksheet and its workbook's style sheet
just to remove confusion
| The resulting stylesheet
| The final map of conditional formatting rules applied to ranges
------------------------------------------------------------------------------
Implementation details
------------------------------------------------------------------------------
a block of cells in this function; the top-left is the cell proper, and the
remaining cells are the cells covered by the rowspan/colspan.
Also returns the cell merge instruction, if any.
If we have formatting instructions, we want to set the corresponding
applyXXX properties | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE DeriveGeneric #
module Codec.Xlsx.Formatted
( FormattedCell(..)
, Formatted(..)
, Format(..)
, formatted
, formatWorkbook
, toFormattedCells
, CondFormatted(..)
, conditionallyFormatted
, formatAlignment
, formatBorder
, formatFill
, formatFont
, formatNumberFormat
, formatProtection
, formatPivotButton
, formatQuotePrefix
* * FormattedCell
, formattedCell
, formattedFormat
, formattedColSpan
, formattedRowSpan
, condfmtCondition
, condfmtDxf
, condfmtPriority
, condfmtStopIfTrue
) where
#ifdef USE_MICROLENS
import Lens.Micro
import Lens.Micro.Mtl
import Lens.Micro.TH
import Lens.Micro.GHC ()
#else
import Control.Lens
#endif
import Control.Monad (forM, guard)
import Control.Monad.State hiding (forM_, mapM)
import Data.Default
import Data.Foldable (asum, forM_)
import Data.Function (on)
import Data.List (foldl', groupBy, sortBy, sortBy)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.Text (Text)
import Data.Traversable (mapM)
import Data.Tuple (swap)
import GHC.Generics (Generic)
import Prelude hiding (mapM)
import Safe (headNote, fromJustNote)
import Codec.Xlsx.Types
data FormattingState = FormattingState {
_formattingBorders :: Map Border Int
, _formattingCellXfs :: Map CellXf Int
, _formattingFills :: Map Fill Int
, _formattingFonts :: Map Font Int
, _formattingNumFmts :: Map Text Int
}
makeLenses ''FormattingState
stateFromStyleSheet :: StyleSheet -> FormattingState
stateFromStyleSheet StyleSheet{..} = FormattingState{
_formattingBorders = fromValueList _styleSheetBorders
, _formattingCellXfs = fromValueList _styleSheetCellXfs
, _formattingFills = fromValueList _styleSheetFills
, _formattingFonts = fromValueList _styleSheetFonts
, _formattingNumFmts = M.fromList . map swap $ M.toList _styleSheetNumFmts
, _formattingMerges = []
}
fromValueList :: Ord a => [a] -> Map a Int
fromValueList = M.fromList . (`zip` [0..])
toValueList :: Map a Int -> [a]
toValueList = map snd . sortBy (comparing fst) . map swap . M.toList
updateStyleSheetFromState :: StyleSheet -> FormattingState -> StyleSheet
updateStyleSheetFromState sSheet FormattingState{..} = sSheet
{ _styleSheetBorders = toValueList _formattingBorders
, _styleSheetCellXfs = toValueList _formattingCellXfs
, _styleSheetFills = toValueList _formattingFills
, _styleSheetFonts = toValueList _formattingFonts
, _styleSheetNumFmts = M.fromList . map swap $ M.toList _formattingNumFmts
}
getId :: Ord a => Lens' FormattingState (Map a Int) -> a -> State FormattingState Int
getId = getId' 0
getId' :: Ord a
=> Int
-> Lens' FormattingState (Map a Int)
-> a
-> State FormattingState Int
getId' k f v = do
aMap <- use f
case M.lookup v aMap of
Just anId -> return anId
Nothing -> do let anId = k + M.size aMap
f %= M.insert v anId
return anId
data FormattedCondFmt = FormattedCondFmt
{ _condfmtCondition :: Condition
, _condfmtDxf :: Dxf
, _condfmtPriority :: Int
, _condfmtStopIfTrue :: Maybe Bool
} deriving (Eq, Show, Generic)
makeLenses ''FormattedCondFmt
TODOs :
* Add a number format ( ' _ cellXfApplyNumberFormat ' , ' _ cellXfNumFmtId ' )
data Format = Format
{ _formatAlignment :: Maybe Alignment
, _formatBorder :: Maybe Border
, _formatFill :: Maybe Fill
, _formatFont :: Maybe Font
, _formatNumberFormat :: Maybe NumberFormat
, _formatProtection :: Maybe Protection
, _formatPivotButton :: Maybe Bool
, _formatQuotePrefix :: Maybe Bool
} deriving (Eq, Show, Generic)
makeLenses ''Format
| Cell with formatting . ' _ ' property of ' _ formattedCell ' is ignored
data FormattedCell = FormattedCell
{ _formattedCell :: Cell
, _formattedFormat :: Format
, _formattedColSpan :: Int
, _formattedRowSpan :: Int
} deriving (Eq, Show, Generic)
makeLenses ''FormattedCell
instance Default FormattedCell where
def = FormattedCell
{ _formattedCell = def
, _formattedFormat = def
, _formattedColSpan = 1
, _formattedRowSpan = 1
}
instance Default Format where
def = Format
{ _formatAlignment = Nothing
, _formatBorder = Nothing
, _formatFill = Nothing
, _formatFont = Nothing
, _formatNumberFormat = Nothing
, _formatProtection = Nothing
, _formatPivotButton = Nothing
, _formatQuotePrefix = Nothing
}
instance Default FormattedCondFmt where
def = FormattedCondFmt ContainsBlanks def topCfPriority Nothing
data Formatted = Formatted {
| The final ' CellMap ' ; see ' _ wsCells '
formattedCellMap :: CellMap
, formattedStyleSheet :: StyleSheet
, formattedMerges :: [Range]
} deriving (Eq, Show, Generic)
Creating formatted Excel spreadsheets using the ' Cell ' datatype directly ,
even with the support for the ' StyleSheet ' datatype , is fairly painful .
This function deals with all these problems . Given a map of ' FormattedCell 's ,
which refer directly to ' 's , ' Border 's , etc . ( rather than font IDs ,
sharing , constructs IDs , and then constructs the final ' CellMap ' , as well as
formatted :: Map (RowIndex, ColumnIndex) FormattedCell -> StyleSheet -> Formatted
formatted cs styleSheet =
let initSt = stateFromStyleSheet styleSheet
(cs', finalSt) = runState (mapM (uncurry formatCell) (M.toList cs)) initSt
styleSheet' = updateStyleSheetFromState styleSheet finalSt
in Formatted {
formattedCellMap = M.fromList (concat cs')
, formattedStyleSheet = styleSheet'
, formattedMerges = reverse (finalSt ^. formattingMerges)
}
formatWorkbook ::
[(Text, Map (RowIndex, ColumnIndex) FormattedCell)] -> StyleSheet -> Xlsx
formatWorkbook nfcss initStyle = extract go
where
initSt = stateFromStyleSheet initStyle
go = flip runState initSt $
forM nfcss $ \(name, fcs) -> do
cs' <- forM (M.toList fcs) $ \(rc, fc) -> formatCell rc fc
merges <- reverse . _formattingMerges <$> get
return ( name
, def & wsCells .~ M.fromList (concat cs')
& wsMerges .~ merges)
extract (sheets, st) =
def & xlSheets .~ sheets
& xlStyles .~ renderStyleSheet (updateStyleSheetFromState initStyle st)
toFormattedCells :: CellMap -> [Range] -> StyleSheet -> Map (RowIndex, ColumnIndex) FormattedCell
toFormattedCells m merges StyleSheet{..} = applyMerges $ M.map toFormattedCell m
where
toFormattedCell cell@Cell{..} =
FormattedCell
, _formattedFormat = maybe def formatFromStyle $ flip M.lookup cellXfs =<< _cellStyle
, _formattedColSpan = 1
, _formattedRowSpan = 1 }
formatFromStyle cellXf =
Format
{ _formatAlignment = applied _cellXfApplyAlignment _cellXfAlignment cellXf
, _formatBorder = flip M.lookup borders =<<
applied _cellXfApplyBorder _cellXfBorderId cellXf
, _formatFill = flip M.lookup fills =<<
applied _cellXfApplyFill _cellXfFillId cellXf
, _formatFont = flip M.lookup fonts =<<
applied _cellXfApplyFont _cellXfFontId cellXf
, _formatNumberFormat = lookupNumFmt =<<
applied _cellXfApplyNumberFormat _cellXfNumFmtId cellXf
, _formatProtection = _cellXfProtection cellXf
, _formatPivotButton = _cellXfPivotButton cellXf
, _formatQuotePrefix = _cellXfQuotePrefix cellXf }
idMapped :: [a] -> Map Int a
idMapped = M.fromList . zip [0..]
cellXfs = idMapped _styleSheetCellXfs
borders = idMapped _styleSheetBorders
fills = idMapped _styleSheetFills
fonts = idMapped _styleSheetFonts
lookupNumFmt fId = asum
[ StdNumberFormat <$> idToStdNumberFormat fId
, UserNumberFormat <$> M.lookup fId _styleSheetNumFmts]
applied :: (CellXf -> Maybe Bool) -> (CellXf -> Maybe a) -> CellXf -> Maybe a
applied applyProp prop cXf = do
apply <- applyProp cXf
if apply then prop cXf else fail "not applied"
applyMerges cells = foldl' onlyTopLeft cells merges
onlyTopLeft cells range = flip execState cells $ do
let ((r1, c1), (r2, c2)) =
fromJustNote "fromRange" $ fromRange range
nonTopLeft = tail [(r, c) | r<-[r1..r2], c<-[c1..c2]]
forM_ nonTopLeft (modify . M.delete)
at (r1, c1) . non def . formattedRowSpan .=
(unRowIndex r2 - unRowIndex r1 + 1)
at (r1, c1) . non def . formattedColSpan .=
(unColumnIndex c2 - unColumnIndex c1 + 1)
data CondFormatted = CondFormatted {
condformattedStyleSheet :: StyleSheet
, condformattedFormattings :: Map SqRef ConditionalFormatting
} deriving (Eq, Show, Generic)
conditionallyFormatted :: Map CellRef [FormattedCondFmt] -> StyleSheet -> CondFormatted
conditionallyFormatted cfs styleSheet = CondFormatted
{ condformattedStyleSheet = styleSheet & styleSheetDxfs .~ finalDxfs
, condformattedFormattings = fmts
}
where
(cellFmts, dxf2id) = runState (mapM (mapM mapDxf) cfs) dxf2id0
dxf2id0 = fromValueList (styleSheet ^. styleSheetDxfs)
fmts = M.fromList . map mergeSqRef . groupBy ((==) `on` snd) .
sortBy (comparing snd) $ M.toList cellFmts
mergeSqRef cellRefs2fmt =
(SqRef (map fst cellRefs2fmt),
headNote "fmt group should not be empty" (map snd cellRefs2fmt))
finalDxfs = toValueList dxf2id
| Format a cell with ( potentially ) rowspan or colspan
formatCell :: (RowIndex, ColumnIndex) -> FormattedCell
-> State FormattingState [((RowIndex, ColumnIndex), Cell)]
formatCell (row, col) cell = do
let (block, mMerge) = cellBlock (row, col) cell
forM_ mMerge $ \merge -> formattingMerges %= (:) merge
mapM go block
where
go :: ((RowIndex, ColumnIndex), FormattedCell)
-> State FormattingState ((RowIndex, ColumnIndex), Cell)
go (pos, c@FormattedCell{..}) = do
styleId <- cellStyleId c
return (pos, _formattedCell{_cellStyle = styleId})
| Cell block corresponding to a single ' FormattedCell '
A single ' FormattedCell ' might have a colspan or rowspan greater than 1 .
Although Excel obviously supports cell merges , it does not correctly apply
borders to the cells covered by the rowspan or colspan . Therefore we create
cellBlock :: (RowIndex, ColumnIndex) -> FormattedCell
-> ([((RowIndex, ColumnIndex), FormattedCell)], Maybe Range)
cellBlock (row, col) cell@FormattedCell{..} = (block, merge)
where
block :: [((RowIndex, ColumnIndex), FormattedCell)]
block = [ ((row', col'), cellAt (row', col'))
| row' <- [topRow .. bottomRow]
, col' <- [leftCol .. rightCol]
]
merge :: Maybe Range
merge = do guard (topRow /= bottomRow || leftCol /= rightCol)
return $ mkRange (topRow, leftCol) (bottomRow, rightCol)
cellAt :: (RowIndex, ColumnIndex) -> FormattedCell
cellAt (row', col') =
if row' == row && col == col'
then cell
else def & formattedFormat . formatBorder ?~ borderAt (row', col')
border = _formatBorder _formattedFormat
borderAt :: (RowIndex, ColumnIndex) -> Border
borderAt (row', col') = def
& borderTop .~ do guard (row' == topRow) ; _borderTop =<< border
& borderBottom .~ do guard (row' == bottomRow) ; _borderBottom =<< border
& borderLeft .~ do guard (col' == leftCol) ; _borderLeft =<< border
& borderRight .~ do guard (col' == rightCol) ; _borderRight =<< border
topRow, bottomRow :: RowIndex
leftCol, rightCol :: ColumnIndex
topRow = row
bottomRow = RowIndex $ unRowIndex row + _formattedRowSpan - 1
leftCol = col
rightCol = ColumnIndex $ unColumnIndex col + _formattedColSpan - 1
cellStyleId :: FormattedCell -> State FormattingState (Maybe Int)
cellStyleId c = mapM (getId formattingCellXfs) =<< constructCellXf c
constructCellXf :: FormattedCell -> State FormattingState (Maybe CellXf)
constructCellXf FormattedCell{_formattedFormat=Format{..}} = do
mBorderId <- getId formattingBorders `mapM` _formatBorder
mFillId <- getId formattingFills `mapM` _formatFill
mFontId <- getId formattingFonts `mapM` _formatFont
let getFmtId :: Lens' FormattingState (Map Text Int) -> NumberFormat -> State FormattingState Int
getFmtId _ (StdNumberFormat fmt) = return (stdNumberFormatId fmt)
getFmtId l (UserNumberFormat fmt) = getId' firstUserNumFmtId l fmt
mNumFmtId <- getFmtId formattingNumFmts `mapM` _formatNumberFormat
let xf = CellXf {
_cellXfApplyAlignment = apply _formatAlignment
, _cellXfApplyBorder = apply mBorderId
, _cellXfApplyFill = apply mFillId
, _cellXfApplyFont = apply mFontId
, _cellXfApplyNumberFormat = apply _formatNumberFormat
, _cellXfApplyProtection = apply _formatProtection
, _cellXfBorderId = mBorderId
, _cellXfFillId = mFillId
, _cellXfFontId = mFontId
, _cellXfNumFmtId = mNumFmtId
, _cellXfPivotButton = _formatPivotButton
, _cellXfQuotePrefix = _formatQuotePrefix
TODO
, _cellXfAlignment = _formatAlignment
, _cellXfProtection = _formatProtection
}
return $ if xf == def then Nothing else Just xf
where
apply :: Maybe a -> Maybe Bool
apply Nothing = Nothing
apply (Just _) = Just True
mapDxf :: FormattedCondFmt -> State (Map Dxf Int) CfRule
mapDxf FormattedCondFmt{..} = do
dxf2id <- get
dxfId <- case M.lookup _condfmtDxf dxf2id of
Just i ->
return i
Nothing -> do
let newId = M.size dxf2id
modify $ M.insert _condfmtDxf newId
return newId
return CfRule
{ _cfrCondition = _condfmtCondition
, _cfrDxfId = Just dxfId
, _cfrPriority = _condfmtPriority
, _cfrStopIfTrue = _condfmtStopIfTrue
}
|
395021d9e07947e5f3a2678fd0c6ef334e8a06da6990e2e34a1ad4d866f552ed | Feuerlabs/kvdb | kvdb_leveldb.erl | %%%---- BEGIN COPYRIGHT -------------------------------------------------------
%%%
Copyright ( C ) 2012 Feuerlabs , Inc. All rights reserved .
%%%
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%%---- END COPYRIGHT ---------------------------------------------------------
@author
@author < >
%%% @hidden
%%% @doc
to
%%% @end
-module(kvdb_leveldb).
-behaviour(kvdb).
-export([open/2, close/1]).
-export([add_table/3, delete_table/2, list_tables/1]).
-export([put/3, push/4, get/3, get_attrs/4, index_get/4, index_keys/4,
update_counter/4, pop/3, prel_pop/3, extract/3, delete/3,
list_queue/3, list_queue/6, list_queue/7, is_queue_empty/3,
queue_read/3, queue_insert/5, queue_delete/3, mark_queue_object/4,
queue_head_write/4, queue_head_read/3, queue_head_delete/3]).
-export([first_queue/2, next_queue/3]).
-export([first/2, last/2, next/3, prev/3,
prefix_match/3, prefix_match/4, prefix_match_rel/5]).
-export([get_schema_mod/2]).
-export([schema_write/4, schema_read/3, schema_delete/3, schema_fold/3]).
-export([info/2, is_table/2]).
-export([dump_tables/1]).
-import(kvdb_lib, [dec/3, enc/3]).
-include("kvdb.hrl").
-define(if_table(Db, Tab, Expr), if_table(Db, Tab, fun() -> Expr end)).
info(#db{} = Db, What) ->
case What of
tables -> list_tables(Db);
encoding -> Db#db.encoding;
ref -> Db#db.ref;
{Tab,encoding} -> ?if_table(Db, Tab, encoding(Db, Tab));
{Tab,index } -> ?if_table(Db, Tab, index(Db, Tab));
{Tab,type } -> ?if_table(Db, Tab, type(Db, Tab));
{Tab,schema } -> ?if_table(Db, Tab, schema(Db, Tab));
{Tab,tabrec } -> schema_lookup(Db, {table, Tab}, undefined);
_ -> undefined
end.
is_table(#db{metadata = ETS}, Tab) ->
ets:member(ETS, {table, Tab}).
if_table(Db, Tab, F) ->
case is_table(Db, Tab) of
true -> F();
false -> undefined
end.
dump_tables(#db{ref = Ref} = Db) ->
with_iterator(
Ref,
fun(I) ->
dump_tables_(eleveldb:iterator_move(I, first), I, Db)
end).
dump_tables_({ok, K, V}, I, Db) ->
Type = bin_match([{$:, obj}, {$=, attr}, {$?, index}], K),
io:fwrite("Type = ~p: K=~p; V=~p~n", [Type, K, V]),
Obj = case Type of
obj ->
[T, Key] = binary:split(K, <<":">>),
case Key of
<<>> ->
{tab_obj, T, kvdb_lib:try_decode(V)};
_ ->
Enc = encoding(Db, T),
case type(Db, T) of
set ->
{obj, T, kvdb_lib:try_decode(Key),
kvdb_lib:try_decode(V)};
TType when TType == fifo; TType == lifo;
element(2, TType) == fifo;
element(2, TType) == lifo ->
io : fwrite("split_queue_key(~p , ~p , ~p)~n " ,
[ Enc , TType , Key ] ) ,
#q_key{queue = Q,
key = Ko} = kvdb_lib:split_queue_key(
Enc, TType, Key),
<<F:8, Val/binary>> = V,
St = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
Kr = dec(key, Key, Enc),
{q_obj, T, Q, Kr,
{Ko, kvdb_lib:try_decode(Val)}, St}
end
end;
attr ->
[T, AKey] = binary:split(K, <<"=">>),
io : fwrite("attr : T=~p ; AKey=~p ~ n " , [ T , AKey ] ) ,
%% {OKey, Rest} = sext:decode_next(AKey),
%% Attr = sext:decode(Rest),
{OKey, Attr} = decode_attr_key(Db, T, AKey),
{attr, T, OKey, Attr, binary_to_term(V)};
index ->
[T, IKey] = binary:split(K, <<"?">>),
{Ix, Rest} = sext:decode_next(IKey),
io : fwrite("index : T=~p ; Ix = ~p ; Rest = ~p ~ n " , [ T , Ix , Rest ] ) ,
{index, T, Ix, sext:decode(Rest), V};
unknown ->
{unknown, K, V}
end,
[Obj | dump_tables_(eleveldb:iterator_move(I, next), I, Db)];
dump_tables_({error, _}, _, _) ->
[];
dump_tables_(Other, _, _) ->
io:fwrite("dump_tables_(~p, _, _)~n", [Other]).
< < Key / binary , ( sext : encode(AttrName))/binary > >
decode_attr_key(Db, Tab, K) ->
case key_encoding(Db, Tab) of
sext ->
[Kdec, Rest] = sext:decode_next(K),
{Kdec, sext:decode(Rest)};
raw ->
%% This is the hard part
since the first part is an arbitrary binary , we must guess where
%% the sext-encoded attribute name starts. We know what the start
%% codes of a sext-encoded term can be. Try each, in order.
{match, Ps} =
re:run(K,<<"[",8,9,10,11,12,13,14,15,16,17,18,19,"]">>,
[global]),
{P, AName} = try_sext_decode(lists:flatten(Ps), K),
<<Key:P/binary, _/binary>> = K,
{Key, AName}
end.
key_encoding(Db, T) ->
case encoding(Db, T) of
E when is_atom(E) -> E;
E when is_tuple(E) -> element(1, E)
end.
try_sext_decode([{P,_}|Ps], K) ->
<<_:P/binary, Rest/binary>> = K,
try A = sext:decode(Rest),
{P, A}
catch
error:_ ->
try_sext_decode(Ps, K)
end.
bin_match(Ts, B) ->
Cs = << << "\\", C:8 >> || {C,_} <- Ts >>,
Pat = << "[", Cs/binary, "]" >>,
case re:run(B, Pat, [{capture, first, list}]) of
{match, [[C]]} ->
{_,T} = lists:keyfind(C,1,Ts),
T;
_ ->
unknown
end.
get_schema_mod(Db, Default) ->
case schema_lookup(Db, schema_mod, undefined) of
undefined ->
schema_write(Db, {schema_mod, Default}),
Default;
M ->
M
end.
open(DbName, Options) ->
E = proplists:get_value(encoding, Options, sext),
kvdb_lib:check_valid_encoding(E),
DbOpts = proplists:get_value(db_opts, Options, [{create_if_missing,true}]),
Res = case proplists:get_value(file, Options) of
undefined ->
File = kvdb_lib:db_file(DbName),
eleveldb:open(File, DbOpts);
Name ->
filelib:ensure_dir(Name),
eleveldb:open(Name, DbOpts)
end,
case Res of
{ok, Ref} ->
{ok, ensure_schema(#db{ref = Ref, encoding = E}, Options)};
Error ->
Error
end.
%% make_string(A) when is_atom(A) ->
%% atom_to_list(A);
%% make_string(S) when is_list(S) ->
%% try binary_to_list(iolist_to_binary([S]))
%% catch
%% error:_ ->
%% lists:flatten(io_lib:fwrite("~w",[S]))
%% end;
%% make_string(B) when is_binary(B) ->
) ;
%% make_string(X) ->
%% lists:flatten(io_lib:fwrite("~w", [X])).
close(_Db) ->
%% leveldb is garbage collected
ok.
add_table(#db{encoding = Enc} = Db, Table, Opts) when is_list(Opts) ->
TabR = kvdb_lib:make_tabrec(Table, Opts, #table{encoding = Enc}),
add_table(Db, Table, TabR);
add_table(Db, Table, #table{} = TabR) ->
add_table(Db, Table, TabR, []).
add_table(Db, Table, #table{encoding = Enc, type = Type, index = Ix} = TabR, Opts) ->
case schema_lookup(Db, {table, Table}, undefined) of
T when T =/= undefined ->
ok;
undefined ->
case do_add_table(Db, Table) of
ok ->
schema_write(Db, {{table, Table}, TabR}),
[schema_write(Db, property, {Table, K}, V)
|| {K, V} <- [{encoding, Enc}, {type, Type}, {index, Ix} | Opts]],
ok;
Error ->
Error
end
end.
do_add_table(#db{ref = Db}, Table) ->
T = make_table_key(Table, <<>>),
eleveldb:put(Db, T, <<>>, []).
list_tables(#db{metadata = ETS}) ->
ets:select(ETS, [{ {{table, '$1'}, '_'},
[{'=/=','$1',?META_TABLE}], ['$1'] }]).
delete_table(#db{ref = Ref} = Db, Table) ->
case schema_lookup(Db, {table, Table}, undefined) of
undefined ->
ok;
#table{} ->
Kt = make_table_key(Table, <<>>),
Ka = make_key(Table, $=, <<>>),
Ki = make_key(Table, $?, <<>>),
with_iterator(
Ref,
fun(I) ->
delete_table_(eleveldb:iterator_move(I, Kt),
I, Kt,Ka,Ki, byte_size(Kt), Ref)
end),
schema_delete(Db, {table, Table}),
schema_delete(Db, {Table, encoding}),
ok
end.
delete_table_({ok, K, _V}, I, Kt,Ka,Ki, Sz, Ref) ->
case K of
<<X:Sz/binary, _/binary>> when X==Kt; X==Ka; X==Ki ->
eleveldb:delete(Ref, K, []),
delete_table_(eleveldb:iterator_move(I, next), I, Kt,Ka,Ki, Sz, Ref);
_ ->
ok
end;
delete_table_({error,invalid_iterator}, _, _, _, _, _, _) ->
ok.
put(Db, Table, Obj) ->
lager:debug("put: Db = ~p, Table = ~p, Obj = ~p ~n", [Db, Table, Obj]),
case type(Db, Table) of
set ->
put_(Db, Table, Obj, put);
_ ->
{error, illegal}
end.
put_(Db, Table, {K,V}, Op) ->
%% Frequently used case, therefore optimized. No indexing on {K,V} tuples
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = encode_elem(key, K, Type, Enc, Op),
Val = encode_elem(value, V, Type, Enc, Op),
put_raw(Db, Table, K, Key, none, V, Val, put);
put_(Db, Table, {K, Attrs, V}, Op) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = encode_elem(key, K, Type, Enc, Op),
Val = encode_elem(value, V, Type, Enc, Op),
put_raw(Db, Table, K, Key, Attrs, V, Val, put).
put_raw(#db{ref = Ref}, Table, _, Key, none, _, Val, _) ->
eleveldb:put(Ref, make_table_key(Table, Key), Val, []);
put_raw(#db{ref = Ref} = Db, Table, K, Key, Attrs, V, Val, Op) ->
OldAttrs = get_attrs_(Db, Table, Key, all),
Ix = index(Db, Table),
IxOps = case Ix of
[_|_] ->
OldIxVals = kvdb_lib:index_vals(
Ix, K, OldAttrs,
fun() ->
get_value(Db, Table, K)
end),
NewIxVals = kvdb_lib:index_vals(Ix, K, Attrs,
fun() -> V end),
[{delete, ix_key(Table, I, K)} ||
I <- OldIxVals -- NewIxVals]
++ [{put, ix_key(Table, I, K), <<>>} ||
I <- NewIxVals -- OldIxVals];
_ ->
[]
end,
DelAttrs = if element(2,Op) =/= push ->
attrs_to_delete(
Table, Key,
[{A,Va} ||
{A,Va} <- OldAttrs,
not lists:keymember(A, 1, Attrs)]);
true -> []
end,
PutAttrs = attrs_to_put(Table, Key, Attrs),
case eleveldb:write(Ref, [{put, make_table_key(Table, Key), Val}|
DelAttrs ++ PutAttrs ++ IxOps], []) of
ok ->
ok;
Other ->
Other
end.
encode_elem(_Elem, V, _T, _Enc, {queue,_}) when is_binary(V) ->
%% This should really be cleaned up, but for now, when put_(...) is called
%% from push(...), the key and value parts are already coded as binary.
V;
encode_elem(Elem, V, _, Enc, _) ->
enc(Elem, V, Enc).
ix_key(Table, I, K) ->
make_key(Table, $?, <<(sext:encode(I))/binary, (sext:encode(K))/binary>>).
update_counter(#db{ref = Ref} = Db, Table, K, Incr) when is_integer(Incr) ->
case type(Db, Table) of
set ->
Enc = encoding(Db, Table),
Key = enc(key, K, Enc),
case eleveldb:get(Ref, TabKey = make_table_key(Table, Key),
[{fill_cache, true}]) of
{ok, V} ->
NewV =
case dec(value, V, Enc) of
I when is_integer(I) ->
NewI = I + Incr,
enc(value, NewI, Enc);
B when is_binary(B) ->
Sz = bit_size(B),
<<I:Sz/integer>> = B,
NewI = I + Incr,
enc(value, <<NewI:Sz/integer>>, Enc);
_ ->
erlang:error(illegal)
end,
ok = eleveldb:put(Ref, TabKey, NewV, []),
dec(value, NewV, Enc);
_ ->
erlang:error(not_found)
end;
_ ->
erlang:error(illegal)
end.
push(#db{} = Db, Table, Q, Obj) ->
Type = type(Db, Table),
if Type == fifo; Type == lifo; element(1,Type) == keyed ->
Enc = encoding(Db, Table),
{_ActualKey, QKey} =
kvdb_lib:actual_key(Enc, Type, Q, element(1, Obj)),
{Key, Attrs, Value} = encode_queue_obj(
Enc, Type, setelement(1, Obj, QKey)),
case put_raw(Db, Table, QKey, Key, Attrs,
obj_val(Obj), Value, {queue,push}) of
ok ->
{ok, QKey};
Other ->
Other
end;
PutAttrs = attrs_to_put(Table , Key , ) ,
%% Put = {put, make_table_key(Table, Key), Value},
case : write(Ref , [ Put|PutAttrs ] , [ ] ) of
%% ok ->
%% {ok, QKey};
%% Other ->
%% Other
%% end;
true ->
erlang:error(illegal)
end.
queue_insert(#db{} = Db, Table, #q_key{} = QKey, St, Obj) when
St==blocking; St==active; St==inactive ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = : q_key_to_actual(QKey , Enc , Type ) ,
Obj1 = setelement(1, Obj, QKey),
put_(Db , Table , Obj1 , put ) .
{EncKey, Attrs, Value} = encode_queue_obj(Enc, Type, Obj1, St),
put_raw(Db, Table, QKey, EncKey, Attrs, obj_val(Obj1), Value,
{queue,put}).
obj_val({_,V} ) -> V;
obj_val({_,_,V}) -> V.
queue_head_write(#db{} = Db, Table, Queue, Obj) ->
Type = type(Db, Table),
HeadKey = kvdb_lib:q_head_key(Queue, Type),
queue_insert(Db, Table, HeadKey, active, Obj).
Key = enc(key , : q_key_to_actual(HeadKey , Enc , Type ) , Enc ) ,
%% Val = enc(value, Data, Enc),
eleveldb : put(Ref , make_table_key(Table , Key ) , , [ ] ) .
queue_head_read(#db{ref = Ref} = Db, Table, Queue) ->
Type = type(Db, Table),
Enc = encoding(Db, Table),
HeadKey = kvdb_lib:q_head_key(Queue, Type),
Key = kvdb_lib:q_key_to_actual(HeadKey, Enc, Type),
QHeadKey = make_table_key(Table, Key),
case eleveldb:get(Ref, QHeadKey, []) of
{ok, <<_:8, V/binary>>} ->
{ok, decode_obj_v(Db, Enc, Table, Key, HeadKey#q_key.key, V)};
{ ok , : dec(value , V , Enc ) } ;
not_found ->
{error, not_found}
end.
queue_head_delete(#db{} = _Db, _Table, _Queue) ->
exit(nyi).
queue_delete(Db, Table, #q_key{} = QKey) ->
_ = extract(Db, Table, QKey),
ok.
queue_delete_obj(#db{ref = Ref}, Table, EncKey, Obj) ->
Key = make_table_key(Table, EncKey),
Attrs = case Obj of
{_, As, _} -> As;
{_, _} -> []
end,
eleveldb:write(Ref, [{delete, Key}
| attrs_to_delete(Table, EncKey, Attrs)], []),
ok.
%% encode_queue_head_key(Table, Queue, Type, Enc) ->
HeadKey = : q_head_key(Queue , Type ) ,
Key = : q_key_to_actual(HeadKey , Enc , Type ) ,
%% make_table_key(Table, Key).
mark_queue_object(#db{} = Db, Table, #q_key{queue = Q} = QK, St) when
St==blocking; St==active; St==inactive ->
case queue_read(Db, Table, QK) of
{ok, _OldSt, Obj} ->
mark_queue_obj(Db, Table, encoding(Db,Table), QK, Obj, St),
{ok, Q, Obj};
{error,_} = E ->
E
end.
mark_queue_obj(#db{ref = Ref} = Db, Table, Enc, QK, Obj, St) when
St==blocking; St==active; St==inactive ->
Type = type(Db, Table),
AKey = : q_key_to_actual(QK , Enc , Type ) ,
{Key, _Attrs, Value} =
encode_queue_obj(Enc, Type, setelement(1,Obj,QK), St),
eleveldb:put(Ref, make_table_key(Table, Key), Value, []).
pop(#db{} = Db, Table, Q) ->
case type(Db, Table) of
set -> erlang:error(illegal);
T ->
Remove = fun(EncKey, _QKey, Obj, _) ->
queue_delete_obj(Db, Table, EncKey, Obj)
end,
do_pop(Db, Table, T, Q, Remove, false)
end.
prel_pop(Db, Table, Q) ->
case type(Db, Table) of
set -> erlang:error(illegal);
T ->
Remove = fun(_, QKey, Obj, Enc) ->
mark_queue_obj(Db, Table, Enc, QKey, Obj, blocking)
end,
do_pop(Db, Table, T, Q, Remove, true)
end.
do_pop(Db, Table, _Type, Q, Remove, ReturnKey) ->
Enc = encoding(Db, Table),
case list_queue_int(Db, Table, Q, fun(_RawKey, inactive, _, _) ->
skip;
(RawKey, _St,K,O) ->
{keep, {RawKey,K,O}}
end, _HeedBlock = true, 2, false) of
{[{Raw,QKey,Obj}|More], _} ->
%% Obj1 = fix_q_obj(Obj, Enc, Type),
Empty = More == [],
Remove(Raw, QKey, Obj, Enc),
if ReturnKey ->
{ok, Obj, QKey, Empty};
true ->
{ok, Obj, Empty}
end;
Stop when Stop == done; Stop == blocked ->
Stop
end.
extract(#db{ref = Ref} = Db, Table, #q_key{queue = Q, key = Key} = QKey) ->
case type(Db, Table) of
set -> erlang:error(illegal);
Type ->
Enc = encoding(Db, Table),
AKey = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
RawKey = make_table_key(Table, AKey),
case eleveldb:get(Ref, RawKey, []) of
{ok, <<St:8, V/binary>>} when St==$*; St==$-; St==$+ ->
Obj = decode_obj_v(Db, Enc, Table, AKey, Key, V),
eleveldb:delete(Ref, RawKey, []),
IsEmpty =
case list_queue(Db, Table, Q,
fun(_,_,O) ->
{keep,O}
end,
_HeedBlock=true, 1) of
{[_], _} -> false;
_ -> true
end,
{ok, setelement(1, Obj, Key), Q, IsEmpty};
not_found ->
{error, not_found};
{error,_} = Err ->
Err
end
end.
is_queue_empty(#db{ref = Ref} = Db, Table, Q) ->
Enc = encoding(Db, Table),
QPfx = kvdb_lib:queue_prefix(Enc, Q, first),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
case eleveldb:iterator_move(I, Prefix) of
{ok, <<QPrefix:Sz/binary, _/binary>>,
<<"*", _/binary>>} ->
%% blocking
false;
{ok, <<QPrefix:Sz/binary, _/binary>> = K, _} ->
<<TPrefix:TPSz/binary, Key/binary>> = K,
case Key of
<<>> -> true;
_ ->
false
end;
_ ->
true
end
end).
first_queue(#db{ref = Ref} = Db, Table) ->
Type = type(Db, Table),
case Type of
set -> erlang:error(illegal);
_ ->
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
first_queue_(
eleveldb:iterator_move(I, TPrefix), I, Db, Table,
TPrefix, TPSz)
end)
end.
first_queue_(Res, I, Db, Table, TPrefix, TPSz) ->
case Res of
{ok, <<TPrefix:TPSz/binary>>, _} ->
first_queue_(eleveldb:iterator_move(I, next), I, Db,
Table, TPrefix, TPSz);
{ok, <<TPrefix:TPSz/binary, K/binary>>, _} ->
Enc = encoding(Db, Table),
#q_key{queue = Q} =
kvdb_lib:split_queue_key(Enc, dec(key, K, Enc)),
{ok, Q};
_ ->
done
end.
next_queue(#db{ref = Ref} = Db, Table, Q) ->
Type = type(Db, Table),
case Type of
set -> erlang:error(illegal);
_ ->
Enc = encoding(Db, Table),
QPfx = kvdb_lib:queue_prefix(Enc, Q, last),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
next_queue_(eleveldb:iterator_move(I, Prefix), I,
Db, Table, QPrefix, Sz,
TPrefix, TPSz, Enc)
end)
end.
next_queue_(Res, I, Db, Table, QPrefix, Sz, TPrefix, TPSz, Enc) ->
case Res of
{ok, <<QPrefix:Sz/binary, _/binary>>, _} ->
next_queue_(eleveldb:iterator_move(I, next), I, Db, Table,
QPrefix, Sz, TPrefix, TPSz, Enc);
{ok, <<TPrefix:TPSz/binary, K/binary>>, _} ->
case kvdb_lib:split_queue_key(Enc, dec(key,K,Enc)) of
#q_key{key = ?Q_HEAD_KEY} ->
next_queue_(eleveldb:iterator_move(I, next), I, Db, Table,
QPrefix, Sz, TPrefix, TPSz, Enc);
#q_key{queue = Q} ->
{ok, Q}
end;
_ ->
done
end.
q_first_(I, Db, Table, Q, Head, Enc, HeedBlock) ->
QPfx = kvdb_lib:queue_prefix(Enc, Q, first),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
q_first_move(eleveldb:iterator_move(I, Prefix),
I, Db, Table, Enc, QPrefix, Sz, TPrefix, Head,
TPSz, HeedBlock).
q_first_move(Res, I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock) ->
case Res of
{ok, Head, _} ->
q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>>, <<"-", _/binary>>} ->
q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>> = K, <<F:8, V/binary>>} ->
if F == $*, HeedBlock ->
blocked;
true ->
<<TPrefix:TPSz/binary, Key/binary>> = K,
case Key of
<<>> -> q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz,
TPrefix, Head, TPSz, HeedBlock);
_ ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
{Key, Status, decode_obj(Db, Enc, Table, Key, V)}
end
end;
_ ->
done
end.
q_last(#db{ref = Ref } = Db , Table , Q , Enc ) - >
with_iterator(Ref , fun(I ) - > q_last_(I , Db , Table , Q , Enc ) end ) .
q_last_(I, Db, Table, Q, Head, Enc, HeedBlock) ->
QPfx = kvdb_lib:queue_prefix(Enc, Q, last),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
case eleveldb:iterator_move(I, Prefix) of
{ok, _K, _V} ->
q_last_move_(eleveldb:iterator_move(I, prev), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock);
{error, invalid_iterator} ->
q_last_move_(eleveldb:iterator_move(I, last), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock)
end.
q_last_move_(Res, I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock) ->
case Res of
{ok, Head, _} ->
q_last_move_(eleveldb:iterator_move(I, prev), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>>, <<"-", _/binary>>} ->
q_last_move_(eleveldb:iterator_move(I, prev),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>> = K1, <<F:8, V1/binary>>} ->
if F == $*, HeedBlock ->
blocked;
true ->
<<TPrefix:TPSz/binary, Key/binary>> = K1,
case Key of
<<>> -> done;
_ ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
{Key, Status, decode_obj(Db, Enc, Table, Key, V1)}
end
end;
_Other ->
done
end.
list_queue(Db, Table, Q) ->
list_queue(Db, Table, Q, fun(_,_,O) -> {keep,O} end, false, infinity).
list_queue(Db, Table, Q, Filter, HeedBlock, Limit) ->
list_queue(Db, Table, Q, Filter, HeedBlock, Limit, false).
list_queue(#db{} = Db, Table, Q, Filter, HeedBlock, Limit, Reverse)
when Limit > 0, is_boolean(Reverse) -> % includes 'infinity'
list_queue_int(Db, Table, Q, fun(_RawKey,St,K,O) -> Filter(St,K,O) end,
HeedBlock, Limit, Reverse).
list_queue_int(#db{ref = Ref} = Db, Table, Q, Filter,
HeedBlock, Limit, Reverse) when Limit > 0, is_boolean(Reverse) ->
Type = type(Db, Table),
Enc = encoding(Db, Table),
Head = make_table_key(
Table, kvdb_lib:q_key_to_actual(
kvdb_lib:q_head_key(Q, Type), Enc, Type)),
QPrefix = table_queue_prefix(Table, Q, Enc),
TPrefix = make_table_key(Table),
Dir = kvdb_lib:queue_list_direction(Type, Reverse),
with_iterator(
Ref,
fun(I) ->
First =
case Dir of
fifo -> q_first_(I, Db, Table, Q, Head, Enc, HeedBlock);
lifo -> q_last_(I, Db, Table, Q, Head, Enc, HeedBlock)
end,
q_all_(First, Limit, Limit, Filter, I, Db, Table,
q_all_dir(Dir), Enc, Type, QPrefix, TPrefix,
HeedBlock, [])
end);
list_queue_int(_, _, _, _, _, 0, _) ->
{[], fun() -> done end}.
q_all_dir(fifo) -> next;
q_all_dir(lifo) -> prev.
q_all_({RawKey, St, Obj}, Limit, Limit0, Filter, I, Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, Acc)
when Limit > 0 ->
#q_key{key = Key} = QKey =
kvdb_lib:split_queue_key(Enc,Type,element(1,Obj)),
{Cont,Acc1} = case Filter(RawKey, St, QKey, setelement(1, Obj, Key)) of
skip -> {true, Acc};
stop -> {false, Acc};
{stop,X} -> {false, [X|Acc]};
{keep,X} -> {true, [X|Acc]}
end,
case {Cont, decr(Limit)} of
{true, Limit1} when Limit1 > 0 ->
q_all_cont(Limit1, Limit0, Filter, I, Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, Acc1);
_ when Acc1 == [] ->
done;
{true, _} ->
TabKey = make_table_key(Table, enc(key, element(1, Obj), Enc)),
{lists:reverse(Acc1),
fun() ->
with_iterator(
Db#db.ref,
fun(I1) ->
eleveldb:iterator_move(I1, TabKey),
q_all_cont(Limit0, Limit0, Filter, I1,
Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, [])
end)
end};
{false, _}->
{lists:reverse(Acc1), fun() -> done end}
end;
q_all_(Stop, _, _, _, _, _, _, _, _, _, _, _, _, Acc)
when Stop == done; Stop == blocked ->
if Acc == [] -> Stop;
true ->
{lists:reverse(Acc), fun() -> Stop end}
end.
q_all_cont(Limit, Limit0, Filter, I, Db, Table, Dir, Enc, Type,
QPrefix, TPrefix, HeedBlock, Acc) ->
QSz = byte_size(QPrefix),
TSz = byte_size(TPrefix),
case eleveldb:iterator_move(I, Dir) of
{ok, <<QPrefix:QSz/binary, _/binary>> = K, <<F:8, V/binary>>} ->
if F == $*, HeedBlock ->
q_all_(blocked, Limit, Limit0, Filter, I, Db,
Table, Dir, Enc, Type, QPrefix, TPrefix,
HeedBlock, Acc);
true ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
<<TPrefix:TSz/binary, Key/binary>> = K,
q_all_({Key, Status, decode_obj(Db, Enc, Table, Key, V)},
Limit, Limit0, Filter, I, Db, Table,
Dir, Enc, Type, QPrefix, TPrefix, HeedBlock, Acc)
end;
_ ->
q_all_(done, Limit, Limit0, Filter, I, Db, Table, Dir,
Enc, Type, QPrefix, TPrefix, HeedBlock, Acc)
end.
table_queue_prefix(Table, Q, Enc) when Enc == raw; element(1, Enc) == raw ->
make_table_key(Table, <<(kvdb_lib:escape(Q))/binary, "%">>);
table_queue_prefix(Table, Q, Enc) when Enc == sext; element(1, Enc) == sext ->
make_table_key(Table, sext:prefix({Q,'_','_'})).
get(Db, Table, Key) ->
lager:debug("get: Db = ~p, Table = ~p, Key = ~p ~n", [Db, Table, Key]),
case type(Db, Table) of
set ->
get(Db, Table, Key, encoding(Db, Table), set);
_ ->
erlang:error(illegal)
end.
get(#db { } = Db , Table , # q_key { } = QKey , Enc , Type ) - >
Actual = : q_key_to_actual(QKey , Enc , Type ) ,
%% EncKey = enc(key, Actual, Enc),
get_(Db , Table , QKey#q_key.key , EncKey , Enc , Type ) ;
get(#db{} = Db, Table, Key, Enc, Type) ->
EncKey = enc(key, Key, Enc),
get_(Db, Table, Key, EncKey, Enc, Type).
get_(#db{ref = Ref} = Db, Table, Key, EncKey, Enc, Type) ->
case {Type, eleveldb:get(Ref, make_table_key(Table, EncKey), [])} of
{set, {ok, V}} ->
{ok, decode_obj_v(Db, Enc, Table, EncKey, Key, V)};
{_, {ok, <<F:8, V/binary>>}} when F==$*; F==$+; F==$- ->
{ok, decode_obj_v(Db, Enc, Table, EncKey, Key, V)};
{_, not_found} ->
{error, not_found};
{_, {error, _}} = Error ->
Error
end.
%% used during indexing (only if index function requires the value)
get_value(Db, Table, K) ->
case get(Db, Table, K) of
{ok, {_, _, V}} ->
V;
{ok, {_, V}} ->
V;
{error, not_found} ->
throw(no_value)
end.
index_get(#db{ref = Ref} = Db, Table, IxName, IxVal) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
IxPat = make_key(Table, $?, sext:encode({IxName, IxVal})),
with_iterator(
Ref,
fun(I) ->
get_by_ix_(prefix_move(I, IxPat, IxPat), I, IxPat, Db,
Table, Enc, Type, obj)
end).
index_keys(#db{ref = Ref} = Db, Table, IxName, IxVal) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
IxPat = make_key(Table, $?, sext:encode({IxName, IxVal})),
with_iterator(
Ref,
fun(I) ->
get_by_ix_(prefix_move(I, IxPat, IxPat), I, IxPat, Db,
Table, Enc, Type, key)
end).
get_by_ix_({ok, K, _}, I, Prefix, Db, Table, Enc, Type, Acc) ->
case get(Db, Table, sext:decode(K), Enc, Type) of
{ok, Obj} ->
Keep = case Acc of
obj -> Obj;
key -> element(1, Obj)
end,
[Keep | get_by_ix_(prefix_move(I, Prefix, next), I,
Prefix, Db, Table, Enc, Type, Acc)];
{error,_} ->
get_by_ix_(prefix_move(I, Prefix, next), I, Prefix,
Db, Table, Enc, Type, Acc)
end;
get_by_ix_(done, _, _, _, _, _, _, _) ->
[].
queue_read(#db{ref = Ref} = Db, Table, #q_key{key = K} = QKey) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
case eleveldb:get(Ref, make_table_key(Table, Key), []) of
{ok, <<St:8, V/binary>>} when St==$*; St==$-; St==$+ ->
Obj = decode_obj_v(Db, Enc, Table, Key, QKey, V),
Status = dec_queue_obj_status(St),
{ok, Status, setelement(1, Obj, K)};
not_found ->
{error, not_found};
{error, _} = Error ->
Error
end.
delete(#db{} = Db, Table, #q_key{} = QKey) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
EncKey = enc(key, Key, Enc),
delete_(Db, Table, Enc, Key, EncKey);
delete(#db{} = Db, Table, Key) ->
Enc = encoding(Db, Table),
EncKey = enc(key, Key, Enc),
delete_(Db, Table, Enc, Key, EncKey).
delete_(#db{ref = Ref} = Db, Table, Enc, Key, EncKey) ->
Ix = case Enc of
{_,_,_} -> index(Db, Table);
_ -> []
end,
{IxOps, As} =
case Enc of
{_, _, _} ->
Attrs = get_attrs_(Db, Table, EncKey, all),
IxOps_ = case Ix of
[_|_] -> [{delete, ix_key(Table, I, Key)} ||
I <- kvdb_lib:index_vals(
Ix, Key, Attrs,
fun() ->
get_value(Db, Table,
Key)
end)];
_ -> []
end,
{IxOps_, attrs_to_delete(Table, EncKey, Attrs)};
_ ->
{[], []}
end,
eleveldb:write(Ref, IxOps ++ [{delete, make_table_key(Table, EncKey)} | As], []).
attrs_to_put(_, _, []) -> [];
attrs_to_put(_, _, none) -> []; % still needed?
attrs_to_put(Table, Key, Attrs) when is_list(Attrs), is_binary(Key) ->
EncKey = sext : encode(Key ) ,
[{put, make_key(Table, $=, <<Key/binary,
(sext:encode(K))/binary>>),
term_to_binary(V)} || {K, V} <- Attrs].
attrs_to_delete(_, _, []) -> [];
attrs_to_delete(Table, Key, Attrs) when is_list(Attrs), is_binary(Key) ->
EncKey = sext : encode(Key ) ,
[{delete, make_key(Table, $=,
<<Key/binary,
(sext:encode(A))/binary>>)} || {A,_} <- Attrs].
get_attrs(#db{ref = Ref} = Db, Table, Key, As) ->
case encoding(Db, Table) of
{_, _, _} = Enc ->
EncKey = enc(key, Key, Enc),
case eleveldb:get(Ref, make_table_key(Table, EncKey), []) of
{ok, _} ->
{ok, get_attrs_(Db, Table, EncKey, As)};
_ ->
{error, not_found}
end;
_ ->
erlang:error(badarg)
end.
get_attrs_(#db{ref = Ref}, Table, EncKey, As) ->
TableKey = make_key(Table, $=, EncKey),
with_iterator(
Ref,
fun(I) ->
get_attrs_iter_(prefix_move(I, TableKey, TableKey),
I, TableKey, As)
end).
get_attrs_iter_({ok, K, V}, I, Prefix, As) ->
Key = sext:decode(K),
case As == all orelse lists:member(Key, As) of
true ->
[{Key, binary_to_term(V)}|
get_attrs_iter_(prefix_move(I, Prefix, next), I, Prefix, As)];
false ->
get_attrs_iter_(prefix_move(I, Prefix, next), I, Prefix, As)
end;
get_attrs_iter_(done, _, _, _) ->
[].
prefix_match(Db, Table, Prefix) ->
prefix_match(Db, Table, Prefix, 100).
prefix_match(#db{} = Db, Table, Prefix, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
prefix_match(Db, Table, Prefix, false, Limit).
prefix_match_rel(#db{} = Db, Table, Prefix, StartPoint, Limit) ->
prefix_match(Db, Table, Prefix, {true, StartPoint}, Limit).
prefix_match(#db{} = Db, Table, Prefix, Rel, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
case type(Db, Table) of
set ->
prefix_match_set(Db, Table, Prefix, Rel, Limit);
_ ->
error(badarg)
end.
prefix_match_set(#db{ref = Ref} = Db, Table, Prefix, Rel, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
Enc = encoding(Db, Table),
EncPrefix = kvdb_lib:enc_prefix(key, Prefix, Enc),
EncStart = case Rel of
false ->
EncPrefix;
{true, StartPoint} ->
enc(key, StartPoint, Enc)
end,
TablePrefix = make_table_key(Table),
TabPfxSz = byte_size(TablePrefix),
MatchKey = make_table_key(Table, EncPrefix),
StartKey = make_table_key(Table, EncStart),
with_iterator(
Ref,
fun(I) ->
if Rel==false, EncStart == <<>> ->
case eleveldb:iterator_move(I, TablePrefix) of
{ok, <<TablePrefix:TabPfxSz/binary>>, _} ->
prefix_match_(I, next, TablePrefix, Db, Table,
MatchKey, TablePrefix, Prefix,
Enc, Limit, Limit, []);
_ ->
done
end;
Rel=/=false ->
case eleveldb:iterator_move(I, StartKey) of
{ok, StartKey, _} ->
prefix_match_(I, next, StartKey, Db, Table,
MatchKey, TablePrefix, Prefix, Enc,
Limit, Limit, []);
{ok, _, _} ->
prefix_match_(I, StartKey, StartKey, Db, Table,
MatchKey, TablePrefix, Prefix, Enc,
Limit, Limit, [])
end;
true ->
prefix_match_(I, StartKey, StartKey, Db, Table, MatchKey,
TablePrefix, Prefix, Enc, Limit, Limit, [])
end
end).
prefix_match_(_I, _Next, Prev, #db{ref = Ref} = Db, Table, MatchKey, TPfx, Pfx,
Enc, 0, Limit0, Acc) ->
{lists:reverse(Acc),
fun() ->
with_iterator(
Ref,
fun(I1) ->
case eleveldb:iterator_move(I1, Prev) of
{ok, _, _} ->
prefix_match_(
I1, next, Prev, Db, Table, MatchKey, TPfx,
Pfx, Enc, Limit0, Limit0, []);
_ ->
done
end
end)
end};
prefix_match_(I, Next, _Prev, Db, Table, MatchKey, TPfx, Pfx, Enc,
Limit, Limit0, Acc) ->
Sz = byte_size(MatchKey),
case eleveldb:iterator_move(I, Next) of
{ok, <<MatchKey:Sz/binary, _/binary>> = Key, Val} ->
PSz = byte_size(TPfx),
<<TPfx:PSz/binary, K/binary>> = Key,
case (K =/= <<>> andalso kvdb_lib:is_prefix(Pfx, K, Enc)) of
true ->
prefix_match_(I, next, Key, Db, Table, MatchKey, TPfx, Pfx,
Enc, decr(Limit), Limit0,
[decode_obj(Db, Enc, Table, K, Val) | Acc]);
false ->
{lists:reverse(Acc), fun() -> done end}
end;
_ ->
%% prefix doesn't match, or end of database
{lists:reverse(Acc), fun() ->
done
end}
end.
decr(infinity) -> infinity;
decr(I) when is_integer(I) -> I-1.
first(#db{} = Db, Table) ->
first(Db, encoding(Db, Table), Table).
first(#db{ref = Ref} = Db, Enc, Table) ->
TableKey = make_table_key(Table),
with_iterator(
Ref,
fun(I) ->
case prefix_move(I, TableKey, TableKey) of
{ok, <<>>, _} ->
case prefix_move(I, TableKey, next) of
{ok, K, V} ->
{ok, decode_obj(Db, Enc, Table, K, V)};
done ->
done
end;
_ ->
done
end
end).
prefix_move(I, Prefix, Dir) ->
Sz = byte_size(Prefix),
case eleveldb:iterator_move(I, Dir) of
{ok, <<Prefix:Sz/binary, K/binary>>, Value} ->
{ok, K, Value};
_ ->
done
end.
last(#db{} = Db, Table) ->
last(Db, encoding(Db, Table), Table).
last(#db{ref = Ref} = Db, Enc, Table) ->
FirstKey = make_table_key(Table),
FirstSize = byte_size(FirstKey),
LastKey = make_table_last_key(Table), % isn't actually stored in the database
with_iterator(
Ref,
fun(I) ->
case eleveldb:iterator_move(I, LastKey) of
{ok,_AfterKey,_} ->
case eleveldb:iterator_move(I, prev) of
{ok, FirstKey, _} ->
% table is empty
done;
{ok, << FirstKey:FirstSize/binary, K/binary>>, Value} ->
{ok, decode_obj(Db, Enc, Table, K, Value)};
_ ->
done
end;
{error,invalid_iterator} ->
%% the last object of this table is likely the very last in the db
case eleveldb:iterator_move(I, last) of
{ok, FirstKey, _} ->
%% table is empty
done;
{ok, << FirstKey:FirstSize/binary, K/binary >>, Value} ->
{ok, decode_obj(Db, Enc, Table, K, Value)}
end;
_ ->
done
end
end).
next(#db{} = Db, Table, Rel) ->
next(Db, encoding(Db, Table), Table, Rel).
next(Db, Enc, Table, Rel) ->
iterator_move(Db, Enc, Table, Rel, fun(A,B) -> A > B end, next).
prev(#db{} = Db, Table, Rel) ->
prev(Db, encoding(Db, Table), Table, Rel).
prev(Db, Enc, Table, Rel) ->
try iterator_move(Db, Enc, Table, Rel, fun(A,B) -> A < B end, prev) of
{ok, {<<>>, _}} ->
done;
Other ->
Other
catch
error:Err ->
io:fwrite("CRASH: ~p, ~p~n", [Err, erlang:get_stacktrace()]),
erlang:error(Err)
end.
iterator_move(#db{ref = Ref} = Db, Enc, Table, Rel, Comp, Dir) ->
TableKey = make_table_key(Table),
KeySize = byte_size(TableKey),
EncRel = enc(key, Rel, Enc),
RelKey = make_table_key(Table, EncRel),
with_iterator(
Ref,
fun(I) ->
iterator_move_(I, Db, Table, Enc, TableKey, KeySize,
EncRel, RelKey, Comp, Dir)
end).
iterator_move_(I, Db, Table, Enc, TableKey, KeySize, EncRel,
RelKey, Comp, Dir) ->
case eleveldb:iterator_move(I, RelKey) of
{ok, <<TableKey:KeySize/binary, Key/binary>>, Value} ->
case Key =/= <<>> andalso Comp(Key, EncRel) of
true ->
{ok, decode_obj(Db, Enc, Table, Key, Value)};
false ->
case eleveldb:iterator_move(I, Dir) of
{ok, <<TableKey:KeySize/binary,
Key2/binary>>, Value2} ->
case Key2 of
<<>> -> done;
_ ->
{ok, decode_obj(Db, Enc, Table,
Key2, Value2)}
end;
_ ->
done
end
end;
{ok, OtherKey, _} when Dir == prev ->
if byte_size(OtherKey) >= KeySize ->
<<OtherTabPat:KeySize/binary, _/binary>> = OtherKey,
if OtherTabPat > TableKey ->
%% try stepping back
iterator_move_(I, Db, Table, Enc, TableKey,
KeySize, EncRel, prev, Comp, Dir);
true ->
done
end;
true ->
done
end;
_ ->
done
end.
%% create key
make_table_last_key(Table) ->
make_key(Table, $;, <<>>).
make_table_key(Table) ->
make_key(Table, $:, <<>>).
make_table_key(Table, Key) ->
make_key(Table, $:, Key).
make_key(Table, Sep, Key) when is_binary(Table) ->
<<Table/binary,Sep,Key/binary>>.
encode_obj ( { _ , _ , _ } = Enc , { Key , , Value } ) - >
{ enc(key , Key , Enc ) , , enc(value , Value , Enc ) } ;
%% encode_obj(Enc, {Key, Value}) ->
{ enc(key , Key , Enc ) , none , enc(value , Value , Enc ) } .
encode_queue_obj(Enc, Type, Obj) ->
encode_queue_obj(Enc, Type, Obj, active).
encode_queue_obj({_,_,_} = Enc, Type, {#q_key{} = Key, Attrs, Value}, Status) ->
St = enc_queue_obj_status(Status),
AKey = kvdb_lib:q_key_to_actual(Key, Enc, Type),
{AKey, Attrs, <<St:8, (enc(value, Value, Enc))/binary>>};
encode_queue_obj(Enc, Type, {#q_key{} = Key, Value}, Status) ->
St = enc_queue_obj_status(Status),
AKey = kvdb_lib:q_key_to_actual(Key, Enc, Type),
{AKey, none, <<St:8, (enc(value, Value, Enc))/binary>>}.
enc_queue_obj_status(blocking) -> $*;
enc_queue_obj_status(active ) -> $+;
enc_queue_obj_status(inactive) -> $-.
dec_queue_obj_status($*) -> blocking;
dec_queue_obj_status($+) -> active;
dec_queue_obj_status($-) -> inactive.
decode_obj(Db, Enc, Table, K, V) ->
Key = dec(key, K, Enc),
decode_obj_v(Db, Enc, Table, K, Key, V).
decode_obj_v(Db, Enc, Table, EncKey, Key, V) ->
Value = dec(value, V, Enc),
case Enc of
{_, _, _} ->
Attrs = get_attrs_(Db, Table, EncKey, all),
{Key, Attrs, Value};
_ ->
{Key, Value}
end.
with_iterator(Db, F) ->
{ok, I} = eleveldb:iterator(Db, []),
try F(I)
after
eleveldb:iterator_close(I)
end.
type(Db, Table) ->
schema_lookup(Db, {a, Table, type}, set).
encoding(#db{encoding = Enc} = Db, Table) ->
schema_lookup(Db, {a, Table, encoding}, Enc).
index(#db{} = Db, Table) ->
schema_lookup(Db, {a, Table, index}, []).
schema(#db{} = Db, Table) ->
schema_lookup(Db, {a, Table, schema}, []).
ensure_schema(#db{ref = Ref} = Db, Opts) ->
ETS = ets:new(kvdb_schema, [ordered_set, public]),
Db1 = Db#db{metadata = ETS},
case eleveldb:get(Ref, make_table_key(?META_TABLE, <<>>), []) of
{ok, _} ->
[ets:insert(ETS, X) || X <- whole_table(Db1, sext, ?META_TABLE)],
Db1;
_ ->
ok = do_add_table(Db1, ?META_TABLE),
Tab = #table{name = ?META_TABLE, encoding = sext,
columns = [key,value]},
schema_write(Db1, {{table, ?META_TABLE}, Tab}),
schema_write(Db1, {{a, ?META_TABLE, encoding}, sext}),
schema_write(Db1, {{a, ?META_TABLE, type}, set}),
schema_write(Db1, {schema_mod, proplists:get_value(schema, Opts, kvdb_schema)}),
Db1
end.
whole_table(Db, Enc, Table) ->
whole_table(first(Db, Enc, Table), Db, Enc, Table).
whole_table({ok, {K, V}}, Db, Enc, Table) ->
[{K,V} | whole_table(next(Db, Enc, Table, K), Db, Enc, Table)];
whole_table(done, _Db, _Enc, _Table) ->
[].
schema_write(#db{} = Db, tabrec, Table, #table{} = TabRec) ->
schema_write(Db, {{table, Table}, TabRec});
schema_write(#db{} = Db, property, {Table, Key}, Value) ->
schema_write(Db, {{a, Table, Key}, Value});
schema_write(#db{} = Db, global, Key, Value) ->
schema_write(Db, {Key, Value}).
schema_read(#db{} = Db, tabrec, Table) ->
schema_lookup(Db, {table, Table}, undefined);
schema_read(#db{} = Db, property, {Table, Key}) ->
schema_lookup(Db, {a, Table, Key}, undefined);
schema_read(#db{} = Db, global, Key) ->
schema_lookup(Db, Key, undefined).
schema_delete(#db{} = Db, tabrec, Table) ->
schema_delete(Db, {table, Table});
schema_delete(#db{} = Db, property, {Table, Key}) ->
schema_delete(Db, {a, Table, Key});
schema_delete(#db{} = Db, global, Key) ->
schema_delete(Db, Key).
schema_fold(#db{} = Db, F, A) ->
fold(Db, F, A, sext, ?META_TABLE).
schema_write(#db{metadata = ETS} = Db, Item) ->
ets:insert(ETS, Item),
put(Db, ?META_TABLE, Item).
schema_lookup(_, {a, ?META_TABLE, Attr}, Default) ->
case Attr of
type -> set;
encoding -> sext;
_ -> Default
end;
schema_lookup(#db{metadata = ETS}, Key, Default) ->
case ets:lookup(ETS, Key) of
[{_, Value}] ->
Value;
[] ->
Default
end.
schema_delete(#db{metadata = ETS} = Db, Key) ->
ets:delete(ETS, Key),
delete(Db, ?META_TABLE, Key).
fold(Db, F, A, Enc, Table) ->
fold(first(Db, Enc, Table), F, A, Db, Enc, Table).
fold({ok, {K, V}}, F, A, Db, Enc, Table) ->
{Type, Key} = schema_key_type(K),
fold(next(Db, Enc, Table, K), F, F(Type, {Key, V}, A), Db, Enc, Table);
fold(done, _F, A, _Db, _Enc, _Table) ->
A.
schema_key_type({a,T,K}) ->
{property, {T, K}};
schema_key_type({table, T}) ->
{tabrec, T};
schema_key_type(Other) ->
{global, Other}.
| null | https://raw.githubusercontent.com/Feuerlabs/kvdb/c8c71bf5422a8fa2e58c608c65629be7a58e27f3/src/kvdb_leveldb.erl | erlang | ---- BEGIN COPYRIGHT -------------------------------------------------------
---- END COPYRIGHT ---------------------------------------------------------
@hidden
@doc
@end
{OKey, Rest} = sext:decode_next(AKey),
Attr = sext:decode(Rest),
This is the hard part
the sext-encoded attribute name starts. We know what the start
codes of a sext-encoded term can be. Try each, in order.
make_string(A) when is_atom(A) ->
atom_to_list(A);
make_string(S) when is_list(S) ->
try binary_to_list(iolist_to_binary([S]))
catch
error:_ ->
lists:flatten(io_lib:fwrite("~w",[S]))
end;
make_string(B) when is_binary(B) ->
make_string(X) ->
lists:flatten(io_lib:fwrite("~w", [X])).
leveldb is garbage collected
Frequently used case, therefore optimized. No indexing on {K,V} tuples
This should really be cleaned up, but for now, when put_(...) is called
from push(...), the key and value parts are already coded as binary.
Put = {put, make_table_key(Table, Key), Value},
ok ->
{ok, QKey};
Other ->
Other
end;
Val = enc(value, Data, Enc),
encode_queue_head_key(Table, Queue, Type, Enc) ->
make_table_key(Table, Key).
Obj1 = fix_q_obj(Obj, Enc, Type),
blocking
includes 'infinity'
EncKey = enc(key, Actual, Enc),
used during indexing (only if index function requires the value)
still needed?
prefix doesn't match, or end of database
isn't actually stored in the database
table is empty
the last object of this table is likely the very last in the db
table is empty
try stepping back
create key
encode_obj(Enc, {Key, Value}) -> | Copyright ( C ) 2012 Feuerlabs , Inc. All rights reserved .
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
@author
@author < >
to
-module(kvdb_leveldb).
-behaviour(kvdb).
-export([open/2, close/1]).
-export([add_table/3, delete_table/2, list_tables/1]).
-export([put/3, push/4, get/3, get_attrs/4, index_get/4, index_keys/4,
update_counter/4, pop/3, prel_pop/3, extract/3, delete/3,
list_queue/3, list_queue/6, list_queue/7, is_queue_empty/3,
queue_read/3, queue_insert/5, queue_delete/3, mark_queue_object/4,
queue_head_write/4, queue_head_read/3, queue_head_delete/3]).
-export([first_queue/2, next_queue/3]).
-export([first/2, last/2, next/3, prev/3,
prefix_match/3, prefix_match/4, prefix_match_rel/5]).
-export([get_schema_mod/2]).
-export([schema_write/4, schema_read/3, schema_delete/3, schema_fold/3]).
-export([info/2, is_table/2]).
-export([dump_tables/1]).
-import(kvdb_lib, [dec/3, enc/3]).
-include("kvdb.hrl").
-define(if_table(Db, Tab, Expr), if_table(Db, Tab, fun() -> Expr end)).
info(#db{} = Db, What) ->
case What of
tables -> list_tables(Db);
encoding -> Db#db.encoding;
ref -> Db#db.ref;
{Tab,encoding} -> ?if_table(Db, Tab, encoding(Db, Tab));
{Tab,index } -> ?if_table(Db, Tab, index(Db, Tab));
{Tab,type } -> ?if_table(Db, Tab, type(Db, Tab));
{Tab,schema } -> ?if_table(Db, Tab, schema(Db, Tab));
{Tab,tabrec } -> schema_lookup(Db, {table, Tab}, undefined);
_ -> undefined
end.
is_table(#db{metadata = ETS}, Tab) ->
ets:member(ETS, {table, Tab}).
if_table(Db, Tab, F) ->
case is_table(Db, Tab) of
true -> F();
false -> undefined
end.
dump_tables(#db{ref = Ref} = Db) ->
with_iterator(
Ref,
fun(I) ->
dump_tables_(eleveldb:iterator_move(I, first), I, Db)
end).
dump_tables_({ok, K, V}, I, Db) ->
Type = bin_match([{$:, obj}, {$=, attr}, {$?, index}], K),
io:fwrite("Type = ~p: K=~p; V=~p~n", [Type, K, V]),
Obj = case Type of
obj ->
[T, Key] = binary:split(K, <<":">>),
case Key of
<<>> ->
{tab_obj, T, kvdb_lib:try_decode(V)};
_ ->
Enc = encoding(Db, T),
case type(Db, T) of
set ->
{obj, T, kvdb_lib:try_decode(Key),
kvdb_lib:try_decode(V)};
TType when TType == fifo; TType == lifo;
element(2, TType) == fifo;
element(2, TType) == lifo ->
io : fwrite("split_queue_key(~p , ~p , ~p)~n " ,
[ Enc , TType , Key ] ) ,
#q_key{queue = Q,
key = Ko} = kvdb_lib:split_queue_key(
Enc, TType, Key),
<<F:8, Val/binary>> = V,
St = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
Kr = dec(key, Key, Enc),
{q_obj, T, Q, Kr,
{Ko, kvdb_lib:try_decode(Val)}, St}
end
end;
attr ->
[T, AKey] = binary:split(K, <<"=">>),
io : fwrite("attr : T=~p ; AKey=~p ~ n " , [ T , AKey ] ) ,
{OKey, Attr} = decode_attr_key(Db, T, AKey),
{attr, T, OKey, Attr, binary_to_term(V)};
index ->
[T, IKey] = binary:split(K, <<"?">>),
{Ix, Rest} = sext:decode_next(IKey),
io : fwrite("index : T=~p ; Ix = ~p ; Rest = ~p ~ n " , [ T , Ix , Rest ] ) ,
{index, T, Ix, sext:decode(Rest), V};
unknown ->
{unknown, K, V}
end,
[Obj | dump_tables_(eleveldb:iterator_move(I, next), I, Db)];
dump_tables_({error, _}, _, _) ->
[];
dump_tables_(Other, _, _) ->
io:fwrite("dump_tables_(~p, _, _)~n", [Other]).
< < Key / binary , ( sext : encode(AttrName))/binary > >
decode_attr_key(Db, Tab, K) ->
case key_encoding(Db, Tab) of
sext ->
[Kdec, Rest] = sext:decode_next(K),
{Kdec, sext:decode(Rest)};
raw ->
since the first part is an arbitrary binary , we must guess where
{match, Ps} =
re:run(K,<<"[",8,9,10,11,12,13,14,15,16,17,18,19,"]">>,
[global]),
{P, AName} = try_sext_decode(lists:flatten(Ps), K),
<<Key:P/binary, _/binary>> = K,
{Key, AName}
end.
key_encoding(Db, T) ->
case encoding(Db, T) of
E when is_atom(E) -> E;
E when is_tuple(E) -> element(1, E)
end.
try_sext_decode([{P,_}|Ps], K) ->
<<_:P/binary, Rest/binary>> = K,
try A = sext:decode(Rest),
{P, A}
catch
error:_ ->
try_sext_decode(Ps, K)
end.
bin_match(Ts, B) ->
Cs = << << "\\", C:8 >> || {C,_} <- Ts >>,
Pat = << "[", Cs/binary, "]" >>,
case re:run(B, Pat, [{capture, first, list}]) of
{match, [[C]]} ->
{_,T} = lists:keyfind(C,1,Ts),
T;
_ ->
unknown
end.
get_schema_mod(Db, Default) ->
case schema_lookup(Db, schema_mod, undefined) of
undefined ->
schema_write(Db, {schema_mod, Default}),
Default;
M ->
M
end.
open(DbName, Options) ->
E = proplists:get_value(encoding, Options, sext),
kvdb_lib:check_valid_encoding(E),
DbOpts = proplists:get_value(db_opts, Options, [{create_if_missing,true}]),
Res = case proplists:get_value(file, Options) of
undefined ->
File = kvdb_lib:db_file(DbName),
eleveldb:open(File, DbOpts);
Name ->
filelib:ensure_dir(Name),
eleveldb:open(Name, DbOpts)
end,
case Res of
{ok, Ref} ->
{ok, ensure_schema(#db{ref = Ref, encoding = E}, Options)};
Error ->
Error
end.
) ;
close(_Db) ->
ok.
add_table(#db{encoding = Enc} = Db, Table, Opts) when is_list(Opts) ->
TabR = kvdb_lib:make_tabrec(Table, Opts, #table{encoding = Enc}),
add_table(Db, Table, TabR);
add_table(Db, Table, #table{} = TabR) ->
add_table(Db, Table, TabR, []).
add_table(Db, Table, #table{encoding = Enc, type = Type, index = Ix} = TabR, Opts) ->
case schema_lookup(Db, {table, Table}, undefined) of
T when T =/= undefined ->
ok;
undefined ->
case do_add_table(Db, Table) of
ok ->
schema_write(Db, {{table, Table}, TabR}),
[schema_write(Db, property, {Table, K}, V)
|| {K, V} <- [{encoding, Enc}, {type, Type}, {index, Ix} | Opts]],
ok;
Error ->
Error
end
end.
do_add_table(#db{ref = Db}, Table) ->
T = make_table_key(Table, <<>>),
eleveldb:put(Db, T, <<>>, []).
list_tables(#db{metadata = ETS}) ->
ets:select(ETS, [{ {{table, '$1'}, '_'},
[{'=/=','$1',?META_TABLE}], ['$1'] }]).
delete_table(#db{ref = Ref} = Db, Table) ->
case schema_lookup(Db, {table, Table}, undefined) of
undefined ->
ok;
#table{} ->
Kt = make_table_key(Table, <<>>),
Ka = make_key(Table, $=, <<>>),
Ki = make_key(Table, $?, <<>>),
with_iterator(
Ref,
fun(I) ->
delete_table_(eleveldb:iterator_move(I, Kt),
I, Kt,Ka,Ki, byte_size(Kt), Ref)
end),
schema_delete(Db, {table, Table}),
schema_delete(Db, {Table, encoding}),
ok
end.
delete_table_({ok, K, _V}, I, Kt,Ka,Ki, Sz, Ref) ->
case K of
<<X:Sz/binary, _/binary>> when X==Kt; X==Ka; X==Ki ->
eleveldb:delete(Ref, K, []),
delete_table_(eleveldb:iterator_move(I, next), I, Kt,Ka,Ki, Sz, Ref);
_ ->
ok
end;
delete_table_({error,invalid_iterator}, _, _, _, _, _, _) ->
ok.
put(Db, Table, Obj) ->
lager:debug("put: Db = ~p, Table = ~p, Obj = ~p ~n", [Db, Table, Obj]),
case type(Db, Table) of
set ->
put_(Db, Table, Obj, put);
_ ->
{error, illegal}
end.
put_(Db, Table, {K,V}, Op) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = encode_elem(key, K, Type, Enc, Op),
Val = encode_elem(value, V, Type, Enc, Op),
put_raw(Db, Table, K, Key, none, V, Val, put);
put_(Db, Table, {K, Attrs, V}, Op) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = encode_elem(key, K, Type, Enc, Op),
Val = encode_elem(value, V, Type, Enc, Op),
put_raw(Db, Table, K, Key, Attrs, V, Val, put).
put_raw(#db{ref = Ref}, Table, _, Key, none, _, Val, _) ->
eleveldb:put(Ref, make_table_key(Table, Key), Val, []);
put_raw(#db{ref = Ref} = Db, Table, K, Key, Attrs, V, Val, Op) ->
OldAttrs = get_attrs_(Db, Table, Key, all),
Ix = index(Db, Table),
IxOps = case Ix of
[_|_] ->
OldIxVals = kvdb_lib:index_vals(
Ix, K, OldAttrs,
fun() ->
get_value(Db, Table, K)
end),
NewIxVals = kvdb_lib:index_vals(Ix, K, Attrs,
fun() -> V end),
[{delete, ix_key(Table, I, K)} ||
I <- OldIxVals -- NewIxVals]
++ [{put, ix_key(Table, I, K), <<>>} ||
I <- NewIxVals -- OldIxVals];
_ ->
[]
end,
DelAttrs = if element(2,Op) =/= push ->
attrs_to_delete(
Table, Key,
[{A,Va} ||
{A,Va} <- OldAttrs,
not lists:keymember(A, 1, Attrs)]);
true -> []
end,
PutAttrs = attrs_to_put(Table, Key, Attrs),
case eleveldb:write(Ref, [{put, make_table_key(Table, Key), Val}|
DelAttrs ++ PutAttrs ++ IxOps], []) of
ok ->
ok;
Other ->
Other
end.
encode_elem(_Elem, V, _T, _Enc, {queue,_}) when is_binary(V) ->
V;
encode_elem(Elem, V, _, Enc, _) ->
enc(Elem, V, Enc).
ix_key(Table, I, K) ->
make_key(Table, $?, <<(sext:encode(I))/binary, (sext:encode(K))/binary>>).
update_counter(#db{ref = Ref} = Db, Table, K, Incr) when is_integer(Incr) ->
case type(Db, Table) of
set ->
Enc = encoding(Db, Table),
Key = enc(key, K, Enc),
case eleveldb:get(Ref, TabKey = make_table_key(Table, Key),
[{fill_cache, true}]) of
{ok, V} ->
NewV =
case dec(value, V, Enc) of
I when is_integer(I) ->
NewI = I + Incr,
enc(value, NewI, Enc);
B when is_binary(B) ->
Sz = bit_size(B),
<<I:Sz/integer>> = B,
NewI = I + Incr,
enc(value, <<NewI:Sz/integer>>, Enc);
_ ->
erlang:error(illegal)
end,
ok = eleveldb:put(Ref, TabKey, NewV, []),
dec(value, NewV, Enc);
_ ->
erlang:error(not_found)
end;
_ ->
erlang:error(illegal)
end.
push(#db{} = Db, Table, Q, Obj) ->
Type = type(Db, Table),
if Type == fifo; Type == lifo; element(1,Type) == keyed ->
Enc = encoding(Db, Table),
{_ActualKey, QKey} =
kvdb_lib:actual_key(Enc, Type, Q, element(1, Obj)),
{Key, Attrs, Value} = encode_queue_obj(
Enc, Type, setelement(1, Obj, QKey)),
case put_raw(Db, Table, QKey, Key, Attrs,
obj_val(Obj), Value, {queue,push}) of
ok ->
{ok, QKey};
Other ->
Other
end;
PutAttrs = attrs_to_put(Table , Key , ) ,
case : write(Ref , [ Put|PutAttrs ] , [ ] ) of
true ->
erlang:error(illegal)
end.
queue_insert(#db{} = Db, Table, #q_key{} = QKey, St, Obj) when
St==blocking; St==active; St==inactive ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = : q_key_to_actual(QKey , Enc , Type ) ,
Obj1 = setelement(1, Obj, QKey),
put_(Db , Table , Obj1 , put ) .
{EncKey, Attrs, Value} = encode_queue_obj(Enc, Type, Obj1, St),
put_raw(Db, Table, QKey, EncKey, Attrs, obj_val(Obj1), Value,
{queue,put}).
obj_val({_,V} ) -> V;
obj_val({_,_,V}) -> V.
queue_head_write(#db{} = Db, Table, Queue, Obj) ->
Type = type(Db, Table),
HeadKey = kvdb_lib:q_head_key(Queue, Type),
queue_insert(Db, Table, HeadKey, active, Obj).
Key = enc(key , : q_key_to_actual(HeadKey , Enc , Type ) , Enc ) ,
eleveldb : put(Ref , make_table_key(Table , Key ) , , [ ] ) .
queue_head_read(#db{ref = Ref} = Db, Table, Queue) ->
Type = type(Db, Table),
Enc = encoding(Db, Table),
HeadKey = kvdb_lib:q_head_key(Queue, Type),
Key = kvdb_lib:q_key_to_actual(HeadKey, Enc, Type),
QHeadKey = make_table_key(Table, Key),
case eleveldb:get(Ref, QHeadKey, []) of
{ok, <<_:8, V/binary>>} ->
{ok, decode_obj_v(Db, Enc, Table, Key, HeadKey#q_key.key, V)};
{ ok , : dec(value , V , Enc ) } ;
not_found ->
{error, not_found}
end.
queue_head_delete(#db{} = _Db, _Table, _Queue) ->
exit(nyi).
queue_delete(Db, Table, #q_key{} = QKey) ->
_ = extract(Db, Table, QKey),
ok.
queue_delete_obj(#db{ref = Ref}, Table, EncKey, Obj) ->
Key = make_table_key(Table, EncKey),
Attrs = case Obj of
{_, As, _} -> As;
{_, _} -> []
end,
eleveldb:write(Ref, [{delete, Key}
| attrs_to_delete(Table, EncKey, Attrs)], []),
ok.
HeadKey = : q_head_key(Queue , Type ) ,
Key = : q_key_to_actual(HeadKey , Enc , Type ) ,
mark_queue_object(#db{} = Db, Table, #q_key{queue = Q} = QK, St) when
St==blocking; St==active; St==inactive ->
case queue_read(Db, Table, QK) of
{ok, _OldSt, Obj} ->
mark_queue_obj(Db, Table, encoding(Db,Table), QK, Obj, St),
{ok, Q, Obj};
{error,_} = E ->
E
end.
mark_queue_obj(#db{ref = Ref} = Db, Table, Enc, QK, Obj, St) when
St==blocking; St==active; St==inactive ->
Type = type(Db, Table),
AKey = : q_key_to_actual(QK , Enc , Type ) ,
{Key, _Attrs, Value} =
encode_queue_obj(Enc, Type, setelement(1,Obj,QK), St),
eleveldb:put(Ref, make_table_key(Table, Key), Value, []).
pop(#db{} = Db, Table, Q) ->
case type(Db, Table) of
set -> erlang:error(illegal);
T ->
Remove = fun(EncKey, _QKey, Obj, _) ->
queue_delete_obj(Db, Table, EncKey, Obj)
end,
do_pop(Db, Table, T, Q, Remove, false)
end.
prel_pop(Db, Table, Q) ->
case type(Db, Table) of
set -> erlang:error(illegal);
T ->
Remove = fun(_, QKey, Obj, Enc) ->
mark_queue_obj(Db, Table, Enc, QKey, Obj, blocking)
end,
do_pop(Db, Table, T, Q, Remove, true)
end.
do_pop(Db, Table, _Type, Q, Remove, ReturnKey) ->
Enc = encoding(Db, Table),
case list_queue_int(Db, Table, Q, fun(_RawKey, inactive, _, _) ->
skip;
(RawKey, _St,K,O) ->
{keep, {RawKey,K,O}}
end, _HeedBlock = true, 2, false) of
{[{Raw,QKey,Obj}|More], _} ->
Empty = More == [],
Remove(Raw, QKey, Obj, Enc),
if ReturnKey ->
{ok, Obj, QKey, Empty};
true ->
{ok, Obj, Empty}
end;
Stop when Stop == done; Stop == blocked ->
Stop
end.
extract(#db{ref = Ref} = Db, Table, #q_key{queue = Q, key = Key} = QKey) ->
case type(Db, Table) of
set -> erlang:error(illegal);
Type ->
Enc = encoding(Db, Table),
AKey = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
RawKey = make_table_key(Table, AKey),
case eleveldb:get(Ref, RawKey, []) of
{ok, <<St:8, V/binary>>} when St==$*; St==$-; St==$+ ->
Obj = decode_obj_v(Db, Enc, Table, AKey, Key, V),
eleveldb:delete(Ref, RawKey, []),
IsEmpty =
case list_queue(Db, Table, Q,
fun(_,_,O) ->
{keep,O}
end,
_HeedBlock=true, 1) of
{[_], _} -> false;
_ -> true
end,
{ok, setelement(1, Obj, Key), Q, IsEmpty};
not_found ->
{error, not_found};
{error,_} = Err ->
Err
end
end.
is_queue_empty(#db{ref = Ref} = Db, Table, Q) ->
Enc = encoding(Db, Table),
QPfx = kvdb_lib:queue_prefix(Enc, Q, first),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
case eleveldb:iterator_move(I, Prefix) of
{ok, <<QPrefix:Sz/binary, _/binary>>,
<<"*", _/binary>>} ->
false;
{ok, <<QPrefix:Sz/binary, _/binary>> = K, _} ->
<<TPrefix:TPSz/binary, Key/binary>> = K,
case Key of
<<>> -> true;
_ ->
false
end;
_ ->
true
end
end).
first_queue(#db{ref = Ref} = Db, Table) ->
Type = type(Db, Table),
case Type of
set -> erlang:error(illegal);
_ ->
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
first_queue_(
eleveldb:iterator_move(I, TPrefix), I, Db, Table,
TPrefix, TPSz)
end)
end.
first_queue_(Res, I, Db, Table, TPrefix, TPSz) ->
case Res of
{ok, <<TPrefix:TPSz/binary>>, _} ->
first_queue_(eleveldb:iterator_move(I, next), I, Db,
Table, TPrefix, TPSz);
{ok, <<TPrefix:TPSz/binary, K/binary>>, _} ->
Enc = encoding(Db, Table),
#q_key{queue = Q} =
kvdb_lib:split_queue_key(Enc, dec(key, K, Enc)),
{ok, Q};
_ ->
done
end.
next_queue(#db{ref = Ref} = Db, Table, Q) ->
Type = type(Db, Table),
case Type of
set -> erlang:error(illegal);
_ ->
Enc = encoding(Db, Table),
QPfx = kvdb_lib:queue_prefix(Enc, Q, last),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
with_iterator(
Ref,
fun(I) ->
next_queue_(eleveldb:iterator_move(I, Prefix), I,
Db, Table, QPrefix, Sz,
TPrefix, TPSz, Enc)
end)
end.
next_queue_(Res, I, Db, Table, QPrefix, Sz, TPrefix, TPSz, Enc) ->
case Res of
{ok, <<QPrefix:Sz/binary, _/binary>>, _} ->
next_queue_(eleveldb:iterator_move(I, next), I, Db, Table,
QPrefix, Sz, TPrefix, TPSz, Enc);
{ok, <<TPrefix:TPSz/binary, K/binary>>, _} ->
case kvdb_lib:split_queue_key(Enc, dec(key,K,Enc)) of
#q_key{key = ?Q_HEAD_KEY} ->
next_queue_(eleveldb:iterator_move(I, next), I, Db, Table,
QPrefix, Sz, TPrefix, TPSz, Enc);
#q_key{queue = Q} ->
{ok, Q}
end;
_ ->
done
end.
q_first_(I, Db, Table, Q, Head, Enc, HeedBlock) ->
QPfx = kvdb_lib:queue_prefix(Enc, Q, first),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
q_first_move(eleveldb:iterator_move(I, Prefix),
I, Db, Table, Enc, QPrefix, Sz, TPrefix, Head,
TPSz, HeedBlock).
q_first_move(Res, I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock) ->
case Res of
{ok, Head, _} ->
q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>>, <<"-", _/binary>>} ->
q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>> = K, <<F:8, V/binary>>} ->
if F == $*, HeedBlock ->
blocked;
true ->
<<TPrefix:TPSz/binary, Key/binary>> = K,
case Key of
<<>> -> q_first_move(eleveldb:iterator_move(I, next),
I, Db, Table, Enc, QPrefix, Sz,
TPrefix, Head, TPSz, HeedBlock);
_ ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
{Key, Status, decode_obj(Db, Enc, Table, Key, V)}
end
end;
_ ->
done
end.
q_last(#db{ref = Ref } = Db , Table , Q , Enc ) - >
with_iterator(Ref , fun(I ) - > q_last_(I , Db , Table , Q , Enc ) end ) .
q_last_(I, Db, Table, Q, Head, Enc, HeedBlock) ->
QPfx = kvdb_lib:queue_prefix(Enc, Q, last),
Prefix = make_table_key(Table, kvdb_lib:enc(key, QPfx, Enc)),
QPrefix = table_queue_prefix(Table, Q, Enc),
Sz = byte_size(QPrefix),
TPrefix = make_table_key(Table),
TPSz = byte_size(TPrefix),
case eleveldb:iterator_move(I, Prefix) of
{ok, _K, _V} ->
q_last_move_(eleveldb:iterator_move(I, prev), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock);
{error, invalid_iterator} ->
q_last_move_(eleveldb:iterator_move(I, last), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock)
end.
q_last_move_(Res, I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock) ->
case Res of
{ok, Head, _} ->
q_last_move_(eleveldb:iterator_move(I, prev), I, Db, Table, Enc,
QPrefix, Sz, TPrefix, Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>>, <<"-", _/binary>>} ->
q_last_move_(eleveldb:iterator_move(I, prev),
I, Db, Table, Enc, QPrefix, Sz, TPrefix,
Head, TPSz, HeedBlock);
{ok, <<QPrefix:Sz/binary, _/binary>> = K1, <<F:8, V1/binary>>} ->
if F == $*, HeedBlock ->
blocked;
true ->
<<TPrefix:TPSz/binary, Key/binary>> = K1,
case Key of
<<>> -> done;
_ ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
{Key, Status, decode_obj(Db, Enc, Table, Key, V1)}
end
end;
_Other ->
done
end.
list_queue(Db, Table, Q) ->
list_queue(Db, Table, Q, fun(_,_,O) -> {keep,O} end, false, infinity).
list_queue(Db, Table, Q, Filter, HeedBlock, Limit) ->
list_queue(Db, Table, Q, Filter, HeedBlock, Limit, false).
list_queue(#db{} = Db, Table, Q, Filter, HeedBlock, Limit, Reverse)
list_queue_int(Db, Table, Q, fun(_RawKey,St,K,O) -> Filter(St,K,O) end,
HeedBlock, Limit, Reverse).
list_queue_int(#db{ref = Ref} = Db, Table, Q, Filter,
HeedBlock, Limit, Reverse) when Limit > 0, is_boolean(Reverse) ->
Type = type(Db, Table),
Enc = encoding(Db, Table),
Head = make_table_key(
Table, kvdb_lib:q_key_to_actual(
kvdb_lib:q_head_key(Q, Type), Enc, Type)),
QPrefix = table_queue_prefix(Table, Q, Enc),
TPrefix = make_table_key(Table),
Dir = kvdb_lib:queue_list_direction(Type, Reverse),
with_iterator(
Ref,
fun(I) ->
First =
case Dir of
fifo -> q_first_(I, Db, Table, Q, Head, Enc, HeedBlock);
lifo -> q_last_(I, Db, Table, Q, Head, Enc, HeedBlock)
end,
q_all_(First, Limit, Limit, Filter, I, Db, Table,
q_all_dir(Dir), Enc, Type, QPrefix, TPrefix,
HeedBlock, [])
end);
list_queue_int(_, _, _, _, _, 0, _) ->
{[], fun() -> done end}.
q_all_dir(fifo) -> next;
q_all_dir(lifo) -> prev.
q_all_({RawKey, St, Obj}, Limit, Limit0, Filter, I, Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, Acc)
when Limit > 0 ->
#q_key{key = Key} = QKey =
kvdb_lib:split_queue_key(Enc,Type,element(1,Obj)),
{Cont,Acc1} = case Filter(RawKey, St, QKey, setelement(1, Obj, Key)) of
skip -> {true, Acc};
stop -> {false, Acc};
{stop,X} -> {false, [X|Acc]};
{keep,X} -> {true, [X|Acc]}
end,
case {Cont, decr(Limit)} of
{true, Limit1} when Limit1 > 0 ->
q_all_cont(Limit1, Limit0, Filter, I, Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, Acc1);
_ when Acc1 == [] ->
done;
{true, _} ->
TabKey = make_table_key(Table, enc(key, element(1, Obj), Enc)),
{lists:reverse(Acc1),
fun() ->
with_iterator(
Db#db.ref,
fun(I1) ->
eleveldb:iterator_move(I1, TabKey),
q_all_cont(Limit0, Limit0, Filter, I1,
Db, Table, Dir, Enc,
Type, QPrefix, TPrefix, HeedBlock, [])
end)
end};
{false, _}->
{lists:reverse(Acc1), fun() -> done end}
end;
q_all_(Stop, _, _, _, _, _, _, _, _, _, _, _, _, Acc)
when Stop == done; Stop == blocked ->
if Acc == [] -> Stop;
true ->
{lists:reverse(Acc), fun() -> Stop end}
end.
q_all_cont(Limit, Limit0, Filter, I, Db, Table, Dir, Enc, Type,
QPrefix, TPrefix, HeedBlock, Acc) ->
QSz = byte_size(QPrefix),
TSz = byte_size(TPrefix),
case eleveldb:iterator_move(I, Dir) of
{ok, <<QPrefix:QSz/binary, _/binary>> = K, <<F:8, V/binary>>} ->
if F == $*, HeedBlock ->
q_all_(blocked, Limit, Limit0, Filter, I, Db,
Table, Dir, Enc, Type, QPrefix, TPrefix,
HeedBlock, Acc);
true ->
Status = case F of
$* -> blocking;
$+ -> active;
$- -> inactive
end,
<<TPrefix:TSz/binary, Key/binary>> = K,
q_all_({Key, Status, decode_obj(Db, Enc, Table, Key, V)},
Limit, Limit0, Filter, I, Db, Table,
Dir, Enc, Type, QPrefix, TPrefix, HeedBlock, Acc)
end;
_ ->
q_all_(done, Limit, Limit0, Filter, I, Db, Table, Dir,
Enc, Type, QPrefix, TPrefix, HeedBlock, Acc)
end.
table_queue_prefix(Table, Q, Enc) when Enc == raw; element(1, Enc) == raw ->
make_table_key(Table, <<(kvdb_lib:escape(Q))/binary, "%">>);
table_queue_prefix(Table, Q, Enc) when Enc == sext; element(1, Enc) == sext ->
make_table_key(Table, sext:prefix({Q,'_','_'})).
get(Db, Table, Key) ->
lager:debug("get: Db = ~p, Table = ~p, Key = ~p ~n", [Db, Table, Key]),
case type(Db, Table) of
set ->
get(Db, Table, Key, encoding(Db, Table), set);
_ ->
erlang:error(illegal)
end.
get(#db { } = Db , Table , # q_key { } = QKey , Enc , Type ) - >
Actual = : q_key_to_actual(QKey , Enc , Type ) ,
get_(Db , Table , QKey#q_key.key , EncKey , Enc , Type ) ;
get(#db{} = Db, Table, Key, Enc, Type) ->
EncKey = enc(key, Key, Enc),
get_(Db, Table, Key, EncKey, Enc, Type).
get_(#db{ref = Ref} = Db, Table, Key, EncKey, Enc, Type) ->
case {Type, eleveldb:get(Ref, make_table_key(Table, EncKey), [])} of
{set, {ok, V}} ->
{ok, decode_obj_v(Db, Enc, Table, EncKey, Key, V)};
{_, {ok, <<F:8, V/binary>>}} when F==$*; F==$+; F==$- ->
{ok, decode_obj_v(Db, Enc, Table, EncKey, Key, V)};
{_, not_found} ->
{error, not_found};
{_, {error, _}} = Error ->
Error
end.
get_value(Db, Table, K) ->
case get(Db, Table, K) of
{ok, {_, _, V}} ->
V;
{ok, {_, V}} ->
V;
{error, not_found} ->
throw(no_value)
end.
index_get(#db{ref = Ref} = Db, Table, IxName, IxVal) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
IxPat = make_key(Table, $?, sext:encode({IxName, IxVal})),
with_iterator(
Ref,
fun(I) ->
get_by_ix_(prefix_move(I, IxPat, IxPat), I, IxPat, Db,
Table, Enc, Type, obj)
end).
index_keys(#db{ref = Ref} = Db, Table, IxName, IxVal) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
IxPat = make_key(Table, $?, sext:encode({IxName, IxVal})),
with_iterator(
Ref,
fun(I) ->
get_by_ix_(prefix_move(I, IxPat, IxPat), I, IxPat, Db,
Table, Enc, Type, key)
end).
get_by_ix_({ok, K, _}, I, Prefix, Db, Table, Enc, Type, Acc) ->
case get(Db, Table, sext:decode(K), Enc, Type) of
{ok, Obj} ->
Keep = case Acc of
obj -> Obj;
key -> element(1, Obj)
end,
[Keep | get_by_ix_(prefix_move(I, Prefix, next), I,
Prefix, Db, Table, Enc, Type, Acc)];
{error,_} ->
get_by_ix_(prefix_move(I, Prefix, next), I, Prefix,
Db, Table, Enc, Type, Acc)
end;
get_by_ix_(done, _, _, _, _, _, _, _) ->
[].
queue_read(#db{ref = Ref} = Db, Table, #q_key{key = K} = QKey) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
case eleveldb:get(Ref, make_table_key(Table, Key), []) of
{ok, <<St:8, V/binary>>} when St==$*; St==$-; St==$+ ->
Obj = decode_obj_v(Db, Enc, Table, Key, QKey, V),
Status = dec_queue_obj_status(St),
{ok, Status, setelement(1, Obj, K)};
not_found ->
{error, not_found};
{error, _} = Error ->
Error
end.
delete(#db{} = Db, Table, #q_key{} = QKey) ->
Enc = encoding(Db, Table),
Type = type(Db, Table),
Key = kvdb_lib:q_key_to_actual(QKey, Enc, Type),
EncKey = enc(key, Key, Enc),
delete_(Db, Table, Enc, Key, EncKey);
delete(#db{} = Db, Table, Key) ->
Enc = encoding(Db, Table),
EncKey = enc(key, Key, Enc),
delete_(Db, Table, Enc, Key, EncKey).
delete_(#db{ref = Ref} = Db, Table, Enc, Key, EncKey) ->
Ix = case Enc of
{_,_,_} -> index(Db, Table);
_ -> []
end,
{IxOps, As} =
case Enc of
{_, _, _} ->
Attrs = get_attrs_(Db, Table, EncKey, all),
IxOps_ = case Ix of
[_|_] -> [{delete, ix_key(Table, I, Key)} ||
I <- kvdb_lib:index_vals(
Ix, Key, Attrs,
fun() ->
get_value(Db, Table,
Key)
end)];
_ -> []
end,
{IxOps_, attrs_to_delete(Table, EncKey, Attrs)};
_ ->
{[], []}
end,
eleveldb:write(Ref, IxOps ++ [{delete, make_table_key(Table, EncKey)} | As], []).
attrs_to_put(_, _, []) -> [];
attrs_to_put(Table, Key, Attrs) when is_list(Attrs), is_binary(Key) ->
EncKey = sext : encode(Key ) ,
[{put, make_key(Table, $=, <<Key/binary,
(sext:encode(K))/binary>>),
term_to_binary(V)} || {K, V} <- Attrs].
attrs_to_delete(_, _, []) -> [];
attrs_to_delete(Table, Key, Attrs) when is_list(Attrs), is_binary(Key) ->
EncKey = sext : encode(Key ) ,
[{delete, make_key(Table, $=,
<<Key/binary,
(sext:encode(A))/binary>>)} || {A,_} <- Attrs].
get_attrs(#db{ref = Ref} = Db, Table, Key, As) ->
case encoding(Db, Table) of
{_, _, _} = Enc ->
EncKey = enc(key, Key, Enc),
case eleveldb:get(Ref, make_table_key(Table, EncKey), []) of
{ok, _} ->
{ok, get_attrs_(Db, Table, EncKey, As)};
_ ->
{error, not_found}
end;
_ ->
erlang:error(badarg)
end.
get_attrs_(#db{ref = Ref}, Table, EncKey, As) ->
TableKey = make_key(Table, $=, EncKey),
with_iterator(
Ref,
fun(I) ->
get_attrs_iter_(prefix_move(I, TableKey, TableKey),
I, TableKey, As)
end).
get_attrs_iter_({ok, K, V}, I, Prefix, As) ->
Key = sext:decode(K),
case As == all orelse lists:member(Key, As) of
true ->
[{Key, binary_to_term(V)}|
get_attrs_iter_(prefix_move(I, Prefix, next), I, Prefix, As)];
false ->
get_attrs_iter_(prefix_move(I, Prefix, next), I, Prefix, As)
end;
get_attrs_iter_(done, _, _, _) ->
[].
prefix_match(Db, Table, Prefix) ->
prefix_match(Db, Table, Prefix, 100).
prefix_match(#db{} = Db, Table, Prefix, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
prefix_match(Db, Table, Prefix, false, Limit).
prefix_match_rel(#db{} = Db, Table, Prefix, StartPoint, Limit) ->
prefix_match(Db, Table, Prefix, {true, StartPoint}, Limit).
prefix_match(#db{} = Db, Table, Prefix, Rel, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
case type(Db, Table) of
set ->
prefix_match_set(Db, Table, Prefix, Rel, Limit);
_ ->
error(badarg)
end.
prefix_match_set(#db{ref = Ref} = Db, Table, Prefix, Rel, Limit)
when (is_integer(Limit) orelse Limit == infinity) ->
Enc = encoding(Db, Table),
EncPrefix = kvdb_lib:enc_prefix(key, Prefix, Enc),
EncStart = case Rel of
false ->
EncPrefix;
{true, StartPoint} ->
enc(key, StartPoint, Enc)
end,
TablePrefix = make_table_key(Table),
TabPfxSz = byte_size(TablePrefix),
MatchKey = make_table_key(Table, EncPrefix),
StartKey = make_table_key(Table, EncStart),
with_iterator(
Ref,
fun(I) ->
if Rel==false, EncStart == <<>> ->
case eleveldb:iterator_move(I, TablePrefix) of
{ok, <<TablePrefix:TabPfxSz/binary>>, _} ->
prefix_match_(I, next, TablePrefix, Db, Table,
MatchKey, TablePrefix, Prefix,
Enc, Limit, Limit, []);
_ ->
done
end;
Rel=/=false ->
case eleveldb:iterator_move(I, StartKey) of
{ok, StartKey, _} ->
prefix_match_(I, next, StartKey, Db, Table,
MatchKey, TablePrefix, Prefix, Enc,
Limit, Limit, []);
{ok, _, _} ->
prefix_match_(I, StartKey, StartKey, Db, Table,
MatchKey, TablePrefix, Prefix, Enc,
Limit, Limit, [])
end;
true ->
prefix_match_(I, StartKey, StartKey, Db, Table, MatchKey,
TablePrefix, Prefix, Enc, Limit, Limit, [])
end
end).
prefix_match_(_I, _Next, Prev, #db{ref = Ref} = Db, Table, MatchKey, TPfx, Pfx,
Enc, 0, Limit0, Acc) ->
{lists:reverse(Acc),
fun() ->
with_iterator(
Ref,
fun(I1) ->
case eleveldb:iterator_move(I1, Prev) of
{ok, _, _} ->
prefix_match_(
I1, next, Prev, Db, Table, MatchKey, TPfx,
Pfx, Enc, Limit0, Limit0, []);
_ ->
done
end
end)
end};
prefix_match_(I, Next, _Prev, Db, Table, MatchKey, TPfx, Pfx, Enc,
Limit, Limit0, Acc) ->
Sz = byte_size(MatchKey),
case eleveldb:iterator_move(I, Next) of
{ok, <<MatchKey:Sz/binary, _/binary>> = Key, Val} ->
PSz = byte_size(TPfx),
<<TPfx:PSz/binary, K/binary>> = Key,
case (K =/= <<>> andalso kvdb_lib:is_prefix(Pfx, K, Enc)) of
true ->
prefix_match_(I, next, Key, Db, Table, MatchKey, TPfx, Pfx,
Enc, decr(Limit), Limit0,
[decode_obj(Db, Enc, Table, K, Val) | Acc]);
false ->
{lists:reverse(Acc), fun() -> done end}
end;
_ ->
{lists:reverse(Acc), fun() ->
done
end}
end.
decr(infinity) -> infinity;
decr(I) when is_integer(I) -> I-1.
first(#db{} = Db, Table) ->
first(Db, encoding(Db, Table), Table).
first(#db{ref = Ref} = Db, Enc, Table) ->
TableKey = make_table_key(Table),
with_iterator(
Ref,
fun(I) ->
case prefix_move(I, TableKey, TableKey) of
{ok, <<>>, _} ->
case prefix_move(I, TableKey, next) of
{ok, K, V} ->
{ok, decode_obj(Db, Enc, Table, K, V)};
done ->
done
end;
_ ->
done
end
end).
prefix_move(I, Prefix, Dir) ->
Sz = byte_size(Prefix),
case eleveldb:iterator_move(I, Dir) of
{ok, <<Prefix:Sz/binary, K/binary>>, Value} ->
{ok, K, Value};
_ ->
done
end.
last(#db{} = Db, Table) ->
last(Db, encoding(Db, Table), Table).
last(#db{ref = Ref} = Db, Enc, Table) ->
FirstKey = make_table_key(Table),
FirstSize = byte_size(FirstKey),
with_iterator(
Ref,
fun(I) ->
case eleveldb:iterator_move(I, LastKey) of
{ok,_AfterKey,_} ->
case eleveldb:iterator_move(I, prev) of
{ok, FirstKey, _} ->
done;
{ok, << FirstKey:FirstSize/binary, K/binary>>, Value} ->
{ok, decode_obj(Db, Enc, Table, K, Value)};
_ ->
done
end;
{error,invalid_iterator} ->
case eleveldb:iterator_move(I, last) of
{ok, FirstKey, _} ->
done;
{ok, << FirstKey:FirstSize/binary, K/binary >>, Value} ->
{ok, decode_obj(Db, Enc, Table, K, Value)}
end;
_ ->
done
end
end).
next(#db{} = Db, Table, Rel) ->
next(Db, encoding(Db, Table), Table, Rel).
next(Db, Enc, Table, Rel) ->
iterator_move(Db, Enc, Table, Rel, fun(A,B) -> A > B end, next).
prev(#db{} = Db, Table, Rel) ->
prev(Db, encoding(Db, Table), Table, Rel).
prev(Db, Enc, Table, Rel) ->
try iterator_move(Db, Enc, Table, Rel, fun(A,B) -> A < B end, prev) of
{ok, {<<>>, _}} ->
done;
Other ->
Other
catch
error:Err ->
io:fwrite("CRASH: ~p, ~p~n", [Err, erlang:get_stacktrace()]),
erlang:error(Err)
end.
iterator_move(#db{ref = Ref} = Db, Enc, Table, Rel, Comp, Dir) ->
TableKey = make_table_key(Table),
KeySize = byte_size(TableKey),
EncRel = enc(key, Rel, Enc),
RelKey = make_table_key(Table, EncRel),
with_iterator(
Ref,
fun(I) ->
iterator_move_(I, Db, Table, Enc, TableKey, KeySize,
EncRel, RelKey, Comp, Dir)
end).
iterator_move_(I, Db, Table, Enc, TableKey, KeySize, EncRel,
RelKey, Comp, Dir) ->
case eleveldb:iterator_move(I, RelKey) of
{ok, <<TableKey:KeySize/binary, Key/binary>>, Value} ->
case Key =/= <<>> andalso Comp(Key, EncRel) of
true ->
{ok, decode_obj(Db, Enc, Table, Key, Value)};
false ->
case eleveldb:iterator_move(I, Dir) of
{ok, <<TableKey:KeySize/binary,
Key2/binary>>, Value2} ->
case Key2 of
<<>> -> done;
_ ->
{ok, decode_obj(Db, Enc, Table,
Key2, Value2)}
end;
_ ->
done
end
end;
{ok, OtherKey, _} when Dir == prev ->
if byte_size(OtherKey) >= KeySize ->
<<OtherTabPat:KeySize/binary, _/binary>> = OtherKey,
if OtherTabPat > TableKey ->
iterator_move_(I, Db, Table, Enc, TableKey,
KeySize, EncRel, prev, Comp, Dir);
true ->
done
end;
true ->
done
end;
_ ->
done
end.
make_table_last_key(Table) ->
make_key(Table, $;, <<>>).
make_table_key(Table) ->
make_key(Table, $:, <<>>).
make_table_key(Table, Key) ->
make_key(Table, $:, Key).
make_key(Table, Sep, Key) when is_binary(Table) ->
<<Table/binary,Sep,Key/binary>>.
encode_obj ( { _ , _ , _ } = Enc , { Key , , Value } ) - >
{ enc(key , Key , Enc ) , , enc(value , Value , Enc ) } ;
{ enc(key , Key , Enc ) , none , enc(value , Value , Enc ) } .
encode_queue_obj(Enc, Type, Obj) ->
encode_queue_obj(Enc, Type, Obj, active).
encode_queue_obj({_,_,_} = Enc, Type, {#q_key{} = Key, Attrs, Value}, Status) ->
St = enc_queue_obj_status(Status),
AKey = kvdb_lib:q_key_to_actual(Key, Enc, Type),
{AKey, Attrs, <<St:8, (enc(value, Value, Enc))/binary>>};
encode_queue_obj(Enc, Type, {#q_key{} = Key, Value}, Status) ->
St = enc_queue_obj_status(Status),
AKey = kvdb_lib:q_key_to_actual(Key, Enc, Type),
{AKey, none, <<St:8, (enc(value, Value, Enc))/binary>>}.
enc_queue_obj_status(blocking) -> $*;
enc_queue_obj_status(active ) -> $+;
enc_queue_obj_status(inactive) -> $-.
dec_queue_obj_status($*) -> blocking;
dec_queue_obj_status($+) -> active;
dec_queue_obj_status($-) -> inactive.
decode_obj(Db, Enc, Table, K, V) ->
Key = dec(key, K, Enc),
decode_obj_v(Db, Enc, Table, K, Key, V).
decode_obj_v(Db, Enc, Table, EncKey, Key, V) ->
Value = dec(value, V, Enc),
case Enc of
{_, _, _} ->
Attrs = get_attrs_(Db, Table, EncKey, all),
{Key, Attrs, Value};
_ ->
{Key, Value}
end.
with_iterator(Db, F) ->
{ok, I} = eleveldb:iterator(Db, []),
try F(I)
after
eleveldb:iterator_close(I)
end.
type(Db, Table) ->
schema_lookup(Db, {a, Table, type}, set).
encoding(#db{encoding = Enc} = Db, Table) ->
schema_lookup(Db, {a, Table, encoding}, Enc).
index(#db{} = Db, Table) ->
schema_lookup(Db, {a, Table, index}, []).
schema(#db{} = Db, Table) ->
schema_lookup(Db, {a, Table, schema}, []).
ensure_schema(#db{ref = Ref} = Db, Opts) ->
ETS = ets:new(kvdb_schema, [ordered_set, public]),
Db1 = Db#db{metadata = ETS},
case eleveldb:get(Ref, make_table_key(?META_TABLE, <<>>), []) of
{ok, _} ->
[ets:insert(ETS, X) || X <- whole_table(Db1, sext, ?META_TABLE)],
Db1;
_ ->
ok = do_add_table(Db1, ?META_TABLE),
Tab = #table{name = ?META_TABLE, encoding = sext,
columns = [key,value]},
schema_write(Db1, {{table, ?META_TABLE}, Tab}),
schema_write(Db1, {{a, ?META_TABLE, encoding}, sext}),
schema_write(Db1, {{a, ?META_TABLE, type}, set}),
schema_write(Db1, {schema_mod, proplists:get_value(schema, Opts, kvdb_schema)}),
Db1
end.
whole_table(Db, Enc, Table) ->
whole_table(first(Db, Enc, Table), Db, Enc, Table).
whole_table({ok, {K, V}}, Db, Enc, Table) ->
[{K,V} | whole_table(next(Db, Enc, Table, K), Db, Enc, Table)];
whole_table(done, _Db, _Enc, _Table) ->
[].
schema_write(#db{} = Db, tabrec, Table, #table{} = TabRec) ->
schema_write(Db, {{table, Table}, TabRec});
schema_write(#db{} = Db, property, {Table, Key}, Value) ->
schema_write(Db, {{a, Table, Key}, Value});
schema_write(#db{} = Db, global, Key, Value) ->
schema_write(Db, {Key, Value}).
schema_read(#db{} = Db, tabrec, Table) ->
schema_lookup(Db, {table, Table}, undefined);
schema_read(#db{} = Db, property, {Table, Key}) ->
schema_lookup(Db, {a, Table, Key}, undefined);
schema_read(#db{} = Db, global, Key) ->
schema_lookup(Db, Key, undefined).
schema_delete(#db{} = Db, tabrec, Table) ->
schema_delete(Db, {table, Table});
schema_delete(#db{} = Db, property, {Table, Key}) ->
schema_delete(Db, {a, Table, Key});
schema_delete(#db{} = Db, global, Key) ->
schema_delete(Db, Key).
schema_fold(#db{} = Db, F, A) ->
fold(Db, F, A, sext, ?META_TABLE).
schema_write(#db{metadata = ETS} = Db, Item) ->
ets:insert(ETS, Item),
put(Db, ?META_TABLE, Item).
schema_lookup(_, {a, ?META_TABLE, Attr}, Default) ->
case Attr of
type -> set;
encoding -> sext;
_ -> Default
end;
schema_lookup(#db{metadata = ETS}, Key, Default) ->
case ets:lookup(ETS, Key) of
[{_, Value}] ->
Value;
[] ->
Default
end.
schema_delete(#db{metadata = ETS} = Db, Key) ->
ets:delete(ETS, Key),
delete(Db, ?META_TABLE, Key).
fold(Db, F, A, Enc, Table) ->
fold(first(Db, Enc, Table), F, A, Db, Enc, Table).
fold({ok, {K, V}}, F, A, Db, Enc, Table) ->
{Type, Key} = schema_key_type(K),
fold(next(Db, Enc, Table, K), F, F(Type, {Key, V}, A), Db, Enc, Table);
fold(done, _F, A, _Db, _Enc, _Table) ->
A.
schema_key_type({a,T,K}) ->
{property, {T, K}};
schema_key_type({table, T}) ->
{tabrec, T};
schema_key_type(Other) ->
{global, Other}.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.