From b6391d9d579f863cd151769abb830511ca4f0f23 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 25 Feb 2015 17:05:25 -0700 Subject: [PATCH 001/349] first commit of re-enabling stacklets --- Makefile | 4 +-- pixie/stacklets.pxi | 81 ++++++++++++++++++++++++++++++++++++++++++++ pixie/stdlib.pxi | 5 ++- pixie/vm/rt.py | 1 + pixie/vm/stacklet.py | 56 ++++++++++++++++++++++++++++++ target.py | 3 ++ 6 files changed, 147 insertions(+), 3 deletions(-) create mode 100644 pixie/stacklets.pxi create mode 100644 pixie/vm/stacklet.py diff --git a/Makefile b/Makefile index bb5cda71..e8f1c0a4 100644 --- a/Makefile +++ b/Makefile @@ -2,11 +2,11 @@ all: help EXTERNALS=../externals -PYTHON ?= python +PYTHON ?= pypy PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy -COMMON_BUILD_OPTS?=--thread --no-shared --gcrootfinder=shadowstack +COMMON_BUILD_OPTS?=--thread --no-shared --gcrootfinder=shadowstack --continuation JIT_OPTS?=--opt=jit TARGET_OPTS?=target.py diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi new file mode 100644 index 00000000..e8d75da4 --- /dev/null +++ b/pixie/stacklets.pxi @@ -0,0 +1,81 @@ +(ns pixie.stacklets + (require pixie.uv :as uv)) + +(def stacklet-loop-h (atom nil)) + +(defn -spawn-thread [fn] + (let [[h val] (@stacklet-loop-h [:spawn fn])] + (reset! stacklet-loop-h h) + (println h val) + val)) + +(defn enqueue [q itm] + ; TODO: Rewrite this crappy impl + (vec (conj (seq q) itm))) + +(defn dequeue [q] + [(ith q -1) + (pop q)]) + + +(defn yield-control [] + (let [[h] (@stacklet-loop-h [:yield nil])] + (reset! stacklet-loop-h h) + nil)) + + +(defmacro spawn [& body] + `(let [f (fn [h# _] + (reset! stacklet-loop-h h#) + (try + (println "spawn" h#) + ;(reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (println "returning " result#) + (@stacklet-loop-h [:spawn-end result#])) + (catch e (println e)))) + [h# val#] (@stacklet-loop-h [:spawn f])] + (reset! stacklet-loop-h h#) + val#)) + +(defn -with-stacklets [fn] + (let [[h [op arg]] ((new-stacklet fn) nil)] + (println h op arg) + (loop [op op + arg arg + this_h h + tasks []] + (println "in loop" op arg this_h tasks) + (cond + (= op :spawn) (let [wh (new-stacklet arg) + [h [op arg]] (this_h nil)] + (recur op arg h (enqueue tasks wh))) + (= op :yield) (let [tasks (enqueue tasks this_h) + [task tasks] (dequeue tasks) + [h [op arg]] (task nil)] + (recur op arg h tasks)) + (= op :spawn-end) (if (empty? tasks) + arg + (let [[task tasks] (dequeue tasks) + [h [op arg]] (task nil)] + (recur op arg h tasks))) + :else (assert false (str "Unkown command " op " " arg)))))) + + +(defmacro with-stacklets [& body] + `(-with-stacklets + (fn [h# _] + (try + (println h# _) + (reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (@stacklet-loop-h [:spawn-end result#])) + (catch e + (println e)))))) + +(with-stacklets (spawn (dotimes [x 10] + (yield-control) + (println x))) + (spawn (dotimes [x 10] + (yield-control) + (println x)))(yield-control)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index eb69fc64..30ab4933 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1630,7 +1630,10 @@ All these forms can be combined and nested, in the example below: For more information, see http://clojure.org/special_forms#binding-forms"} [bindings & body] - (let* [destructured-bindings (transduce (map #(apply destructure %1)) + (let* [destructured-bindings (transduce (map (fn [args] + (assert (= 2 (count args)) (str "Bindings must be in pairs, not " args + " " (meta (first args)))) + (apply destructure args))) concat [] (partition 2 bindings))] diff --git a/pixie/vm/rt.py b/pixie/vm/rt.py index 7eb65b33..d9ff37ed 100644 --- a/pixie/vm/rt.py +++ b/pixie/vm/rt.py @@ -68,6 +68,7 @@ def wrapper(*args): import pixie.vm.libs.string import pixie.vm.threads import pixie.vm.string_builder + import pixie.vm.stacklet numbers.init() diff --git a/pixie/vm/stacklet.py b/pixie/vm/stacklet.py new file mode 100644 index 00000000..da42cfc0 --- /dev/null +++ b/pixie/vm/stacklet.py @@ -0,0 +1,56 @@ +import rpython.rlib.rstacklet as rstacklet +from pixie.vm.object import Object, Type, affirm +from pixie.vm.code import as_var +import pixie.vm.rt as rt + + +class GlobalState(object): + def __init__(self): + self._is_inited = False + self._val = None + + +global_state = GlobalState() + + +def init(): + if not global_state._is_inited: + global_state._th = rstacklet.StackletThread(rt.__config__) + global_state._is_inited = True + + +class StackletHandle(Object): + _type = Type(u"StackletHandle") + def __init__(self, h): + self._stacklet_handle = h + self._used = False + + def type(self): + return self._type + + def invoke(self, args): + affirm(not self._used, u"Can only call a given stacklet handle once.") + affirm(len(args) == 1, u"Only one arg should be handed to a stacklet handle") + self._used = True + global_state._val = args[0] + new_h = StackletHandle(global_state._th.switch(self._stacklet_handle)) + val = global_state._val + global_state._val = None + return rt.vector(new_h, val) + +def new_handler(h, _): + fn = global_state._val + global_state._val = None + h = global_state._th.switch(h) + val = global_state._val + fn.invoke([StackletHandle(h), val]) + affirm(False, u"TODO: What do we do now?") + return h + + + +@as_var("new-stacklet") +def new_stacklet(fn): + global_state._val = fn + h = global_state._th.new(new_handler) + return StackletHandle(h) \ No newline at end of file diff --git a/target.py b/target.py index a91a940b..c1726876 100644 --- a/target.py +++ b/target.py @@ -185,6 +185,9 @@ def load_stdlib(): def entry_point(args): try: + import pixie.vm.stacklet + pixie.vm.stacklet.init() + interactive = True exit = False script_args = [] From 5b155ccc3c853dce27ebdc244036614cc4e4df40 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 26 Feb 2015 15:56:09 -0700 Subject: [PATCH 002/349] more stacklet support of libuv and fix a bug with ffi callbacks --- pixie/stacklets.pxi | 75 ++++++++++++++++++++++++++++++++------------ pixie/vm/libs/ffi.py | 2 +- 2 files changed, 56 insertions(+), 21 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index e8d75da4..91578687 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -11,11 +11,12 @@ (defn enqueue [q itm] ; TODO: Rewrite this crappy impl - (vec (conj (seq q) itm))) + (swap! q (fn [q] (vec (conj (seq q) itm))))) (defn dequeue [q] - [(ith q -1) - (pop q)]) + (let [itm (ith @q -1)] + (swap! q pop) + itm)) (defn yield-control [] @@ -38,28 +39,60 @@ (reset! stacklet-loop-h h#) val#)) +(defn sleep [ms] + (let [[h] (@stacklet-loop-h [:sleep ms])] + (reset! stacklet-loop-h h) + nil)) + +(defmulti async-fn (fn [f args k tasks] f)) + +(defmethod async-fn :sleep + ([f args k tasks] + (let [cb (atom nil) + timer (uv/uv_timer_t)] + (reset! cb (ffi-prep-callback uv/uv_timer_cb + (fn [handle] + (enqueue tasks k) + (uv/uv_timer_stop timer) + (-dispose! @cb)))) + (uv/uv_timer_init (uv/uv_default_loop) timer) + (uv/uv_timer_start timer @cb args 0)))) + (defn -with-stacklets [fn] - (let [[h [op arg]] ((new-stacklet fn) nil)] + (let [[h [op arg]] ((new-stacklet fn) nil) + tasks (atom [])] (println h op arg) (loop [op op arg arg - this_h h - tasks []] + this_h h] (println "in loop" op arg this_h tasks) (cond + ; (= 0 (count tasks)) (uv/uv_run_loop (uv/uv_default_loop)) (= op :spawn) (let [wh (new-stacklet arg) [h [op arg]] (this_h nil)] - (recur op arg h (enqueue tasks wh))) - (= op :yield) (let [tasks (enqueue tasks this_h) - [task tasks] (dequeue tasks) + (enqueue tasks wh) + (println @tasks) + (recur op arg h)) + (= op :yield) (let [_ (enqueue tasks this_h) + task (dequeue tasks) [h [op arg]] (task nil)] - (recur op arg h tasks)) - (= op :spawn-end) (if (empty? tasks) - arg - (let [[task tasks] (dequeue tasks) - [h [op arg]] (task nil)] - (recur op arg h tasks))) - :else (assert false (str "Unkown command " op " " arg)))))) + (recur op arg h)) + (= op :spawn-end) (do (when (empty? @tasks) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT)) + (if (empty? @tasks) + :done + (let [task (dequeue tasks) + [h [op arg]] (task nil)] + (recur op arg h)))) + :else (do (async-fn op arg this_h tasks) + (when (empty? @tasks) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT)) + (if (empty? @tasks) + :done + (let [task (dequeue tasks) + [h [op arg]] (task nil)] + (recur op arg h)))) + :else (assert false (str "Unknown command " op " " arg)))))) (defmacro with-stacklets [& body] @@ -74,8 +107,10 @@ (println e)))))) (with-stacklets (spawn (dotimes [x 10] - (yield-control) - (println x))) + (sleep 100) + + (println "<- " x))) (spawn (dotimes [x 10] - (yield-control) - (println x)))(yield-control)) + (sleep 100) + (println "-> " x))) + (yield-control)) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 15e13167..33d43d8e 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -554,7 +554,7 @@ def ffi_prep_callback(tp, f): affirm(isinstance(tp, CFunctionType), u"First argument to ffi-prep-callback must be a CFunctionType") raw_closure = rffi.cast(rffi.VOIDP, clibffi.closureHeap.alloc()) - unique_id = len(registered_callbacks) + unique_id = rffi.cast(lltype.Signed, raw_closure) res = clibffi.c_ffi_prep_closure(rffi.cast(clibffi.FFI_CLOSUREP, raw_closure), tp.get_cd().cif, invoke_callback, From c769b86de4dc037996d81cd1efb952aea9d1c876 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 26 Feb 2015 22:27:04 -0700 Subject: [PATCH 003/349] start of async io support for pixie --- pixie/PixieChecker.hpp | 123 ++++++++++++++++++++++++++++++++++++++++- pixie/stacklets.pxi | 59 +++++++++++++------- pixie/uv.pxi | 109 +++++++++++++++++++++++++++++++++++- 3 files changed, 267 insertions(+), 24 deletions(-) diff --git a/pixie/PixieChecker.hpp b/pixie/PixieChecker.hpp index 4c5f0571..7266cbea 100644 --- a/pixie/PixieChecker.hpp +++ b/pixie/PixieChecker.hpp @@ -24,7 +24,7 @@ template < typename T > std::string to_string( const T& n ) stm << n ; return stm.str() ; } - + // Function Checker template @@ -92,7 +92,7 @@ struct FunctionTyper<0, T> " ]}"; } }; - + template struct FunctionTyper<4, T> { @@ -108,7 +108,124 @@ struct FunctionTyper<0, T> " ]}"; } }; - + + template + struct FunctionTyper<5, T> + { + static std::string getType() + { + return "{:type :function :arity 5 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + " ]}"; + } + }; + + template + struct FunctionTyper<6, T> + { + static std::string getType() + { + return "{:type :function :arity 6 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + GetType::arg6_type>() + " " + + " ]}"; + } + }; + + template + struct FunctionTyper<7, T> + { + static std::string getType() + { + return "{:type :function :arity 7 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + GetType::arg6_type>() + " " + + GetType::arg7_type>() + " " + + " ]}"; + } + }; + + template + struct FunctionTyper<8, T> + { + static std::string getType() + { + return "{:type :function :arity 8 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + GetType::arg6_type>() + " " + + GetType::arg7_type>() + " " + + GetType::arg8_type>() + " " + + " ]}"; + } + }; + + template + struct FunctionTyper<9, T> + { + static std::string getType() + { + return "{:type :function :arity 9 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + GetType::arg6_type>() + " " + + GetType::arg7_type>() + " " + + GetType::arg8_type>() + " " + + GetType::arg9_type>() + " " + + " ]}"; + } + }; + + template + struct FunctionTyper<10, T> + { + static std::string getType() + { + return "{:type :function :arity 10 :returns " + + GetType::result_type>() + + " :arguments [" + + GetType::arg1_type>() + " " + + GetType::arg2_type>() + " " + + GetType::arg3_type>() + " " + + GetType::arg4_type>() + " " + + GetType::arg5_type>() + " " + + GetType::arg6_type>() + " " + + GetType::arg7_type>() + " " + + GetType::arg8_type>() + " " + + GetType::arg9_type>() + " " + + GetType::arg10_type>() + " " + + " ]}"; + } + }; + // End Function Typer diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 91578687..cac6e968 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -52,12 +52,39 @@ timer (uv/uv_timer_t)] (reset! cb (ffi-prep-callback uv/uv_timer_cb (fn [handle] - (enqueue tasks k) + (enqueue tasks [k nil]) (uv/uv_timer_stop timer) (-dispose! @cb)))) (uv/uv_timer_init (uv/uv_default_loop) timer) (uv/uv_timer_start timer @cb args 0)))) + +(defmacro defuvfsfn [nm args return] + (let [kw (keyword (str "pixie.uv/" (name nm)))] + `(do (defn ~nm ~args + (let [[h# result#] (@stacklet-loop-h [~kw ~args])] + (reset! stacklet-loop-h h#) + result#)) + (defmethod async-fn ~kw + [f# ~args k# tasks#] + (let [cb# (atom nil)] + (reset! cb# (ffi-prep-callback uv/uv_fs_cb + (fn [req#] + (enqueue tasks# [k# (~return req#)]) + (uv/uv_fs_req_cleanup req#) + (-dispose! @cb#)))) + (~(symbol (str "pixie.uv/uv_fs_" (name nm))) + (uv/uv_default_loop) + (uv/uv_fs_t) + ~@args + @cb#)))))) + +((var defuvfsfn) 'open '[path flags mode] :result) + +(defuvfsfn open [path flags mode] :result) + +(keyword "foo/bar") + (defn -with-stacklets [fn] (let [[h [op arg]] ((new-stacklet fn) nil) tasks (atom [])] @@ -70,27 +97,26 @@ ; (= 0 (count tasks)) (uv/uv_run_loop (uv/uv_default_loop)) (= op :spawn) (let [wh (new-stacklet arg) [h [op arg]] (this_h nil)] - (enqueue tasks wh) - (println @tasks) + (enqueue tasks [wh nil]) (recur op arg h)) - (= op :yield) (let [_ (enqueue tasks this_h) - task (dequeue tasks) - [h [op arg]] (task nil)] + (= op :yield) (let [_ (enqueue tasks [this_h nil]) + [task val] (dequeue tasks) + [h [op arg]] (task val)] (recur op arg h)) (= op :spawn-end) (do (when (empty? @tasks) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT)) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_ONCE)) (if (empty? @tasks) :done - (let [task (dequeue tasks) - [h [op arg]] (task nil)] + (let [[task val] (dequeue tasks) + [h [op arg]] (task val)] (recur op arg h)))) :else (do (async-fn op arg this_h tasks) (when (empty? @tasks) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT)) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_ONCE)) (if (empty? @tasks) :done - (let [task (dequeue tasks) - [h [op arg]] (task nil)] + (let [[task val] (dequeue tasks) + [h [op arg]] (task val)] (recur op arg h)))) :else (assert false (str "Unknown command " op " " arg)))))) @@ -106,11 +132,4 @@ (catch e (println e)))))) -(with-stacklets (spawn (dotimes [x 10] - (sleep 100) - - (println "<- " x))) - (spawn (dotimes [x 10] - (sleep 100) - (println "-> " x))) - (yield-control)) +(with-stacklets (open "/tmp/foo-bar-baz" uv/O_WRONLY uv/O_CREAT)) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index e6f03f15..94fefb0a 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -35,4 +35,111 @@ (f/defcfn uv_timer_stop) (f/defcfn uv_timer_again) (f/defcfn uv_timer_set_repeat) - (f/defcfn uv_timer_get_repeat)) + (f/defcfn uv_timer_get_repeat) + + ;; Filesystem + + (f/defcstruct uv_fs_t [:loop + :fs_type + :path + :result + :ptr]) + (f/defcstruct uv_timespec_t [:tv_sec + :tv_nsec]) + (f/defcstruct uv_stat_t [:st_dev + :st_mode + :st_nlink + :st_uid + :st_gid + :st_rdev + :st_ino + :st_size + :st_blksize + :st_blocks + :st_flags + :st_gen]) + + (f/defconst UV_FS_UNKNOWN) + (f/defconst UV_FS_CUSTOM) + (f/defconst UV_FS_OPEN) + (f/defconst UV_FS_CLOSE) + (f/defconst UV_FS_READ) + (f/defconst UV_FS_WRITE) + (f/defconst UV_FS_SENDFILE) + (f/defconst UV_FS_STAT) + (f/defconst UV_FS_LSTAT) + (f/defconst UV_FS_FSTAT) + (f/defconst UV_FS_FTRUNCATE) + (f/defconst UV_FS_UTIME) + (f/defconst UV_FS_FUTIME) + (f/defconst UV_FS_ACCESS) + (f/defconst UV_FS_CHMOD) + (f/defconst UV_FS_FCHMOD) + (f/defconst UV_FS_FSYNC) + (f/defconst UV_FS_FDATASYNC) + (f/defconst UV_FS_UNLINK) + (f/defconst UV_FS_RMDIR) + (f/defconst UV_FS_MKDIR) + (f/defconst UV_FS_MKDTEMP) + (f/defconst UV_FS_RENAME) + (f/defconst UV_FS_SCANDIR) + (f/defconst UV_FS_LINK) + (f/defconst UV_FS_SYMLINK) + (f/defconst UV_FS_READLINK) + (f/defconst UV_FS_CHOWN) + (f/defconst UV_FS_FCHOWN) + + (f/defconst UV_DIRENT_UNKNOWN) + (f/defconst UV_DIRENT_FILE) + (f/defconst UV_DIRENT_DIR) + (f/defconst UV_DIRENT_LINK) + (f/defconst UV_DIRENT_FIFO) + (f/defconst UV_DIRENT_SOCKET) + (f/defconst UV_DIRENT_CHAR) + (f/defconst UV_DIRENT_BLOCK) + + (f/defcstruct uv_dirent_t [:name + :type]) + + (f/defcfn uv_fs_req_cleanup) + (f/defcfn uv_fs_close) + (f/defcfn uv_fs_open) + + (f/defccallback uv_fs_cb) + + (f/defcfn uv_fs_unlink) + (f/defcfn uv_fs_write) + (f/defcfn uv_fs_read) + (f/defcfn uv_fs_mkdir) + (f/defcfn uv_fs_mkdtemp) + (f/defcfn uv_fs_rmdir) + (f/defcfn uv_fs_scandir) + (f/defcfn uv_fs_scandir_next) + (f/defcfn uv_fs_stat) + (f/defcfn uv_fs_fstat) + (f/defcfn uv_fs_lstat) + (f/defcfn uv_fs_rename) + (f/defcfn uv_fs_fsync) + (f/defcfn uv_fs_fdatasync) + (f/defcfn uv_fs_ftruncate) + (f/defcfn uv_fs_sendfile) + (f/defcfn uv_fs_access) + (f/defcfn uv_fs_chmod) + (f/defcfn uv_fs_fchmod) + (f/defcfn uv_fs_utime) + (f/defcfn uv_fs_futime) + (f/defcfn uv_fs_link) + (f/defcfn uv_fs_symlink) + (f/defcfn uv_fs_readlink) + (f/defcfn uv_fs_chown) + (f/defcfn uv_fs_fchown) + + (f/defconst O_RDONLY) + (f/defconst O_WRONLY) + (f/defconst O_RDWR) + + (f/defconst O_APPEND) + (f/defconst O_ASYNC) + (f/defconst O_CREAT) + + ) From 05bd97e4cb1cf33101571b2693176633e7b38508 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 27 Feb 2015 20:52:09 -0700 Subject: [PATCH 004/349] stacklets play nice with libuv now. Main loop refactored to be much cleaner --- pixie/stacklets.pxi | 166 +++++++++++++++++++++++++++----------------- pixie/uv.pxi | 30 +++++++- 2 files changed, 129 insertions(+), 67 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index cac6e968..4869c296 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -1,13 +1,23 @@ (ns pixie.stacklets (require pixie.uv :as uv)) +;; LibUV seems to act up when we invoke a stacklet from inside a callbac +;; so we compensate by simply storing the stacklets in a task queue +;; and calling them later outside of the libuv loop. + (def stacklet-loop-h (atom nil)) -(defn -spawn-thread [fn] - (let [[h val] (@stacklet-loop-h [:spawn fn])] - (reset! stacklet-loop-h h) - (println h val) - val)) +(def thread-count (atom 0)) + +(defmulti async-fn (fn [f args k] f)) + +(defmethod async-fn :spawn-end + [_ _ _] + (swap! thread-count dec) + (when (= @thread-count 0) + (uv/uv_stop (uv/uv_default_loop)))) + +(def tasks (atom [])) (defn enqueue [q itm] ; TODO: Rewrite this crappy impl @@ -18,41 +28,60 @@ (swap! q pop) itm)) +(comment + (defn run-and-process [k args] + + (let [[h [op args]] (k args)] + (async-fn op args h)))) + +(defn -run-and-process [k args] + + (let [[h [op args]] (k args)] + (async-fn op args h))) + +(defn run-and-process [k args] + (swap! tasks conj [k args])) + +;; Yield (defn yield-control [] (let [[h] (@stacklet-loop-h [:yield nil])] (reset! stacklet-loop-h h) nil)) +(def close_cb (ffi-prep-callback uv/uv_close_cb + (fn [handle] + (pixie.ffi/free handle) + ))) -(defmacro spawn [& body] - `(let [f (fn [h# _] - (reset! stacklet-loop-h h#) - (try - (println "spawn" h#) - ;(reset! stacklet-loop-h h#) - (let [result# (do ~@body)] - (println "returning " result#) - (@stacklet-loop-h [:spawn-end result#])) - (catch e (println e)))) - [h# val#] (@stacklet-loop-h [:spawn f])] - (reset! stacklet-loop-h h#) - val#)) +(def tasks (atom [])) + +(defmethod async-fn :yield + [_ args k] + + (let [a (uv/uv_async_t) + cb (atom nil)] + (reset! cb (ffi-prep-callback uv/uv_async_cb + (fn [handle] + (uv/uv_close a close_cb) + (run-and-process k nil)))) + (uv/uv_async_init (uv/uv_default_loop) a @cb) + (uv/uv_async_send a))) + +;;; Sleep (defn sleep [ms] (let [[h] (@stacklet-loop-h [:sleep ms])] (reset! stacklet-loop-h h) nil)) -(defmulti async-fn (fn [f args k tasks] f)) - (defmethod async-fn :sleep - ([f args k tasks] + ([f args k] (let [cb (atom nil) timer (uv/uv_timer_t)] (reset! cb (ffi-prep-callback uv/uv_timer_cb (fn [handle] - (enqueue tasks [k nil]) + (run-and-process k nil) (uv/uv_timer_stop timer) (-dispose! @cb)))) (uv/uv_timer_init (uv/uv_default_loop) timer) @@ -70,66 +99,73 @@ (let [cb# (atom nil)] (reset! cb# (ffi-prep-callback uv/uv_fs_cb (fn [req#] - (enqueue tasks# [k# (~return req#)]) - (uv/uv_fs_req_cleanup req#) - (-dispose! @cb#)))) + (try + (enqueue tasks# [k# (~return (pixie.ffi/cast req# uv/uv_fs_t))]) + (uv/uv_fs_req_cleanup req#) + (-dispose! @cb#) + (catch e (println e)))))) (~(symbol (str "pixie.uv/uv_fs_" (name nm))) (uv/uv_default_loop) (uv/uv_fs_t) ~@args @cb#)))))) +(comment + ((var defuvfsfn) 'open '[path flags mode] :result) -((var defuvfsfn) 'open '[path flags mode] :result) - -(defuvfsfn open [path flags mode] :result) - -(keyword "foo/bar") + (defuvfsfn open [path flags mode] :result) + (defuvfsfn read [file bufs nbufs offset] :result) + (defuvfsfn close [file] :result)) (defn -with-stacklets [fn] - (let [[h [op arg]] ((new-stacklet fn) nil) - tasks (atom [])] - (println h op arg) - (loop [op op - arg arg - this_h h] - (println "in loop" op arg this_h tasks) - (cond - ; (= 0 (count tasks)) (uv/uv_run_loop (uv/uv_default_loop)) - (= op :spawn) (let [wh (new-stacklet arg) - [h [op arg]] (this_h nil)] - (enqueue tasks [wh nil]) - (recur op arg h)) - (= op :yield) (let [_ (enqueue tasks [this_h nil]) - [task val] (dequeue tasks) - [h [op arg]] (task val)] - (recur op arg h)) - (= op :spawn-end) (do (when (empty? @tasks) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_ONCE)) - (if (empty? @tasks) - :done - (let [[task val] (dequeue tasks) - [h [op arg]] (task val)] - (recur op arg h)))) - :else (do (async-fn op arg this_h tasks) - (when (empty? @tasks) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_ONCE)) - (if (empty? @tasks) - :done - (let [[task val] (dequeue tasks) - [h [op arg]] (task val)] - (recur op arg h)))) - :else (assert false (str "Unknown command " op " " arg)))))) + (let [[h [op arg]] ((new-stacklet fn) nil)] + (swap! thread-count inc) + (async-fn op arg h) + (loop [] + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT) + (let [tks @tasks] + (reset! tasks []) + (when (not (empty? tks)) + (doseq [[k args] tks] + (-run-and-process k args)) + (recur)))))) (defmacro with-stacklets [& body] `(-with-stacklets (fn [h# _] (try - (println h# _) (reset! stacklet-loop-h h#) (let [result# (do ~@body)] (@stacklet-loop-h [:spawn-end result#])) (catch e (println e)))))) -(with-stacklets (open "/tmp/foo-bar-baz" uv/O_WRONLY uv/O_CREAT)) + + +(with-stacklets (dotimes [x 10000] + (yield-control) + (println x))) + +(comment + (defn run-later [f] + (let [a (uv/uv_async_t) + cb (atom nil)] + (println "start yield") + (reset! cb (ffi-prep-callback uv/uv_async_cb + (fn [handle] + (println "process yield") + (f) + (uv/uv_close a close_cb) + (-dispose! @cb) + (println "done process yield")))) + (uv/uv_async_init (uv/uv_default_loop) a @cb) + (uv/uv_async_send a))) + + (defn cfn [x] + (fn [] + (println x) + (if (pos? x) + (run-later (cfn (dec x)))))) + + (do (run-later (cfn 10000)) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT))) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 94fefb0a..85079189 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -7,6 +7,10 @@ (f/defconst UV_RUN_ONCE) (f/defconst UV_RUN_NOWAIT) + (f/defcfn uv_close) + (f/defccallback uv_close_cb) + + (f/defcstruct uv_loop_t []) (f/defcfn uv_loop_init) @@ -23,6 +27,7 @@ (f/defcfn uv_update_time) (f/defcfn uv_walk) + (f/defccallback uv_read_cb) @@ -37,6 +42,7 @@ (f/defcfn uv_timer_set_repeat) (f/defcfn uv_timer_get_repeat) + ;; Filesystem (f/defcstruct uv_fs_t [:loop @@ -57,7 +63,15 @@ :st_blksize :st_blocks :st_flags - :st_gen]) + :st_gen + :st_atim.tv_sec + :st_atim.tv_nsec + :st_mtim.tv_sec + :st_mtim.tv_nsec + :st_ctim.tv_sec + :st_ctim.tv_nsec + :st_birthtim.tv_sec + :st_birthtim.tv_nsec]) (f/defconst UV_FS_UNKNOWN) (f/defconst UV_FS_CUSTOM) @@ -142,4 +156,16 @@ (f/defconst O_ASYNC) (f/defconst O_CREAT) - ) + (f/defconst S_IRUSR) + + + ; ERRNO + (f/defconst UV_E2BIG) + (f/defconst UV_EACCES) + + + ; async + (f/defcstruct uv_async_t []) + (f/defccallback uv_async_cb) + (f/defcfn uv_async_init) + (f/defcfn uv_async_send)) From 0400ef40503337953a0e2dd7f4238c26011a6854 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 4 Mar 2015 16:09:15 -0700 Subject: [PATCH 005/349] latest work --- Makefile | 7 ++++- pixie/stacklets.pxi | 71 +++++++++++++++++++++++++++++++++------------ pixie/vm/threads.py | 35 ++++++++++++++++++++++ 3 files changed, 93 insertions(+), 20 deletions(-) diff --git a/Makefile b/Makefile index e8f1c0a4..37645acb 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ all: help EXTERNALS=../externals -PYTHON ?= pypy +PYTHON ?= python PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy @@ -52,9 +52,14 @@ $(EXTERNALS)/pypy: run: ./pixie-vm + run_interactive: @PYTHONPATH=$(PYTHONPATH) $(PYTHON) target.py +run_interactive_stacklets: + @PYTHONPATH=$(PYTHONPATH) $(PYTHON) target.py pixie/stacklets.pxi + + run_built_tests: pixie-vm ./pixie-vm run-tests.pxi diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 4869c296..abf22e2b 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -58,15 +58,7 @@ (defmethod async-fn :yield [_ args k] - - (let [a (uv/uv_async_t) - cb (atom nil)] - (reset! cb (ffi-prep-callback uv/uv_async_cb - (fn [handle] - (uv/uv_close a close_cb) - (run-and-process k nil)))) - (uv/uv_async_init (uv/uv_default_loop) a @cb) - (uv/uv_async_send a))) + (add-item task-queue [k args])) ;;; Sleep @@ -116,18 +108,53 @@ (defuvfsfn read [file bufs nbufs offset] :result) (defuvfsfn close [file] :result)) + +(defprotocol IBlockingQueue + (add-item [this item]) + (remove-item [this])) + +(deftype BlockingQueue [items lock locked] + IBlockingQueue + (add-item [this item] + (enqueue items item) + (when @locked + (-release-lock lock) + (reset! locked false)) + (-yield-thread)) + (remove-item [this] + (when (empty? @items) + (reset! locked true) + (-acquire-lock lock true)) + (dequeue items))) + +(defn blocking-queue [] + (let [l (-create-lock)] + (-acquire-lock l true) + (->BlockingQueue (atom []) l (atom true)))) + +(def task-queue (blocking-queue)) + + + + (defn -with-stacklets [fn] (let [[h [op arg]] ((new-stacklet fn) nil)] (swap! thread-count inc) (async-fn op arg h) (loop [] - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT) - (let [tks @tasks] - (reset! tasks []) - (when (not (empty? tks)) - (doseq [[k args] tks] - (-run-and-process k args)) - (recur)))))) + (let [[k args] (remove-item task-queue)] + (-run-and-process k args) + (recur))))) + +(defn -with-stacklets [fn] + (let [new-s (new-stacklet fn) + [h [op arg]] (new-s nil)] + (loop [h h + op op + arg arg] + (if (not (= op :spawn-end)) + (let [[h [op arg]] (h nil)] + (recur h op arg)))))) (defmacro with-stacklets [& body] @@ -141,10 +168,16 @@ (println e)))))) - (with-stacklets (dotimes [x 10000] - (yield-control) - (println x))) + (yield-control) + (println x))) + +(comment + + + (dotimes [t 33] + (-thread (fn [] (dotimes [x 10000] + (println t x)))))) (comment (defn run-later [f] diff --git a/pixie/vm/threads.py b/pixie/vm/threads.py index 6d8404b9..d34b47b8 100644 --- a/pixie/vm/threads.py +++ b/pixie/vm/threads.py @@ -1,7 +1,10 @@ +from pixie.vm.object import Object, Type +from pixie.vm.primitives import true import rpython.rlib.rthread as rthread from pixie.vm.primitives import nil import rpython.rlib.rgil as rgil from pixie.vm.code import as_var +import pixie.vm.rt as rt from rpython.rlib.objectmodel import invoke_around_extcall @@ -55,6 +58,38 @@ def yield_thread(): do_yield_thread() return nil +# Locks + +class Lock(Object): + _type = Type(u"pixie.stdlib.Lock") + def __init__(self, ll_lock): + self._ll_lock = ll_lock + + def type(self): + return Lock._type + + +@as_var("-create-lock") +def _create_lock(): + return Lock(rthread.allocate_lock()) + +@as_var("-acquire-lock") +def _acquire_lock(self, no_wait): + assert isinstance(self, Lock) + return rt.wrap(self._ll_lock.acquire(no_wait == true)) + +@as_var("-acquire-lock-timed") +def _acquire_lock(self, ms): + assert isinstance(self, Lock) + return rt.wrap(self._ll_lock.acquire(ms.int_val())) + +@as_var("-release-lock") +def _release_lock(self): + assert isinstance(self, Lock) + return rt.wrap(self._ll_lock.release()) + + + ## From PYPY From e1c869ec1d643aaefcfb00ece5582a858532bf55 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 4 Mar 2015 21:14:19 -0700 Subject: [PATCH 006/349] well it seems stacklets work much better on Linux --- pixie/stacklets.pxi | 172 +++++++++++++++++++++++++------------------- pixie/stdlib.pxi | 5 ++ 2 files changed, 105 insertions(+), 72 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index abf22e2b..f6d9144d 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -39,16 +39,35 @@ (let [[h [op args]] (k args)] (async-fn op args h))) -(defn run-and-process [k args] - (swap! tasks conj [k args])) +(defn run-and-process [k] + (let [[h f] (k nil)] + (f h))) ;; Yield -(defn yield-control [] - (let [[h] (@stacklet-loop-h [:yield nil])] +(defn switch-back [f] + (let [[h] (@stacklet-loop-h f)] (reset! stacklet-loop-h h) nil)) +(defn -run-later [f] + (let [a (uv/uv_async_t) + cb (atom nil)] + (reset! cb (ffi-prep-callback uv/uv_async_cb + (fn [handle] + (try + (uv/uv_close a close_cb) + (-dispose! @cb) + (f) + (catch ex (println ex)))))) + (uv/uv_async_init (uv/uv_default_loop) a @cb) + (uv/uv_async_send a))) + + +(defn yield-control [] + (switch-back (fn [k] + (-run-later (partial run-and-process k))))) + (def close_cb (ffi-prep-callback uv/uv_close_cb (fn [handle] (pixie.ffi/free handle) @@ -67,17 +86,36 @@ (reset! stacklet-loop-h h) nil)) -(defmethod async-fn :sleep - ([f args k] - (let [cb (atom nil) - timer (uv/uv_timer_t)] - (reset! cb (ffi-prep-callback uv/uv_timer_cb - (fn [handle] - (run-and-process k nil) - (uv/uv_timer_stop timer) - (-dispose! @cb)))) - (uv/uv_timer_init (uv/uv_default_loop) timer) - (uv/uv_timer_start timer @cb args 0)))) +(defn sleep [ms] + (let [f (fn [k] + (let [cb (atom nil) + timer (uv/uv_timer_t)] + (reset! cb (ffi-prep-callback uv/uv_timer_cb + (fn [handle] + (try + (run-and-process k) + (uv/uv_timer_stop timer) + (-dispose! @cb) + (catch ex + (println ex)))))) + (uv/uv_timer_init (uv/uv_default_loop) timer) + (uv/uv_timer_start timer @cb ms 0)))] + (switch-back f))) + +(defn -spawn [start-fn] + (switch-back (fn [k] + (-run-later (fn [] + (run-and-process (new-stacklet start-fn)))) + (-run-later (partial run-and-process k))))) + +(defmacro spawn [& body] + `(-spawn (fn [h# _] + (try + (reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (switch-back (fn [_] nil))) + (catch e + (println e)))))) (defmacro defuvfsfn [nm args return] @@ -101,61 +139,12 @@ (uv/uv_fs_t) ~@args @cb#)))))) -(comment - ((var defuvfsfn) 'open '[path flags mode] :result) - - (defuvfsfn open [path flags mode] :result) - (defuvfsfn read [file bufs nbufs offset] :result) - (defuvfsfn close [file] :result)) - - -(defprotocol IBlockingQueue - (add-item [this item]) - (remove-item [this])) - -(deftype BlockingQueue [items lock locked] - IBlockingQueue - (add-item [this item] - (enqueue items item) - (when @locked - (-release-lock lock) - (reset! locked false)) - (-yield-thread)) - (remove-item [this] - (when (empty? @items) - (reset! locked true) - (-acquire-lock lock true)) - (dequeue items))) - -(defn blocking-queue [] - (let [l (-create-lock)] - (-acquire-lock l true) - (->BlockingQueue (atom []) l (atom true)))) - -(def task-queue (blocking-queue)) - - (defn -with-stacklets [fn] - (let [[h [op arg]] ((new-stacklet fn) nil)] - (swap! thread-count inc) - (async-fn op arg h) - (loop [] - (let [[k args] (remove-item task-queue)] - (-run-and-process k args) - (recur))))) - -(defn -with-stacklets [fn] - (let [new-s (new-stacklet fn) - [h [op arg]] (new-s nil)] - (loop [h h - op op - arg arg] - (if (not (= op :spawn-end)) - (let [[h [op arg]] (h nil)] - (recur h op arg)))))) - + (let [[h f] ((new-stacklet fn) nil)] + (f h) + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT))) (defmacro with-stacklets [& body] `(-with-stacklets @@ -163,14 +152,13 @@ (try (reset! stacklet-loop-h h#) (let [result# (do ~@body)] - (@stacklet-loop-h [:spawn-end result#])) + (switch-back (fn [_] nil))) (catch e (println e)))))) - -(with-stacklets (dotimes [x 10000] - (yield-control) - (println x))) +(with-stacklets + (dotimes [x (* 1024 10)] + (spawn 1))) (comment @@ -202,3 +190,43 @@ (do (run-later (cfn 10000)) (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT))) + + +(comment + ((var defuvfsfn) 'open '[path flags mode] :result) + + (defuvfsfn open [path flags mode] :result) + (defuvfsfn read [file bufs nbufs offset] :result) + (defuvfsfn close [file] :result)) + + +(comment + (defprotocol IBlockingQueue + (add-item [this item]) + (remove-item [this])) + + (deftype BlockingQueue [items lock locked] + IBlockingQueue + (add-item [this item] + (enqueue items item) + (when @locked + (-release-lock lock) + (reset! locked false)) + (-yield-thread)) + (remove-item [this] + (when (empty? @items) + (reset! locked true) + (-acquire-lock lock true)) + (dequeue items))) + + (defn blocking-queue [] + (let [l (-create-lock)] + (-acquire-lock l true) + (->BlockingQueue (atom []) l (atom true)))) + + (def task-queue (blocking-queue)) + + + + +) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 30ab4933..cb1a8beb 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2117,3 +2117,8 @@ Expands to calls to `extend-type`." `(-dispose! ~nm)) names) result#))) + + +(defn partial [f & args] + (fn [& args2] + (apply f (-> args vec (into args2))))) From df8214b84163e53ba20a5a5f4bb5842ae0d38608 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 6 Mar 2015 15:43:32 -0700 Subject: [PATCH 007/349] more work on libuv ffi, it's getting there --- pixie/ffi-infer.pxi | 41 ++++++++++++++++---------- pixie/stacklets.pxi | 70 ++++++++++++++++++++++++-------------------- pixie/uv.pxi | 16 ++++++++-- pixie/vm/libs/ffi.py | 29 ++++++++++++++---- 4 files changed, 100 insertions(+), 56 deletions(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 49578c20..cea11bc6 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -81,26 +81,30 @@ return 0; ;; To Ctype conversion -(defmulti edn-to-ctype :type) +(defmulti edn-to-ctype (fn [n _] + (:type n))) -(defn callback-type [{:keys [arguments returns]}] - `(ffi-callback ~(vec (map edn-to-ctype arguments)) ~(edn-to-ctype returns))) +(defn callback-type [{:keys [arguments returns]} in-struct?] + `(ffi-callback ~(vec (map (fn [x] (edn-to-ctype x in-struct?)) + arguments)) + ~(edn-to-ctype returns in-struct?))) (defmethod edn-to-ctype :pointer - [{:keys [of-type] :as ptr}] + [{:keys [of-type] :as ptr} in-struct?] (cond - (= of-type {:signed? true :size 1 :type :int}) 'pixie.stdlib/CCharP - (= (:type of-type) :function) (callback-type of-type) + (and (= of-type {:signed? true :size 1 :type :int}) + (not in-struct?)) 'pixie.stdlib/CCharP + (= (:type of-type) :function) (callback-type of-type in-struct?) :else 'pixie.stdlib/CVoidP)) (defmethod edn-to-ctype :float - [{:keys [size]}] + [{:keys [size]} _] (cond (= size 8) 'pixie.stdlib/CDouble :else (assert False "unknown type"))) (defmethod edn-to-ctype :void - [_] + [_ _] `pixie.stdlib/CVoid) (def int-types {[8 true] 'pixie.stdlib/CInt8 @@ -113,7 +117,7 @@ return 0; [64 false] 'pixie.stdlib/CUInt64}) (defmethod edn-to-ctype :int - [{:keys [size signed?] :as tp}] + [{:keys [size signed?] :as tp} _] (let [tp-found (get int-types [(* 8 size) signed?])] (assert tp-found (str "No type found for " tp)) tp-found)) @@ -132,33 +136,36 @@ return 0; [{:keys [name]} {:keys [type arguments returns]}] (assert (= type :function) (str name " is not infered to be a function")) `(def ~(symbol name) - (ffi-fn *library* ~name ~(vec (map edn-to-ctype arguments)) ~(edn-to-ctype returns)))) + (ffi-fn *library* ~name + ~(vec (map (fn [x] (edn-to-ctype x false)) + arguments)) + ~(edn-to-ctype returns false)))) (defmethod generate-code :raw-struct [{:keys [name members]} {:keys [size infered-members]}] `(def ~(symbol name) (pixie.ffi/c-struct ~name ~size [~@(map (fn [name {:keys [type offset]}] - `[~(keyword name) ~(edn-to-ctype type) ~offset]) + `[~(keyword name) ~(edn-to-ctype type true) ~offset]) members infered-members)]))) (defmethod generate-code :struct [{:keys [name members]} {:keys [size infered-members]}] `(def ~(symbol name) (pixie.ffi/c-struct ~name ~size [~@(map (fn [name {:keys [type offset]}] - `[~(keyword name) ~(edn-to-ctype type) ~offset]) + `[~(keyword name) ~(edn-to-ctype type true) ~offset]) members infered-members)]))) (defmethod generate-code :type [{:keys [name members]} {:keys [size infered-members]}] `(def ~(symbol name) (pixie.ffi/c-struct ~name ~size [~@(map (fn [name {:keys [type offset]}] - `[~(keyword name) ~(edn-to-ctype type) ~offset]) + `[~(keyword name) ~(edn-to-ctype type true) ~offset]) members infered-members)]))) (defmethod generate-code :callback [{:keys [name]} {:keys [of-type]}] `(def ~(symbol name) - ~(callback-type of-type))) + ~(callback-type of-type false))) (defn run-infer [config cmds] @@ -175,8 +182,10 @@ return 0; (apply str " " (interpose " " (:cxx-flags *config*))) " -o /tmp/a.out && /tmp/a.out") _ (println cmd-str) - result (read-string (io/run-command cmd-str))] - `(do ~@(map generate-code cmds result)))) + result (read-string (io/run-command cmd-str)) + gen (vec (map generate-code cmds result))] + (println gen) + `(do ~@gen))) (defn full-lib-name [library-name] (if (= library-name "c") diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index f6d9144d..b36bf6c9 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -39,16 +39,19 @@ (let [[h [op args]] (k args)] (async-fn op args h))) -(defn run-and-process [k] - (let [[h f] (k nil)] - (f h))) +(defn run-and-process + ([k] + (run-and-process k nil)) + ([k val] + (let [[h f] (k val)] + (f h)))) ;; Yield (defn switch-back [f] - (let [[h] (@stacklet-loop-h f)] + (let [[h val] (@stacklet-loop-h f)] (reset! stacklet-loop-h h) - nil)) + val)) (defn -run-later [f] (let [a (uv/uv_async_t) @@ -81,11 +84,6 @@ ;;; Sleep -(defn sleep [ms] - (let [[h] (@stacklet-loop-h [:sleep ms])] - (reset! stacklet-loop-h h) - nil)) - (defn sleep [ms] (let [f (fn [k] (let [cb (atom nil) @@ -102,6 +100,7 @@ (uv/uv_timer_start timer @cb ms 0)))] (switch-back f))) +;; Spawn (defn -spawn [start-fn] (switch-back (fn [k] (-run-later (fn [] @@ -119,26 +118,26 @@ (defmacro defuvfsfn [nm args return] - (let [kw (keyword (str "pixie.uv/" (name nm)))] - `(do (defn ~nm ~args - (let [[h# result#] (@stacklet-loop-h [~kw ~args])] - (reset! stacklet-loop-h h#) - result#)) - (defmethod async-fn ~kw - [f# ~args k# tasks#] - (let [cb# (atom nil)] - (reset! cb# (ffi-prep-callback uv/uv_fs_cb - (fn [req#] - (try - (enqueue tasks# [k# (~return (pixie.ffi/cast req# uv/uv_fs_t))]) - (uv/uv_fs_req_cleanup req#) - (-dispose! @cb#) - (catch e (println e)))))) - (~(symbol (str "pixie.uv/uv_fs_" (name nm))) - (uv/uv_default_loop) - (uv/uv_fs_t) - ~@args - @cb#)))))) + `(defn ~nm ~args + (let [f (fn [k#] + (let [cb# (atom nil)] + (reset! cb# (ffi-prep-callback uv/uv_fs_cb + (fn [req#] + (try + (run-and-process k# (~return (pixie.ffi/cast req# uv/uv_fs_t))) + (uv/uv_fs_req_cleanup req#) + (-dispose! @cb#) + (catch e (println e)))))) + (~(symbol (str "pixie.uv/uv_" (name nm))) + (uv/uv_default_loop) + (uv/uv_fs_t) + ~@args + @cb#)))] + (switch-back f)))) + +(defuvfsfn fs_open [path flags mode] :result) +(defuvfsfn fs_read [file bufs nbufs offset] :result) +(defuvfsfn fs_close [file] :result) (defn -with-stacklets [fn] @@ -157,8 +156,15 @@ (println e)))))) (with-stacklets - (dotimes [x (* 1024 10)] - (spawn 1))) + (let [f (fs_open "/tmp/foo.txt" uv/O_RDONLY uv/S_IRUSR) + b (uv/new-fs-buf 1024)] + (println (type (:base b))) + (let [err (fs_read f b 1 0)] + (println err) + (assert (pos? err))) + (dotimes [x 100] + (puts (str (char (pixie.ffi/unpack (:base b) x CUInt8))))) + (println "done"))) (comment diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 85079189..877274c5 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -1,7 +1,7 @@ (ns pixie.uv (require pixie.ffi-infer :as f)) -(f/with-config {:library "uv" +(f/with-config {:library "uv" :includes ["uv.h"]} (f/defconst UV_RUN_DEFAULT) (f/defconst UV_RUN_ONCE) @@ -115,6 +115,8 @@ (f/defcstruct uv_dirent_t [:name :type]) + (f/defcstruct uv_buf_t [:base :len]) + (f/defcfn uv_fs_req_cleanup) (f/defcfn uv_fs_close) (f/defcfn uv_fs_open) @@ -163,9 +165,19 @@ (f/defconst UV_E2BIG) (f/defconst UV_EACCES) + (f/defcfn uv_err_name) ; async (f/defcstruct uv_async_t []) (f/defccallback uv_async_cb) (f/defcfn uv_async_init) - (f/defcfn uv_async_send)) + (f/defcfn uv_async_send) + ) + + +(defn new-fs-buf [size] + (let [b (buffer size) + bt (uv_buf_t)] + (pixie.ffi/set! bt :base b) + (pixie.ffi/set! bt :len size) + bt)) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 33d43d8e..fdb17b1b 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -359,11 +359,28 @@ def ffi_get_value(self, ptr): return String(unicode(rffi.charp2str(casted[0]))) def ffi_set_value(self, ptr, val): - pnt = rffi.cast(rffi.CCHARPP, ptr) - utf8 = unicode_to_utf8(rt.name(val)) - raw = rffi.str2charp(utf8) - pnt[0] = raw - return CCharPToken(raw) + if isinstance(val, String): + pnt = rffi.cast(rffi.CCHARPP, ptr) + utf8 = unicode_to_utf8(rt.name(val)) + raw = rffi.str2charp(utf8) + pnt[0] = raw + return CCharPToken(raw) + elif isinstance(val, Buffer): + vpnt = rffi.cast(rffi.VOIDPP, ptr) + vpnt[0] = val.buffer() + elif isinstance(val, VoidP): + vpnt = rffi.cast(rffi.VOIDPP, ptr) + vpnt[0] = val.raw_data() + elif val is nil: + vpnt = rffi.cast(rffi.VOIDPP, ptr) + vpnt[0] = rffi.cast(rffi.VOIDP, 0) + elif isinstance(val, CStruct): + vpnt = rffi.cast(rffi.VOIDPP, ptr) + vpnt[0] = rffi.cast(rffi.VOIDP, val.raw_data()) + else: + print val + affirm(False, u"Cannot encode this type") + def ffi_size(self): return rffi.sizeof(rffi.CCHARP) @@ -642,7 +659,7 @@ def set_val(self, k, v): (tp, offset) = self._type.get_desc(k) if tp is None: - runtime_error(u"Invalid field name: " + rt.name(rt.str(tp))) + runtime_error(u"Invalid field name: " + rt.name(rt.str(k))) offset = rffi.ptradd(self._buffer, offset) tp.ffi_set_value(rffi.cast(rffi.VOIDP, offset), v) From e5bb1211477a165534f93faf806768104ad39516 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 6 Mar 2015 16:37:04 -0700 Subject: [PATCH 008/349] implemented promises --- pixie/stacklets.pxi | 122 +++++++++++++++++++++----------------------- 1 file changed, 59 insertions(+), 63 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index b36bf6c9..a2babc2a 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -7,48 +7,18 @@ (def stacklet-loop-h (atom nil)) -(def thread-count (atom 0)) -(defmulti async-fn (fn [f args k] f)) -(defmethod async-fn :spawn-end - [_ _ _] - (swap! thread-count dec) - (when (= @thread-count 0) - (uv/uv_stop (uv/uv_default_loop)))) - -(def tasks (atom [])) - -(defn enqueue [q itm] - ; TODO: Rewrite this crappy impl - (swap! q (fn [q] (vec (conj (seq q) itm))))) - -(defn dequeue [q] - (let [itm (ith @q -1)] - (swap! q pop) - itm)) - -(comment - (defn run-and-process [k args] - - (let [[h [op args]] (k args)] - (async-fn op args h)))) - -(defn -run-and-process [k args] - - (let [[h [op args]] (k args)] - (async-fn op args h))) +;; Yield (defn run-and-process ([k] (run-and-process k nil)) ([k val] - (let [[h f] (k val)] - (f h)))) - -;; Yield + (let [[h f] (k val)] + (f h)))) -(defn switch-back [f] +(defn call-cc [f] (let [[h val] (@stacklet-loop-h f)] (reset! stacklet-loop-h h) val)) @@ -68,20 +38,11 @@ (defn yield-control [] - (switch-back (fn [k] - (-run-later (partial run-and-process k))))) + (call-cc (fn [k] + (-run-later (partial run-and-process k))))) (def close_cb (ffi-prep-callback uv/uv_close_cb - (fn [handle] - (pixie.ffi/free handle) - ))) - -(def tasks (atom [])) - -(defmethod async-fn :yield - [_ args k] - (add-item task-queue [k args])) - + pixie.ffi/free)) ;;; Sleep (defn sleep [ms] @@ -98,21 +59,21 @@ (println ex)))))) (uv/uv_timer_init (uv/uv_default_loop) timer) (uv/uv_timer_start timer @cb ms 0)))] - (switch-back f))) + (call-cc f))) ;; Spawn (defn -spawn [start-fn] - (switch-back (fn [k] - (-run-later (fn [] - (run-and-process (new-stacklet start-fn)))) - (-run-later (partial run-and-process k))))) + (call-cc (fn [k] + (-run-later (fn [] + (run-and-process (new-stacklet start-fn)))) + (-run-later (partial run-and-process k))))) (defmacro spawn [& body] `(-spawn (fn [h# _] (try (reset! stacklet-loop-h h#) (let [result# (do ~@body)] - (switch-back (fn [_] nil))) + (call-cc (fn [_] nil))) (catch e (println e)))))) @@ -133,7 +94,7 @@ (uv/uv_fs_t) ~@args @cb#)))] - (switch-back f)))) + (call-cc f)))) (defuvfsfn fs_open [path flags mode] :result) (defuvfsfn fs_read [file bufs nbufs offset] :result) @@ -151,20 +112,55 @@ (try (reset! stacklet-loop-h h#) (let [result# (do ~@body)] - (switch-back (fn [_] nil))) + (call-cc (fn [_] nil))) (catch e (println e)))))) + + +(deftype Promise [val pending-callbacks delivered?] + IDeref + (-deref [self] + (if delivered? + val + (do + (call-cc (fn [k] + (swap! pending-callbacks conj + (fn [v] + (-run-later (partial run-and-process k v))))))))) + IFn + (-invoke [self v] + (assert (not delivered?) "Can only deliver a promise once") + (set-field! self :val v) + (println @pending-callbacks) + (doseq [f @pending-callbacks] + (f v)) + (reset! pending-callbacks nil) + nil)) + +(defn promise [] + (->Promise nil (atom []) false)) + (with-stacklets - (let [f (fs_open "/tmp/foo.txt" uv/O_RDONLY uv/S_IRUSR) - b (uv/new-fs-buf 1024)] - (println (type (:base b))) - (let [err (fs_read f b 1 0)] - (println err) - (assert (pos? err))) - (dotimes [x 100] - (puts (str (char (pixie.ffi/unpack (:base b) x CUInt8))))) - (println "done"))) + (let [p (promise)] + (spawn @p) + (spawn @p) + (spawn (p 42)) + @p)) + +(comment + + + (with-stacklets + (let [f (fs_open "/tmp/foo.txt" uv/O_RDONLY uv/S_IRUSR) + b (uv/new-fs-buf 1024)] + (println (type (:base b))) + (let [err (fs_read f b 1 0)] + (println err) + (assert (pos? err))) + (dotimes [x 100] + (puts (str (char (pixie.ffi/unpack (:base b) x CUInt8))))) + (println "done")))) (comment From 38271ac70f9f5b058d8a61087269b6bf592ad4cf Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sun, 8 Mar 2015 16:23:39 -0600 Subject: [PATCH 009/349] move blocking io code into ffi-blocking --- pixie/ffi-infer.pxi | 3 +- pixie/io.pxi | 140 ---------------------------------- pixie/stdlib.pxi | 23 ++++-- tests/pixie/tests/test-io.pxi | 2 +- 4 files changed, 17 insertions(+), 151 deletions(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index cea11bc6..9a2d54b3 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -1,5 +1,5 @@ (ns pixie.ffi-infer - (require pixie.io :as io)) + (require pixie.io-blocking :as io)) (defn -add-rel-path [rel] (swap! load-paths conj (str (first @load-paths) "/" rel))) @@ -184,7 +184,6 @@ return 0; _ (println cmd-str) result (read-string (io/run-command cmd-str)) gen (vec (map generate-code cmds result))] - (println gen) `(do ~@gen))) (defn full-lib-name [library-name] diff --git a/pixie/io.pxi b/pixie/io.pxi index 46524dbf..efb24575 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -9,7 +9,6 @@ (def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) (def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) - (defprotocol IInputStream (read-byte [this] "Read a single character") (read [this buffer len] "Reads multiple bytes into a buffer, returns the number of bytes read")) @@ -20,142 +19,3 @@ (defprotocol IClosable (close [this] "Closes the stream")) - -(def DEFAULT-BUFFER-SIZE 1024) - -(deftype FileStream [fp] - IInputStream - (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) - "Not enough capacity in the buffer") - (let [read-count (fread buffer 1 len fp)] - (set-buffer-count! buffer read-count) - read-count)) - (read-byte [this] - (fgetc buffer)) - IClosable - (close [this] - (fclose fp)) - IReduce - (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) - -(defn open-read - {:doc "Open a file for reading, returning a IInputStream" - :added "0.1"} - [filename] - (assert (string? filename) "Filename must be a string") - (->FileStream (fopen filename "r"))) - -(defn read-line - "Read one line from input-stream for each invocation. - nil when all lines have been read" - [input-stream] - (let [line-feed (into #{} (map int [\newline \return])) - buf (buffer 1)] - (loop [acc []] - (let [len (read input-stream buf 1)] - (cond - (and (pos? len) (not (line-feed (first buf)))) - (recur (conj acc (first buf))) - - (and (zero? len) (empty? acc)) nil - - :else (apply str (map char acc))))))) - -(defn line-seq - "Returns the lines of text from input-stream as a lazy sequence of strings. - input-stream must implement IInputStream" - [input-stream] - (when-let [line (read-line input-stream)] - (cons line (lazy-seq (line-seq input-stream))))) - -(deftype FileOutputStream [fp] - IOutputStream - (write-byte [this val] - (assert (integer? val) "Value must be a int") - (fputc val fp)) - (write [this buffer] - (fwrite buffer 1 (count buffer) fp)) - IClosable - (close [this] - (fclose fp))) - -(defn file-output-rf [filename] - (let [fp (->FileOutputStream (fopen filename "w"))] - (fn ([] 0) - ([cnt] (close fp) cnt) - ([cnt chr] - (assert (integer? chr)) - (let [written (write-byte fp chr)] - (if (= written 0) - (reduced cnt) - (+ cnt written))))))) - - -(defn spit [filename val] - (transduce (map int) - (file-output-rf filename) - (str val))) - -(defn slurp [filename] - (let [c (->FileStream (fopen filename "r")) - result (transduce - (map char) - string-builder - c)] - (close c) - result)) - -(deftype ProcessInputStream [fp] - IInputStream - (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) - "Not enough capacity in the buffer") - (let [read-count (fread buffer 1 len fp)] - (set-buffer-count! buffer read-count) - read-count)) - (read-byte [this] - (fgetc fp)) - IClosable - (close [this] - (pclose fp)) - IReduce - (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) - - -(defn popen-read - {:doc "Open a file for reading, returning a IInputStream" - :added "0.1"} - [command] - (assert (string? command) "Command must be a string") - (->ProcessInputStream (popen command "r"))) - - -(defn run-command [command] - (let [c (->ProcessInputStream (popen command "r")) - result (transduce - (map char) - string-builder - c)] - (close c) - result)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index cb1a8beb..0ac534da 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1075,12 +1075,6 @@ Creates new maps if the keys are not present." (pop-binding-frame!) ret)))) -(defmacro require [ns kw as-nm] - (assert (= kw :as) "Require expects :as as the second argument") - `(do (load-ns (quote ~ns)) - (assert (the-ns (quote ~ns)) (str "Couldn't find the namespace " (quote ~ns) " after loading the file")) - (refer-ns (this-ns-name) (the-ns (quote ~ns)) (quote ~as-nm)))) - (defmacro ns [nm & body] `(do (in-ns ~(keyword (name nm))) ~@body)) @@ -1137,7 +1131,7 @@ Creates new maps if the keys are not present." (protocol? @(resolve-in *ns* body)) [@(resolve-in *ns* body) (second res) (conj (third res) body)] - :else (throw (str "can only extend protocols or Object, not " body))) + :else (throw (str "can only extend protocols or Object, not " body " of type " (type body)))) (seq? body) (let [proto (first res) tbs (second res) pbs (third res)] (if (protocol? proto) [proto tbs (conj pbs body)] @@ -1869,9 +1863,11 @@ user => (refer 'pixie.string :exclude '(substring))" exclude (set (:exclude filters)) refers (if (= :all (:refer filters)) (keys nsmap) - (or (:refer filters) (:only filters) (keys nsmap)))] + (or (:refer filters) (:only filters)))] (when (and refers (not (satisfies? ISeqable refers))) (throw ":only/:refer must be a collection of symbols")) + (when-let [as (:as filters)] + (refer-ns *ns* ns-sym as)) (loop [syms (seq refers)] (if (not syms) nil @@ -1885,6 +1881,17 @@ user => (refer 'pixie.string :exclude '(substring))" (recur (next syms))))) nil)) + + +(defmacro require [ns & args] + `(do (load-ns (quote ~ns)) + (assert (the-ns (quote ~ns)) + (str "Couldn't find the namespace " (quote ~ns) " after loading the file")) + + (apply refer (quote [~ns ~@args])))) + + + (extend -iterator ISeq (fn [s] (loop [s s] (when s diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 36ffa040..86a238b8 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -1,6 +1,6 @@ (ns pixie.tests.test-io (require pixie.test :as t) - (require pixie.io :as io)) + (require pixie.io-blocking :as io)) (t/deftest test-file-reduction (let [f (io/open-read "tests/pixie/tests/test-io.txt")] From 249463e1c53baa51e97c0d83196de10118eeeab0 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 9 Mar 2015 07:06:10 -0600 Subject: [PATCH 010/349] async slurp implemented --- pixie/io-blocking.pxi | 153 +++++++++++++++++++++++++++++++++ pixie/io.pxi | 194 +++++++++++++++++++++++++++++++++++++----- pixie/stacklets.pxi | 36 ++------ pixie/streams.pxi | 21 +++++ target.py | 10 ++- 5 files changed, 363 insertions(+), 51 deletions(-) create mode 100644 pixie/io-blocking.pxi create mode 100644 pixie/streams.pxi diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi new file mode 100644 index 00000000..f5565373 --- /dev/null +++ b/pixie/io-blocking.pxi @@ -0,0 +1,153 @@ +(ns pixie.io-blocking + (require pixie.streams :as st :refer :all)) + + +(def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) +(def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) +(def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) +(def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) +(def fwrite (ffi-fn libc "fwrite" [CVoidP CInt CInt CVoidP] CInt)) +(def fclose (ffi-fn libc "fclose" [CVoidP] CInt)) +(def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) +(def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) + + + +(def DEFAULT-BUFFER-SIZE 1024) + +(deftype FileStream [fp] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [read-count (fread buffer 1 len fp)] + (set-buffer-count! buffer read-count) + read-count)) + (read-byte [this] + (fgetc buffer)) + IClosable + (close [this] + (fclose fp)) + IReduce + (-reduce [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc)))))) + +(defn open-read + {:doc "Open a file for reading, returning a IInputStream" + :added "0.1"} + [filename] + (assert (string? filename) "Filename must be a string") + (->FileStream (fopen filename "r"))) + +(defn read-line + "Read one line from input-stream for each invocation. + nil when all lines have been read" + [input-stream] + (let [line-feed (into #{} (map int [\newline \return])) + buf (buffer 1)] + (loop [acc []] + (let [len (read input-stream buf 1)] + (cond + (and (pos? len) (not (line-feed (first buf)))) + (recur (conj acc (first buf))) + + (and (zero? len) (empty? acc)) nil + + :else (apply str (map char acc))))))) + +(defn line-seq + "Returns the lines of text from input-stream as a lazy sequence of strings. + input-stream must implement IInputStream" + [input-stream] + (when-let [line (read-line input-stream)] + (cons line (lazy-seq (line-seq input-stream))))) + +(deftype FileOutputStream [fp] + IOutputStream + (write-byte [this val] + (assert (integer? val) "Value must be a int") + (fputc val fp)) + (write [this buffer] + (fwrite buffer 1 (count buffer) fp)) + IClosable + (close [this] + (fclose fp))) + +(defn file-output-rf [filename] + (let [fp (->FileOutputStream (fopen filename "w"))] + (fn ([] 0) + ([cnt] (close fp) cnt) + ([cnt chr] + (assert (integer? chr)) + (let [written (write-byte fp chr)] + (if (= written 0) + (reduced cnt) + (+ cnt written))))))) + + +(defn spit [filename val] + (transduce (map int) + (file-output-rf filename) + (str val))) + +(defn slurp [filename] + (let [c (->FileStream (fopen filename "r")) + result (transduce + (map char) + string-builder + c)] + (close c) + result)) + +(deftype ProcessInputStream [fp] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [read-count (fread buffer 1 len fp)] + (set-buffer-count! buffer read-count) + read-count)) + (read-byte [this] + (fgetc fp)) + IClosable + (close [this] + (pclose fp)) + IReduce + (-reduce [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc)))))) + + +(defn popen-read + {:doc "Open a file for reading, returning a IInputStream" + :added "0.1"} + [command] + (assert (string? command) "Command must be a string") + (->ProcessInputStream (popen command "r"))) + + +(defn run-command [command] + (let [c (->ProcessInputStream (popen command "r")) + result (transduce + (map char) + string-builder + c)] + (close c) + result)) diff --git a/pixie/io.pxi b/pixie/io.pxi index efb24575..c9e3ae8f 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,21 +1,173 @@ -(ns pixie.io) - -(def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) -(def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) -(def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) -(def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) -(def fwrite (ffi-fn libc "fwrite" [CVoidP CInt CInt CVoidP] CInt)) -(def fclose (ffi-fn libc "fclose" [CVoidP] CInt)) -(def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) -(def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) - -(defprotocol IInputStream - (read-byte [this] "Read a single character") - (read [this buffer len] "Reads multiple bytes into a buffer, returns the number of bytes read")) - -(defprotocol IOutputStream - (write-byte [this byte]) - (write [this buffer])) - -(defprotocol IClosable - (close [this] "Closes the stream")) +(ns pixie.io + (require pixie.streams :as st :refer :all) + (require pixie.uv :as uv) + (require pixie.stacklets :as st)) + +(defmacro defuvfsfn [nm args return] + `(defn ~nm ~args + (let [f (fn [k#] + (let [cb# (atom nil)] + (reset! cb# (ffi-prep-callback uv/uv_fs_cb + (fn [req#] + (try + (st/run-and-process k# (~return (pixie.ffi/cast req# uv/uv_fs_t))) + (uv/uv_fs_req_cleanup req#) + (-dispose! @cb#) + (catch e (println e)))))) + (~(symbol (str "pixie.uv/uv_" (name nm))) + (uv/uv_default_loop) + (uv/uv_fs_t) + ~@args + @cb#)))] + (st/call-cc f)))) + +(defuvfsfn fs_open [path flags mode] :result) +(defuvfsfn fs_read [file bufs nbufs offset] :result) +(defuvfsfn fs_close [file] :result) + + +(def DEFAULT-BUFFER-SIZE 1024) + +(deftype FileStream [fp offset uvbuf] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [_ (pixie.ffi/set! uvbuf :base buffer) + _ (pixie.ffi/set! uvbuf :len (buffer-capacity buffer)) + read-count (fs_read fp uvbuf 1 offset)] + (assert (not (neg? read-count)) "Read Error") + (set-field! this :offset (+ offset read-count)) + (set-buffer-count! buffer read-count) + read-count)) + (read-byte [this] + (assert false "Does not support read-byte, wrap in a buffering reader")) + IClosable + (close [this] + (pixie.ffi/free uvbuf) + (fs_close fp)) + IReduce + (-reduce [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc)))))) + +(defn open-read + {:doc "Open a file for reading, returning a IInputStream" + :added "0.1"} + [filename] + (assert (string? filename) "Filename must be a string") + (->FileStream (fs_open filename uv/O_RDONLY 0) 0 (uv/uv_buf_t))) + +(defn read-line + "Read one line from input-stream for each invocation. + nil when all lines have been read" + [input-stream] + (let [line-feed (into #{} (map int [\newline \return])) + buf (buffer 1)] + (loop [acc []] + (let [len (read input-stream buf 1)] + (cond + (and (pos? len) (not (line-feed (first buf)))) + (recur (conj acc (first buf))) + + (and (zero? len) (empty? acc)) nil + + :else (apply str (map char acc))))))) + +(defn line-seq + "Returns the lines of text from input-stream as a lazy sequence of strings. + input-stream must implement IInputStream" + [input-stream] + (when-let [line (read-line input-stream)] + (cons line (lazy-seq (line-seq input-stream))))) + +(deftype FileOutputStream [fp] + IOutputStream + (write-byte [this val] + (assert (integer? val) "Value must be a int") + (fputc val fp)) + (write [this buffer] + (fwrite buffer 1 (count buffer) fp)) + IClosable + (close [this] + (fclose fp))) + +(defn file-output-rf [filename] + (let [fp (->FileOutputStream (fopen filename "w"))] + (fn ([] 0) + ([cnt] (close fp) cnt) + ([cnt chr] + (assert (integer? chr)) + (let [written (write-byte fp chr)] + (if (= written 0) + (reduced cnt) + (+ cnt written))))))) + + +(defn spit [filename val] + (transduce (map int) + (file-output-rf filename) + (str val))) + +(defn slurp [filename] + (let [c (open-read filename) + result (transduce + (map char) + string-builder + c)] + (close c) + result)) + +(println (slurp "/tmp/a.txt")) + +(deftype ProcessInputStream [fp] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [read-count (fread buffer 1 len fp)] + (set-buffer-count! buffer read-count) + read-count)) + (read-byte [this] + (fgetc fp)) + IClosable + (close [this] + (pclose fp)) + IReduce + (-reduce [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc)))))) + + +(defn popen-read + {:doc "Open a file for reading, returning a IInputStream" + :added "0.1"} + [command] + (assert (string? command) "Command must be a string") + (->ProcessInputStream (popen command "r"))) + + +(defn run-command [command] + (let [c (->ProcessInputStream (popen command "r")) + result (transduce + (map char) + string-builder + c)] + (close c) + result)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index a2babc2a..ab101bb2 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -78,27 +78,6 @@ (println e)))))) -(defmacro defuvfsfn [nm args return] - `(defn ~nm ~args - (let [f (fn [k#] - (let [cb# (atom nil)] - (reset! cb# (ffi-prep-callback uv/uv_fs_cb - (fn [req#] - (try - (run-and-process k# (~return (pixie.ffi/cast req# uv/uv_fs_t))) - (uv/uv_fs_req_cleanup req#) - (-dispose! @cb#) - (catch e (println e)))))) - (~(symbol (str "pixie.uv/uv_" (name nm))) - (uv/uv_default_loop) - (uv/uv_fs_t) - ~@args - @cb#)))] - (call-cc f)))) - -(defuvfsfn fs_open [path flags mode] :result) -(defuvfsfn fs_read [file bufs nbufs offset] :result) -(defuvfsfn fs_close [file] :result) (defn -with-stacklets [fn] @@ -116,6 +95,9 @@ (catch e (println e)))))) +(defn run-with-stacklets [f] + (with-stacklets + (f))) (deftype Promise [val pending-callbacks delivered?] @@ -141,12 +123,12 @@ (defn promise [] (->Promise nil (atom []) false)) -(with-stacklets - (let [p (promise)] - (spawn @p) - (spawn @p) - (spawn (p 42)) - @p)) +(comment (with-stacklets + (let [p (promise)] + (spawn @p) + (spawn @p) + (spawn (p 42)) + @p))) (comment diff --git a/pixie/streams.pxi b/pixie/streams.pxi new file mode 100644 index 00000000..b037be76 --- /dev/null +++ b/pixie/streams.pxi @@ -0,0 +1,21 @@ +(ns pixie.streams) + +(def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) +(def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) +(def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) +(def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) +(def fwrite (ffi-fn libc "fwrite" [CVoidP CInt CInt CVoidP] CInt)) +(def fclose (ffi-fn libc "fclose" [CVoidP] CInt)) +(def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) +(def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) + +(defprotocol IInputStream + (read-byte [this] "Read a single character") + (read [this buffer len] "Reads multiple bytes into a buffer, returns the number of bytes read")) + +(defprotocol IOutputStream + (write-byte [this byte]) + (write [this buffer])) + +(defprotocol IClosable + (close [this] "Closes the stream")) diff --git a/target.py b/target.py index c1726876..a1219674 100644 --- a/target.py +++ b/target.py @@ -177,12 +177,16 @@ def run_load_stdlib(): return rt.load_ns(rt.wrap(u"pixie/stdlib.pxi")) + rt.load_ns(rt.wrap(u"pixie/stacklets.pxi")) stdlib_loaded.set_true() def load_stdlib(): run_load_stdlib.invoke([]) +from pixie.vm.code import intern_var +run_with_stacklets = intern_var(u"pixie.stacklets", u"run-with-stacklets") + def entry_point(args): try: import pixie.vm.stacklet @@ -216,7 +220,7 @@ def entry_point(args): i += 1 if i < len(args): expr = args[i] - EvalFn(expr).invoke([]) + run_with_stacklets.invoke([EvalFn(expr)]) return 0 else: print "Expected argument for " + arg @@ -252,9 +256,9 @@ def entry_point(args): if not exit: if interactive: - ReplFn(args).invoke([]) + run_with_stacklets.invoke([ReplFn(args)]) else: - BatchModeFn(script_args).invoke([]) + run_with_stacklets.invoke([BatchModeFn(script_args)]) except WrappedException as we: print we._ex.__repr__() From 9490bb14b10404ffc2f135353949f394e0ffd34d Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 9 Mar 2015 15:52:32 -0600 Subject: [PATCH 011/349] updated spit to use async io --- pixie/io.pxi | 63 +++++++++++++++++++++++++++++------ tests/pixie/tests/test-io.pxi | 5 ++- 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index c9e3ae8f..b537d04f 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -23,6 +23,7 @@ (defuvfsfn fs_open [path flags mode] :result) (defuvfsfn fs_read [file bufs nbufs offset] :result) +(defuvfsfn fs_write [file bufs nbufs offset] :result) (defuvfsfn fs_close [file] :result) @@ -59,6 +60,7 @@ @result)) acc)))))) + (defn open-read {:doc "Open a file for reading, returning a IInputStream" :added "0.1"} @@ -66,6 +68,7 @@ (assert (string? filename) "Filename must be a string") (->FileStream (fs_open filename uv/O_RDONLY 0) 0 (uv/uv_buf_t))) + (defn read-line "Read one line from input-stream for each invocation. nil when all lines have been read" @@ -89,27 +92,65 @@ (when-let [line (read-line input-stream)] (cons line (lazy-seq (line-seq input-stream))))) -(deftype FileOutputStream [fp] +(deftype FileOutputStream [fp offset uvbuf] IOutputStream (write-byte [this val] - (assert (integer? val) "Value must be a int") - (fputc val fp)) + (assert false)) (write [this buffer] - (fwrite buffer 1 (count buffer) fp)) + (let [_ (pixie.ffi/set! uvbuf :base buffer) + _ (pixie.ffi/set! uvbuf :len (count buffer)) + write-count (fs_write fp uvbuf 1 offset)] + (when (neg? write-count) + (throw (uv/uv_err_name read-count))) + (assert (= write-count (count buffer)) (str "Write error!" write-count " " (count buffer))) + (set-field! this :offset (+ offset write-count)) + (set-buffer-count! buffer write-count) + write-count)) IClosable (close [this] (fclose fp))) +(deftype BufferedOutputStream [downstream idx buffer] + IOutputStream + (write-byte [this val] + (pixie.ffi/pack! buffer idx CUInt8 val) + (set-field! this :idx (inc idx)) + (when (= idx (buffer-capacity buffer)) + (write downstream buffer) + (set-field this :idx 0))) + IClosable + (close [this] + (set-buffer-count! buffer idx) + (write downstream buffer))) + +(defn buffered-output-stream [downstream size] + (->BufferedOutputStream downstream 0 (buffer size))) + + +(defn throw-on-error [result] + (when (neg? result) + (throw (uv/uv_err_name result))) + result) + +(defn open-write + {:doc "Open a file for reading, returning a IInputStream" + :added "0.1"} + [filename] + (assert (string? filename) "Filename must be a string") + (->FileOutputStream (throw-on-error (fs_open filename uv/O_WRONLY 0)) + 0 + (uv/uv_buf_t))) + + (defn file-output-rf [filename] - (let [fp (->FileOutputStream (fopen filename "w"))] + (let [fp (buffered-output-stream (open-write filename) + DEFAULT-BUFFER-SIZE)] (fn ([] 0) - ([cnt] (close fp) cnt) - ([cnt chr] + ([_] (close fp) nil) + ([_ chr] (assert (integer? chr)) - (let [written (write-byte fp chr)] - (if (= written 0) - (reduced cnt) - (+ cnt written))))))) + (write-byte fp chr) + nil)))) (defn spit [filename val] diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 86a238b8..e3f80fa3 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -1,6 +1,6 @@ (ns pixie.tests.test-io (require pixie.test :as t) - (require pixie.io-blocking :as io)) + (require pixie.io :as io)) (t/deftest test-file-reduction (let [f (io/open-read "tests/pixie/tests/test-io.txt")] @@ -24,8 +24,7 @@ s (io/line-seq f)] (t/assert= (last s) "Second line."))) -(comment + (t/deftest test-slurp-spit (let [val (vec (range 128))] (t/assert= val (read-string (io/slurp "test.tmp" (io/spit "test.tmp" val)))))) -) From 37d50af42ea69a53ef8e5790e17add180f8c8804 Mon Sep 17 00:00:00 2001 From: Igor Vuk Date: Mon, 9 Mar 2015 23:48:58 +0100 Subject: [PATCH 012/349] Fix typos in README.md, remove trailing spaces --- README.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 39110fb4..0f587afb 100644 --- a/README.md +++ b/README.md @@ -51,25 +51,25 @@ Pixie now comes with a build tool called [dust](https://github.com/pixie-lang/du ### So this is written in Python? -It's actually written in the RPython, the same language PyPy is written in. `make build_with_jit` will compile Pixie using the PyPy toolchain. After some time, it will produce an executable called `pixie-vm` this executable is a full blown native interpreter with a JIT, GC, etc. So yes, the guts are written in RPython, just like the guts of most lisp interpreters are written in C. At runtime the only thing that is interpreted is the Pixie bytecode, that is until the JIT kicks in... +It's actually written in the RPython, the same language PyPy is written in. `make build_with_jit` will compile Pixie using the PyPy toolchain. After some time, it will produce an executable called `pixie-vm`. This executable is a full blown native interpreter with a JIT, GC, etc. So yes, the guts are written in RPython, just like the guts of most lisp interpreters are written in C. At runtime the only thing that is interpreted is the Pixie bytecode, that is until the JIT kicks in... ### What's this bit about "magical powers"? -First of all, the word "magic" is in quotes as it's partly a play on words, pixies are small, light and often considered to have magical powers. +First of all, the word "magic" is in quotes as it's partly a play on words, pixies are small, light and often considered to have magical powers. -However there are a few features of pixie that although may not be uncommon, are perhaps unexpected from a lisp. +However there are a few features of pixie that although may not be uncommon, are perhaps unexpected from a lisp. -* Pixie implements its own virtual machine. It does not run on the JVM, CLR or Python VM. It implements its own bytecode, has its own GC and JIT. And it's small. Currently the interpreter, JIT, GC, and stdlib clock in at about 5.5MB once compiled down to an executable. +* Pixie implements its own virtual machine. It does not run on the JVM, CLR or Python VM. It implements its own bytecode, has its own GC and JIT. And it's small. Currently the interpreter, JIT, GC, and stdlib clock in at about 5.5MB once compiled down to an executable. -* The JIT makes some things fast. Very fast. Code like the following compiles down to a loop with 6 CPU instructions. While this may not be too impressive for any language that uses a tracing jit, it is fairly unique for a language as young as Pixie. +* The JIT makes some things fast. Very fast. Code like the following compiles down to a loop with 6 CPU instructions. While this may not be too impressive for any language that uses a tracing jit, it is fairly unique for a language as young as Pixie. ```clojure (comment - This code adds up to 10000 from 0 via calling a function that takes a variable number of arguments. + This code adds up to 10000 from 0 via calling a function that takes a variable number of arguments. That function then reduces over the argument list to add up all given arguments.) - + (defn add-fn [& args] (reduce -add 0 args)) @@ -77,12 +77,12 @@ However there are a few features of pixie that although may not be uncommon, are (if (eq x 10000) x (recur (add-fn x 1)))) - + ``` - - -* Math system is fully polymorphic. Math primitives (+,-, etc.) are built off of polymorphic functions that dispatch on the types of the first two arguments. This allows the math system to be extended to complex numbers, matricies, etc. The performance penalty of such a polymorphic call is completely removed by the RPython generated JIT. + + +* Math system is fully polymorphic. Math primitives (+,-, etc.) are built off of polymorphic functions that dispatch on the types of the first two arguments. This allows the math system to be extended to complex numbers, matrices, etc. The performance penalty of such a polymorphic call is completely removed by the RPython generated JIT. (Planned "magical" Features) @@ -90,21 +90,21 @@ However there are a few features of pixie that although may not be uncommon, are * STM for parallelism. Once STM gets merged into the mainline branch of PyPy, we'll adopt it pretty quickly. -* CSP for concurrency. We already have stacklets, it's not that hard to use them for CSP style concurrency as well. +* CSP for concurrency. We already have stacklets, it's not that hard to use them for CSP style concurrency as well. ## Where do the devs hangout? Mostly on FreeNode at `#pixie-lang` stop by and say "hello". ## Contributing -We have a very open contribution process. If you have a feature you'd like to implement, submit a PR or file an issue and we'll see what we can do. Most PRs are either rejected (if there is a techincal flaw) or accepted within a day, so send an improvement our way and see what happens. +We have a very open contribution process. If you have a feature you'd like to implement, submit a PR or file an issue and we'll see what we can do. Most PRs are either rejected (if there is a technical flaw) or accepted within a day, so send an improvement our way and see what happens. ## Implementation Notes Although parts of the language may be very close to Clojure (they are both lisps after all), language parity is not a design goal. We will take the features from Clojure or other languages that are suitable to our needs, and feel free to reject those that aren't. Therefore this should not be considered a "Clojure Dialect", but instead a "Clojure inspired lisp". ## Disclaimer -This project is the personal work of Timothy Baldridge and contributors. It is not supported by any entity, including Timothy's employer, or any employers of any other contributors. +This project is the personal work of Timothy Baldridge and contributors. It is not supported by any entity, including Timothy's employer, or any employers of any other contributors. ## Copying From 22686acb95852721fcc137b735bd1ef49925d4d1 Mon Sep 17 00:00:00 2001 From: Igor Vuk Date: Mon, 9 Mar 2015 23:50:46 +0100 Subject: [PATCH 013/349] Fix typo: example -> examples --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f587afb..2cda23c1 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Some planned and implemented features: ## Examples -There are example in the /examples directory. +There are examples in the /examples directory. Try out "Hello World" with: ./examples/hello-world.pxi From 4db301f9a713139ccfb7968dcb93f5d70a26bded Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 9 Mar 2015 21:43:26 -0600 Subject: [PATCH 014/349] more work on spit --- pixie/io.pxi | 26 +++++++++++++++----------- pixie/vm/libs/ffi.py | 5 +++++ tests/pixie/tests/test-io.pxi | 2 +- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index b537d04f..2f20749e 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,7 +1,8 @@ (ns pixie.io (require pixie.streams :as st :refer :all) (require pixie.uv :as uv) - (require pixie.stacklets :as st)) + (require pixie.stacklets :as st) + (require pixie.ffi :as ffi)) (defmacro defuvfsfn [nm args return] `(defn ~nm ~args @@ -97,15 +98,18 @@ (write-byte [this val] (assert false)) (write [this buffer] - (let [_ (pixie.ffi/set! uvbuf :base buffer) - _ (pixie.ffi/set! uvbuf :len (count buffer)) - write-count (fs_write fp uvbuf 1 offset)] - (when (neg? write-count) - (throw (uv/uv_err_name read-count))) - (assert (= write-count (count buffer)) (str "Write error!" write-count " " (count buffer))) - (set-field! this :offset (+ offset write-count)) - (set-buffer-count! buffer write-count) - write-count)) + (loop [buffer-offset 0] + (let [_ (pixie.ffi/set! uvbuf :base (ffi/ptr-add buffer buffer-offset)) + _ (pixie.ffi/set! uvbuf :len (- (count buffer) buffer-offset)) + write-count (fs_write fp uvbuf 1 (get-field this :offset))] + (println "offset " offset) + (when (neg? write-count) + (throw (uv/uv_err_name read-count))) + (assert (= write-count (count buffer)) (str "Write error!" write-count " " (count buffer))) + (set-field! this :offset (+ (get-field this :offset) write-count)) + (if (< (+ buffer-offset write-count) (count buffer)) + (recur (+ buffer-offset write-count)) + write-count)))) IClosable (close [this] (fclose fp))) @@ -117,7 +121,7 @@ (set-field! this :idx (inc idx)) (when (= idx (buffer-capacity buffer)) (write downstream buffer) - (set-field this :idx 0))) + (set-field! this :idx 0))) IClosable (close [this] (set-buffer-count! buffer idx) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index fdb17b1b..48ff27db 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -473,6 +473,11 @@ def pack(ptr, offset, tp, val): tp.ffi_set_value(ptr, val) return nil +@as_var(u"pixie.ffi", u"ptr-add") +def pack(ptr, offset): + affirm(isinstance(ptr, VoidP) or isinstance(ptr, Buffer) or isinstance(ptr, CStruct), u"Type is not unpackable") + ptr = rffi.ptradd(ptr.raw_data(), offset.int_val()) + return VoidP(ptr) class CStructType(object.Type): base_type = object.Type(u"pixie.ffi.CStruct") diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index e3f80fa3..09684e76 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -26,5 +26,5 @@ (t/deftest test-slurp-spit - (let [val (vec (range 128))] + (let [val (vec (range 1280))] (t/assert= val (read-string (io/slurp "test.tmp" (io/spit "test.tmp" val)))))) From 2cc2469f72e638032c097590c7262091497f953e Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 9 Mar 2015 22:34:43 -0600 Subject: [PATCH 015/349] fixed mutable fields --- pixie/stdlib.pxi | 17 ++++++++++------ pixie/vm/compiler.py | 31 ++++++++++++++++++++++++++++- tests/pixie/tests/test-compiler.pxi | 15 ++++++++++++++ 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index fe3db177..4746ebac 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1128,12 +1128,17 @@ Creates new maps if the keys are not present." (seq? args)) "protocol override must have arguments") self-arg (first args) _ (assert (symbol? self-arg) "protocol override must have at least one `self' argument") - field-lets (transduce (comp (map (fn [f] - [(symbol (name f)) (list 'get-field self-arg f)])) - cat) - conj fields) - rest (next (next body))] - `(fn ~fn-name ~args (let ~field-lets ~@rest)))) + + rest (next (next body)) + body (reduce + (fn [body f] + `[(local-macro [~(symbol (name f)) + (get-field ~self-arg ~(keyword (name f)))] + ~@body)]) + rest + fields)] + (println body) + `(fn ~fn-name ~args ~@body))) bodies (reduce (fn [res body] (cond diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index afd06a1a..b17b3b4f 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -245,6 +245,13 @@ def emit(self, ctx): ctx.bytecode.append(self.idx) ctx.add_sp(1) +class LocalMacro(LocalType): + def __init__(self, form): + self._from = form + + def emit(self, ctx): + compile_form(self._from, ctx) + @@ -747,6 +754,27 @@ def compile_in_ns(form, ctx): NS_VAR.deref().include_stdlib() compile_fn_call(form, ctx) +def compile_local_macro(form, ctx): + form = rt.next(form) + binding = rt.first(form) + body = rt.next(form) + + sym = rt.nth(binding, rt.wrap(0)) + bind_form = rt.nth(binding, rt.wrap(1)) + + ctx.add_local(rt.name(sym), LocalMacro(bind_form)) + + while True: + compile_form(rt.first(body), ctx) + body = rt.next(body) + + if body is nil: + break + else: + ctx.pop() + + ctx.pop_locals() + builtins = {u"fn*": compile_fn, u"if": compile_if, u"def": compile_def, @@ -760,7 +788,8 @@ def compile_in_ns(form, ctx): u"catch": compile_catch, u"this-ns-name": compile_this_ns, u"in-ns": compile_in_ns, # yes, this is both a function and a compiler special form. - u"yield": compile_yield} + u"yield": compile_yield, + u"local-macro": compile_local_macro} def compiler_special(s): if isinstance(s, symbol.Symbol): diff --git a/tests/pixie/tests/test-compiler.pxi b/tests/pixie/tests/test-compiler.pxi index 052bafe2..944343d4 100644 --- a/tests/pixie/tests/test-compiler.pxi +++ b/tests/pixie/tests/test-compiler.pxi @@ -20,3 +20,18 @@ (t/deftest test-lists (t/assert= (vec '()) []) (t/assert= (vec '()) ())) + + +(defprotocol IMutable + (mutate! [this])) + +(deftype Foo [x] + IMutable + (mutate! [this] + (let [xold x] + (set-field! this :x 42) + (t/assert (not (= xold x))) + (t/assert (= x 42))))) + +(t/deftest test-deftype-mutables + (mutate! (->Foo 0))) From 7be556ee6b04437151745eeaf8c24227d1274a2e Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 10 Mar 2015 06:04:40 -0600 Subject: [PATCH 016/349] how about we don't check in debug code --- pixie/stdlib.pxi | 1 - 1 file changed, 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4746ebac..1cfb420c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1137,7 +1137,6 @@ Creates new maps if the keys are not present." ~@body)]) rest fields)] - (println body) `(fn ~fn-name ~args ~@body))) bodies (reduce (fn [res body] From 301b7efaf2c5d83f333f9c38164207c2b9c8faf6 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 10 Mar 2015 06:36:10 -0600 Subject: [PATCH 017/349] fix async version of spit --- pixie/io.pxi | 11 +++++++---- pixie/uv.pxi | 2 ++ tests/pixie/tests/test-io.pxi | 3 ++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 2f20749e..4d197916 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -101,12 +101,12 @@ (loop [buffer-offset 0] (let [_ (pixie.ffi/set! uvbuf :base (ffi/ptr-add buffer buffer-offset)) _ (pixie.ffi/set! uvbuf :len (- (count buffer) buffer-offset)) - write-count (fs_write fp uvbuf 1 (get-field this :offset))] - (println "offset " offset) + write-count (fs_write fp uvbuf 1 offset)] + (println "offset " offset write-count buffer-offset (count buffer)) (when (neg? write-count) (throw (uv/uv_err_name read-count))) (assert (= write-count (count buffer)) (str "Write error!" write-count " " (count buffer))) - (set-field! this :offset (+ (get-field this :offset) write-count)) + (set-field! this :offset (+ offset write-count)) (if (< (+ buffer-offset write-count) (count buffer)) (recur (+ buffer-offset write-count)) write-count)))) @@ -120,6 +120,7 @@ (pixie.ffi/pack! buffer idx CUInt8 val) (set-field! this :idx (inc idx)) (when (= idx (buffer-capacity buffer)) + (set-buffer-count! buffer (buffer-capacity buffer)) (write downstream buffer) (set-field! this :idx 0))) IClosable @@ -141,7 +142,9 @@ :added "0.1"} [filename] (assert (string? filename) "Filename must be a string") - (->FileOutputStream (throw-on-error (fs_open filename uv/O_WRONLY 0)) + (->FileOutputStream (throw-on-error (fs_open filename + (bit-or uv/O_WRONLY uv/O_CREAT) + uv/S_IRWXU)) 0 (uv/uv_buf_t))) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 877274c5..90bb127f 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -159,6 +159,8 @@ (f/defconst O_CREAT) (f/defconst S_IRUSR) + (f/defconst S_IRWXU) + (f/defconst S_IWUSR) ; ERRNO diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 09684e76..ec4dee02 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -27,4 +27,5 @@ (t/deftest test-slurp-spit (let [val (vec (range 1280))] - (t/assert= val (read-string (io/slurp "test.tmp" (io/spit "test.tmp" val)))))) + (io/spit "test.tmp" val) + (t/assert= val (read-string (io/slurp "test.tmp"))))) From 62cbd153368a45977845d040b44545b67550a54e Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 10 Mar 2015 06:36:52 -0600 Subject: [PATCH 018/349] fix async version of spit --- pixie/io.pxi | 2 -- 1 file changed, 2 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 4d197916..228f8944 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -102,10 +102,8 @@ (let [_ (pixie.ffi/set! uvbuf :base (ffi/ptr-add buffer buffer-offset)) _ (pixie.ffi/set! uvbuf :len (- (count buffer) buffer-offset)) write-count (fs_write fp uvbuf 1 offset)] - (println "offset " offset write-count buffer-offset (count buffer)) (when (neg? write-count) (throw (uv/uv_err_name read-count))) - (assert (= write-count (count buffer)) (str "Write error!" write-count " " (count buffer))) (set-field! this :offset (+ offset write-count)) (if (< (+ buffer-offset write-count) (count buffer)) (recur (+ buffer-offset write-count)) From 76538053a0ada7ea14f1d170c621f984032a7532 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 10 Mar 2015 16:35:25 -0600 Subject: [PATCH 019/349] fixed compilation error with stacklets --- pixie/io.pxi | 2 -- pixie/stacklets.pxi | 8 ++++---- pixie/vm/stdlib.py | 4 ++++ target.py | 11 ++++++++++- tests/pixie/tests/test-io.pxi | 1 - 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 228f8944..cc76046c 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -172,8 +172,6 @@ (close c) result)) -(println (slurp "/tmp/a.txt")) - (deftype ProcessInputStream [fp] IInputStream (read [this buffer len] diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index ab101bb2..0f60d989 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -1,11 +1,11 @@ (ns pixie.stacklets (require pixie.uv :as uv)) -;; LibUV seems to act up when we invoke a stacklet from inside a callbac -;; so we compensate by simply storing the stacklets in a task queue -;; and calling them later outside of the libuv loop. +;; If we don't do this, compiling this file doesn't work since the def will clear out +;; the existing value. -(def stacklet-loop-h (atom nil)) +(if (undefined? (var stacklet-loop-h)) + (def stacklet-loop-h (atom nil))) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 07fdb380..b139cb3f 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -363,6 +363,10 @@ def eval(form): val = interpret(compile(form)) return val +@as_var("undefined?") +def is_undefined(var): + return rt.wrap(not var.is_defined()) + @as_var("load-ns") def load_ns(filename): import pixie.vm.string as string diff --git a/target.py b/target.py index a1219674..d7f7ca3d 100644 --- a/target.py +++ b/target.py @@ -156,6 +156,15 @@ def inner_invoke(self, args): rt.load_reader(StringReader(unicode_from_utf8(self._expr))) +class CompileFileFn(NativeFn): + def __init__(self, filename): + self._filename = filename + + def inner_invoke(self, args): + import pixie.vm.rt as rt + + rt.compile_file(rt.wrap(self._filename)) + class IsPreloadFlag(object): def __init__(self): @@ -239,7 +248,7 @@ def entry_point(args): if i < len(args): path = args[i] print "Compiling ", path - rt.compile_file(rt.wrap(path)) + run_with_stacklets.invoke([CompileFileFn(path)]) exit = True else: print "Expected argument for " + arg diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index ec4dee02..09de53e3 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -24,7 +24,6 @@ s (io/line-seq f)] (t/assert= (last s) "Second line."))) - (t/deftest test-slurp-spit (let [val (vec (range 1280))] (io/spit "test.tmp" val) From 9d99cdd479bf026d7d7b01e4d7b60905d3810825 Mon Sep 17 00:00:00 2001 From: Peter Monks Date: Tue, 10 Mar 2015 15:35:47 -0700 Subject: [PATCH 020/349] Working on issue #218. Code works (with fully qualified paths), but the tests fail (due to fully qualified paths). --- pixie/fs.pxi | 38 ++++++++++++++-------------- pixie/vm/libs/path.py | 17 ++++++++----- tests/pixie/tests/test-fs.pxi | 47 ++++++++++++++++++++--------------- 3 files changed, 57 insertions(+), 45 deletions(-) diff --git a/pixie/fs.pxi b/pixie/fs.pxi index 7be65fda..a7745a7a 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -18,11 +18,11 @@ (basename [this] "Returns the basename of the Filesystem Object") - + ;; TODO (permissions [this] "Returns a string of the octal permissions") - + (mounted? [this] "Returns true if the directory is a mounted") @@ -30,12 +30,12 @@ "Returns the size of the file/dir on disk")) (defprotocol IFile - (extension [this] + (extension [this] "Returns the extension") - - (extension? [this ext] + + (extension? [this ext] "Returns true if file has extension") - + ;; TODO (touch [this] "Create the file if it doesn't exist.")) @@ -71,7 +71,7 @@ ;; Same level (and (zero? (count diff-a)) (zero? (count diff-b))) "." - + ;; If B diverges by one level and a is a Dir we use ".." (and (= 1 (count diff-b)) (instance? Dir a)) ".." @@ -92,16 +92,16 @@ (abs [this] (path/-abs pathz)) - + (exists? [this] (path/-exists? pathz)) (basename [this] (last (string/split (abs this) "/"))) - IFile + IFile ;; TODO: Sort out regex or make strings partitionable. So we can split at - ;; #".". + ;; #".". (extension [this] (last (string/split (abs this) "."))) @@ -113,11 +113,11 @@ (hash (abs this))) (-eq [this other] - (if (instance? File other) + (if (instance? File other) (= (abs this) (abs other)) false)) - (-str [this] + (-str [this] (str (abs this))) (-repr [this] @@ -140,10 +140,10 @@ (basename [this] (last (string/split (abs this) "/"))) - + IDir (list [this] - (path/-list-dir pathz)) + (vec (map fspath (path/-list-dir pathz)))) (walk [this] (transduce (map #(if (path/-file? %) @@ -165,11 +165,11 @@ (hash (abs this))) (-eq [this other] - (if (instance? Dir other) + (if (instance? Dir other) (= (abs this) (abs other)) false)) - (-str [this] + (-str [this] (str (abs this))) (-repr [this] @@ -177,11 +177,11 @@ ;; (deftype Fifo [pathz]) -(defn file +(defn file "Returns a file if the path is a file or does not exist. If a different filesystem object exists at the path an error will be thrown." [x] (let [x (path/-path x)] - (cond + (cond (path/-file? x) (->File x) (not (path/-exists? x)) (->File x) :else (throw (str "A non-file object exists at path: " x))))) @@ -190,7 +190,7 @@ "Returns a dir if the path is a dir or does not exist. If a different filesystem object exists at the path an error will be thrown." [x] (let [x (path/-path x)] - (cond + (cond (path/-dir? x) (->Dir x) (not (path/-exists? x)) (->Dir x) :else (throw (str "A non-dir object exists at path: " x))))) diff --git a/pixie/vm/libs/path.py b/pixie/vm/libs/path.py index 854bedce..8afd0ef2 100644 --- a/pixie/vm/libs/path.py +++ b/pixie/vm/libs/path.py @@ -18,7 +18,7 @@ def __init__(self, top): #def rel_path(self, other): # "Returns the path relative to other path" # return rt.wrap(str(os.path.relpath(self._path, start=other._path))) - + def abs_path(self): "Returns the absolute path" return rt.wrap(os.path.abspath(str(self._path))) @@ -28,8 +28,8 @@ def abs_path(self): # return rt.wrap(rt.name(os.path.basename("a"))) def exists(self): - return true if os.path.exists(str(self._path)) else false - + return true if os.path.exists(str(self._path)) else false + def is_file(self): return true if os.path.isfile(str(self._path)) else false @@ -61,9 +61,14 @@ def path(path): return Path(path) # TODO: Implement this -#@as_var("pixie.path", "list-dir") -#def list_dir(path): - +@as_var("pixie.path", "-list-dir") +def list_dir(self): + assert isinstance(self, Path) + result = rt.vector() + for item in os.listdir(str(self._path)): + result = rt.conj(result, rt.wrap(str(self._path) + "/" + str(item))) + return result + @as_var("pixie.path", "-abs") def _abs(self): assert isinstance(self, Path) diff --git a/tests/pixie/tests/test-fs.pxi b/tests/pixie/tests/test-fs.pxi index c56143cd..b4a14e8a 100644 --- a/tests/pixie/tests/test-fs.pxi +++ b/tests/pixie/tests/test-fs.pxi @@ -14,7 +14,7 @@ (fs/dir dir-b) (fs/dir dir-c)) true) - + (t/assert= (= (fs/file file-a) (fs/file file-b) (fs/file file-c)) @@ -28,26 +28,33 @@ (fs/file file-b) (fs/file file-c)])) 1))) -(comment - (t/deftest test-walking - (let [dir-a "tests/pixie/tests/fs"] - (t/assert= (set (fs/walk (fs/dir dir-a))) - #{(fs/dir (str dir-a "/parent")) - (fs/file (str dir-a "/parent/foo.txt")) - (fs/file (str dir-a "/parent/bar.txt")) - (fs/dir (str dir-a "/parent/child")) - (fs/file (str dir-a "/parent/child/foo.txt")) - (fs/file (str dir-a "/parent/child/bar.txt"))}) - (t/assert= (set (fs/walk-files (fs/dir dir-a))) - #{(fs/file (str dir-a "/parent/foo.txt")) - (fs/file (str dir-a "/parent/bar.txt")) - (fs/file (str dir-a "/parent/child/foo.txt")) - (fs/file (str dir-a "/parent/child/bar.txt"))}) +(t/deftest test-walking + (let [dir-a "tests/pixie/tests/fs"] + (t/assert= (set (fs/walk (fs/dir dir-a))) + #{(fs/dir (str dir-a "/parent")) + (fs/file (str dir-a "/parent/foo.txt")) + (fs/file (str dir-a "/parent/bar.txt")) + (fs/dir (str dir-a "/parent/child")) + (fs/file (str dir-a "/parent/child/foo.txt")) + (fs/file (str dir-a "/parent/child/bar.txt"))}) + + (t/assert= (set (fs/walk-files (fs/dir dir-a))) + #{(fs/file (str dir-a "/parent/foo.txt")) + (fs/file (str dir-a "/parent/bar.txt")) + (fs/file (str dir-a "/parent/child/foo.txt")) + (fs/file (str dir-a "/parent/child/bar.txt"))}) + + (t/assert= (set (fs/walk-dirs (fs/dir dir-a))) + #{(fs/dir (str dir-a "/parent")) + (fs/dir (str dir-a "/parent/child"))}))) - (t/assert= (set (fs/walk-dirs (fs/dir dir-a))) - #{(fs/dir (str dir-a "/parent")) - (fs/dir (str dir-a "/parent/child"))})))) +(t/deftest test-list + (let [dir-a "tests/pixie/tests/fs/parent"] + (t/assert= (set (fs/list (fs/dir dir-a))) + #{(fs/file (str dir-a "foo.txt")) + (fs/file (str dir-a "bar.txt")) + (fs/dir (str dir-a "child"))}))) (t/deftest test-rel? (let [dir-a (fs/dir "tests/pixie/tests/fs") @@ -91,7 +98,7 @@ (t/deftest test-exists? (let [real-dir (fs/dir "tests/pixie/tests/fs/parent") fake-dir (fs/dir "tests/pixie/tests/fs/parent/fake-dir") - fake-file (fs/dir "tests/pixie/tests/fs/parent/fake-file")] + fake-file (fs/dir "tests/pixie/tests/fs/parent/fake-file")] (t/assert= (fs/exists? real-dir) true) (t/assert= (fs/exists? fake-dir) false) (t/assert= (fs/exists? fake-file) false))) From f2b7fd2a3d1ef7071a06916f9e3253dcf56b1fca Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 10 Mar 2015 17:25:37 -0600 Subject: [PATCH 021/349] remove old code --- pixie/stacklets.pxi | 92 --------------------------------------------- 1 file changed, 92 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 0f60d989..ff96a3dc 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -122,95 +122,3 @@ (defn promise [] (->Promise nil (atom []) false)) - -(comment (with-stacklets - (let [p (promise)] - (spawn @p) - (spawn @p) - (spawn (p 42)) - @p))) - -(comment - - - (with-stacklets - (let [f (fs_open "/tmp/foo.txt" uv/O_RDONLY uv/S_IRUSR) - b (uv/new-fs-buf 1024)] - (println (type (:base b))) - (let [err (fs_read f b 1 0)] - (println err) - (assert (pos? err))) - (dotimes [x 100] - (puts (str (char (pixie.ffi/unpack (:base b) x CUInt8))))) - (println "done")))) - -(comment - - - (dotimes [t 33] - (-thread (fn [] (dotimes [x 10000] - (println t x)))))) - -(comment - (defn run-later [f] - (let [a (uv/uv_async_t) - cb (atom nil)] - (println "start yield") - (reset! cb (ffi-prep-callback uv/uv_async_cb - (fn [handle] - (println "process yield") - (f) - (uv/uv_close a close_cb) - (-dispose! @cb) - (println "done process yield")))) - (uv/uv_async_init (uv/uv_default_loop) a @cb) - (uv/uv_async_send a))) - - (defn cfn [x] - (fn [] - (println x) - (if (pos? x) - (run-later (cfn (dec x)))))) - - (do (run-later (cfn 10000)) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT))) - - -(comment - ((var defuvfsfn) 'open '[path flags mode] :result) - - (defuvfsfn open [path flags mode] :result) - (defuvfsfn read [file bufs nbufs offset] :result) - (defuvfsfn close [file] :result)) - - -(comment - (defprotocol IBlockingQueue - (add-item [this item]) - (remove-item [this])) - - (deftype BlockingQueue [items lock locked] - IBlockingQueue - (add-item [this item] - (enqueue items item) - (when @locked - (-release-lock lock) - (reset! locked false)) - (-yield-thread)) - (remove-item [this] - (when (empty? @items) - (reset! locked true) - (-acquire-lock lock true)) - (dequeue items))) - - (defn blocking-queue [] - (let [l (-create-lock)] - (-acquire-lock l true) - (->BlockingQueue (atom []) l (atom true)))) - - (def task-queue (blocking-queue)) - - - - -) From a0a26b8426911609b31ab64e4d0be5802c74d46f Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 11 Mar 2015 06:11:29 -0600 Subject: [PATCH 022/349] deftype performance boost for immutable fields #215 --- benchmarks/deftype_fields.pxi | 16 +++++++++++++ pixie/stdlib.pxi | 18 +++++--------- pixie/vm/custom_types.py | 44 ++++++++++++++++++++++++++++++----- 3 files changed, 60 insertions(+), 18 deletions(-) create mode 100644 benchmarks/deftype_fields.pxi diff --git a/benchmarks/deftype_fields.pxi b/benchmarks/deftype_fields.pxi new file mode 100644 index 00000000..fbee851b --- /dev/null +++ b/benchmarks/deftype_fields.pxi @@ -0,0 +1,16 @@ +;; Before Immutable Opt: 3.9 sec +;; After 3.2 sec + +(defprotocol IAdder + (add-them [this])) + +(deftype Adder [a b] + IAdder + (add-them [this] + (set-field! this :b (+ a b)) + b)) + + +(def adder (->Adder 1 0)) +(dotimes [x (* 1024 1024 1024)] + (assert (= (inc x) (add-them adder)))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1cfb420c..9b95d973 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1159,18 +1159,12 @@ Creates new maps if the keys are not present." type-decl `(def ~nm (create-type ~(keyword (name nm)) ~all-fields)) inst (gensym) ctor `(defn ~ctor-name ~field-syms - (let [~inst (new ~nm)] - ~@(transduce - (map (fn [field] - `(set-field! ~inst ~field ~(symbol (name field))))) - conj - fields) - ~@(transduce - (map (fn [type-body] - `(set-field! ~inst ~(keyword (name (first type-body))) ~(mk-body type-body)))) - conj - type-bodies) - ~inst)) + (new ~nm + ~@field-syms + ~@(transduce (map (fn [type-body] + (mk-body type-body))) + conj + type-bodies))) proto-bodies (transduce (map (fn [body] (cond diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 7a1757b9..0434ba36 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -6,39 +6,64 @@ import pixie.vm.rt as rt class CustomType(Type): - __immutable_fields__ = ["_slots"] + __immutable_fields__ = ["_slots", "_rev?"] def __init__(self, name, slots): Type.__init__(self, name) self._slots = slots + self._mutable_slots = {} + self._rev = 0 @jit.elidable_promote() def get_slot_idx(self, nm): return self._slots[nm] + def set_mutable(self, nm): + if not self.is_mutable(nm): + self._rev += 1 + self._mutable_slots[nm] = nm + + + @jit.elidable_promote() + def _is_mutable(self, nm, rev): + return nm in self._mutable_slots + + def is_mutable(self, nm): + return self._is_mutable(nm, self._rev) + @jit.elidable_promote() def get_num_slots(self): return len(self._slots) class CustomTypeInstance(Object): __immutable_fields__ = ["_type"] - def __init__(self, type): + def __init__(self, type, fields): affirm(isinstance(type, CustomType), u"Can't create a instance of a non custom type") self._custom_type = type - self._fields = [None] * self._custom_type.get_num_slots() + self._fields = fields def type(self): return self._custom_type def set_field(self, name, val): + self._custom_type.set_mutable(name) idx = self._custom_type.get_slot_idx(name) self._fields[idx] = val return self - def get_field(self, name): + @jit.elidable_promote() + def get_field_immutable(self, name): idx = self._custom_type.get_slot_idx(name) return self._fields[idx] + + def get_field(self, name): + if self._custom_type.is_mutable(name): + idx = self._custom_type.get_slot_idx(name) + return self._fields[idx] + else: + return self.get_field_immutable(name) + def set_field_by_idx(self, idx, val): affirm(isinstance(idx, r_uint), u"idx must be a r_uint") self._fields[idx] = val @@ -60,9 +85,16 @@ def create_type(type_name, fields): return CustomType(rt.name(type_name), acc) @as_var("new") -def _new(tp): +def _new__args(args): + affirm(len(args) >= 1, u"new takes at least one parameter") + tp = args[0] affirm(isinstance(tp, CustomType), u"Can only create a new instance of a custom type") - return CustomTypeInstance(tp) + cnt = len(args) - 1 + affirm(cnt - 1 != tp.get_num_slots(), u"Wrong number of initializer fields to custom type") + arr = [None] * cnt + for x in range(cnt): + arr[x] = args[x + 1] + return CustomTypeInstance(tp, arr) @as_var("set-field!") def set_field(inst, field, val): From d26ed0b71365493394746c287b20b0c70685a76c Mon Sep 17 00:00:00 2001 From: Peter Monks Date: Wed, 11 Mar 2015 11:19:24 -0700 Subject: [PATCH 023/349] Fixed issue #218 --- tests/pixie/tests/test-fs.pxi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/pixie/tests/test-fs.pxi b/tests/pixie/tests/test-fs.pxi index b4a14e8a..e5edaffb 100644 --- a/tests/pixie/tests/test-fs.pxi +++ b/tests/pixie/tests/test-fs.pxi @@ -52,9 +52,9 @@ (t/deftest test-list (let [dir-a "tests/pixie/tests/fs/parent"] (t/assert= (set (fs/list (fs/dir dir-a))) - #{(fs/file (str dir-a "foo.txt")) - (fs/file (str dir-a "bar.txt")) - (fs/dir (str dir-a "child"))}))) + #{(fs/file (str dir-a "/foo.txt")) + (fs/file (str dir-a "/bar.txt")) + (fs/dir (str dir-a "/child"))}))) (t/deftest test-rel? (let [dir-a (fs/dir "tests/pixie/tests/fs") From 3c0f3b5d4ecde799421018b9684584a92b3ddf15 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 11 Mar 2015 21:50:44 -0600 Subject: [PATCH 024/349] implement doc string support for native functions --- pixie/stdlib.pxi | 2 ++ pixie/vm/code.py | 7 ++++--- pixie/vm/stdlib.py | 8 ++++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 9b95d973..067e52c9 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1273,11 +1273,13 @@ and implements IAssociative, ILookup and IObject." {:doc "Returns the documentation of the given value." :added "0.1"} [v] + (let [vr (resolve v) x (if vr @vr) doc (get (meta x) :doc) has-doc? (if doc true (get (meta x) :signatures))] (cond + (satisfies? IDoc x) (-doc x) has-doc? (let [sigs (get (meta x) :signatures) examples (get (meta x) :examples) indent (fn [s] diff --git a/pixie/vm/code.py b/pixie/vm/code.py index ed17035f..9e3ad263 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -172,7 +172,7 @@ class NativeFn(BaseCode): """Wrapper for a native function""" _type = object.Type(u"pixie.stdlib.NativeFn") - def __init__(self): + def __init__(self, doc=None): BaseCode.__init__(self) def type(self): @@ -807,11 +807,12 @@ def assert_type(x, tp): def wrap_fn(fn, tp=object.Object): """Converts a native Python function into a pixie function.""" + docstring = unicode(fn.__doc__) if fn.__doc__ else u"" def as_native_fn(f): - return type("W" + fn.__name__, (NativeFn,), {"inner_invoke": f})() + return type("W" + fn.__name__, (NativeFn,), {"inner_invoke": f, "_doc": docstring})() def as_variadic_fn(f): - return type("W" + fn.__name__[:len("__args")], (NativeFn,), {"inner_invoke": f})() + return type("W" + fn.__name__[:len("__args")], (NativeFn,), {"inner_invoke": f, "_doc": docstring})() code = fn.func_code if fn.__name__.endswith("__args"): diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 07fdb380..4cfe5d05 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -43,6 +43,8 @@ defprotocol("pixie.stdlib", "IFn", ["-invoke"]) +defprotocol("pixie.stdlib", "IDoc", ["-doc"]) + IVector = as_var("pixie.stdlib", "IVector")(Protocol(u"IVector")) IMap = as_var("pixie.stdlib", "IMap")(Protocol(u"IMap")) @@ -799,5 +801,11 @@ def _seq(self): @as_var("ex-msg") def ex_msg(e): + """Returns the message contained in an exception""" assert isinstance(e, RuntimeException) return e._data + +@extend(_doc, code.NativeFn._type) +def _doc(self): + assert isinstance(self, code.NativeFn) + return rt.wrap(self._doc) \ No newline at end of file From 4016b85b2aa1b297be9090c358d49ad239e2e60d Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 12 Mar 2015 06:43:40 -0600 Subject: [PATCH 025/349] split the stream apis, remove ICloseable in favor of IDisposable --- pixie/io-blocking.pxi | 22 ++++++++------- pixie/io.pxi | 66 ++++++------------------------------------- pixie/stdlib.pxi | 6 ++++ pixie/streams.pxi | 18 ++++-------- 4 files changed, 32 insertions(+), 80 deletions(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index f5565373..425120b1 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -25,8 +25,8 @@ read-count)) (read-byte [this] (fgetc buffer)) - IClosable - (close [this] + IDisposable + (-dispose! [this] (fclose fp)) IReduce (-reduce [this f init] @@ -72,20 +72,21 @@ (cons line (lazy-seq (line-seq input-stream))))) (deftype FileOutputStream [fp] - IOutputStream + IByteOutputStream (write-byte [this val] (assert (integer? val) "Value must be a int") (fputc val fp)) + IOutputStream (write [this buffer] (fwrite buffer 1 (count buffer) fp)) - IClosable - (close [this] + IDisposable + (-dispose! [this] (fclose fp))) (defn file-output-rf [filename] (let [fp (->FileOutputStream (fopen filename "w"))] (fn ([] 0) - ([cnt] (close fp) cnt) + ([cnt] (dispose! fp) nil) ([cnt chr] (assert (integer? chr)) (let [written (write-byte fp chr)] @@ -105,7 +106,7 @@ (map char) string-builder c)] - (close c) + (dispose! c) result)) (deftype ProcessInputStream [fp] @@ -116,10 +117,11 @@ (let [read-count (fread buffer 1 len fp)] (set-buffer-count! buffer read-count) read-count)) + IByteInputStream (read-byte [this] (fgetc fp)) - IClosable - (close [this] + IDisposable + (-dispose! [this] (pclose fp)) IReduce (-reduce [this f init] @@ -149,5 +151,5 @@ (map char) string-builder c)] - (close c) + (dispose! c) result)) diff --git a/pixie/io.pxi b/pixie/io.pxi index cc76046c..013a7bd7 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -42,10 +42,8 @@ (set-field! this :offset (+ offset read-count)) (set-buffer-count! buffer read-count) read-count)) - (read-byte [this] - (assert false "Does not support read-byte, wrap in a buffering reader")) - IClosable - (close [this] + IDisposable + (-dispose! [this] (pixie.ffi/free uvbuf) (fs_close fp)) IReduce @@ -95,8 +93,6 @@ (deftype FileOutputStream [fp offset uvbuf] IOutputStream - (write-byte [this val] - (assert false)) (write [this buffer] (loop [buffer-offset 0] (let [_ (pixie.ffi/set! uvbuf :base (ffi/ptr-add buffer buffer-offset)) @@ -108,12 +104,12 @@ (if (< (+ buffer-offset write-count) (count buffer)) (recur (+ buffer-offset write-count)) write-count)))) - IClosable - (close [this] + IDisposable + (-dispose! [this] (fclose fp))) (deftype BufferedOutputStream [downstream idx buffer] - IOutputStream + IByteOutputStream (write-byte [this val] (pixie.ffi/pack! buffer idx CUInt8 val) (set-field! this :idx (inc idx)) @@ -121,8 +117,8 @@ (set-buffer-count! buffer (buffer-capacity buffer)) (write downstream buffer) (set-field! this :idx 0))) - IClosable - (close [this] + IDisposable + (-dispose! [this] (set-buffer-count! buffer idx) (write downstream buffer))) @@ -151,7 +147,7 @@ (let [fp (buffered-output-stream (open-write filename) DEFAULT-BUFFER-SIZE)] (fn ([] 0) - ([_] (close fp) nil) + ([_] (dispose! fp)) ([_ chr] (assert (integer? chr)) (write-byte fp chr) @@ -169,49 +165,5 @@ (map char) string-builder c)] - (close c) - result)) - -(deftype ProcessInputStream [fp] - IInputStream - (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) - "Not enough capacity in the buffer") - (let [read-count (fread buffer 1 len fp)] - (set-buffer-count! buffer read-count) - read-count)) - (read-byte [this] - (fgetc fp)) - IClosable - (close [this] - (pclose fp)) - IReduce - (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) - - -(defn popen-read - {:doc "Open a file for reading, returning a IInputStream" - :added "0.1"} - [command] - (assert (string? command) "Command must be a string") - (->ProcessInputStream (popen command "r"))) - - -(defn run-command [command] - (let [c (->ProcessInputStream (popen command "r")) - result (transduce - (map char) - string-builder - c)] - (close c) + (dispose! c) result)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index c4ea4fbb..41380fb2 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2144,6 +2144,12 @@ Expands to calls to `extend-type`." ([sb] (str sb)) ([sb item] (conj! sb item))) +(defn dispose! + "Finalizes use of the object by cleaning up resources used by the object" + [x] + (-dispose! x) + nil) + (defmacro using [bindings & body] (let [pairs (partition 2 bindings) names (map first pairs)] diff --git a/pixie/streams.pxi b/pixie/streams.pxi index b037be76..05b4ad44 100644 --- a/pixie/streams.pxi +++ b/pixie/streams.pxi @@ -1,21 +1,13 @@ (ns pixie.streams) -(def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) -(def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) -(def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) -(def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) -(def fwrite (ffi-fn libc "fwrite" [CVoidP CInt CInt CVoidP] CInt)) -(def fclose (ffi-fn libc "fclose" [CVoidP] CInt)) -(def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) -(def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) - (defprotocol IInputStream - (read-byte [this] "Read a single character") (read [this buffer len] "Reads multiple bytes into a buffer, returns the number of bytes read")) (defprotocol IOutputStream - (write-byte [this byte]) (write [this buffer])) -(defprotocol IClosable - (close [this] "Closes the stream")) +(defprotocol IByteInputStream + (read-byte [this])) + +(defprotocol IByteOutputStream + (write-byte [this byte])) From 5a5d0cb6dce478725693f424a48aeb5d15bccde0 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 13 Mar 2015 23:22:47 -0600 Subject: [PATCH 026/349] started work on source compilation --- pixie/ffi-infer.pxi | 27 +++++++++++++++++++++++++++ pixie/io.pxi | 21 +++++++++++++++++++++ pixie/uv.pxi | 20 ++++++++++++++++++++ pixie/vm/libs/ffi.py | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 103 insertions(+) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 9a2d54b3..8056b57e 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -228,6 +228,33 @@ return 0; :name ~(name nm)))) +(defn compile-library [{:keys [prefix includes]} & source] + (let [c-name (str "/tmp/" prefix ".c") + source-header (apply str (map (fn [i] + (str "#include \"" i "\"\n")) + includes)) + source (apply str source-header (interpose "\n\n" source)) + lib-name (str "/tmp/" prefix "-" (hash source) "." pixie.platform/so-ext) + cmd (str "cc -dynamic-lang " + c-name + (apply str (map (fn [x] ( str " -I " x " ")) + @load-paths)) + + " -o " + lib-name)] + (io/spit c-name source) + (println cmd) + (io/run-command cmd))) + + + +(compile-library + {:prefix "foo" + :includes ["uv.h"]} + "int foo(int bar) + { + return 42; + }") (comment diff --git a/pixie/io.pxi b/pixie/io.pxi index 013a7bd7..ed8378ed 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -167,3 +167,24 @@ c)] (dispose! c) result)) + + +(defn tcp-server [ip port on-connection] + (assert (string? ip) "Ip should be a string") + (assert (integer? port) "Port should be a int") + (let [server (uv/uv_tcp_t) + bind-addr (uv/sockaddr_in) + _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) + on-new-connetion (atom nil)] + (reset! (ffi-prep-callback + uv/uv_connection_cb + (fn [server status] + (when (not (= status -1)) + (println "Got Client!!!!!!!"))))) + (uv/uv_tcp_init (uv/uv_default_loop) server) + (uv/uv_tcp_bind server bind_addr) + (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) + (st/yield-control))) + + +(tcp-server "0.0.0.0" 4242 nil) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 90bb127f..3cab69ae 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -174,6 +174,20 @@ (f/defccallback uv_async_cb) (f/defcfn uv_async_init) (f/defcfn uv_async_send) + + + ; TCP Networking + (f/defcstruct uv_tcp_t []) + (f/defc-raw-struct sockaddr_in) + (f/defcfn uv_tcp_init) + (f/defcfn uv_ip4_addr) + (f/defcfn uv_tcp_bind) + (f/defcfn uv_listen) + (f/defcfn uv_accept) + (f/defcfn uv_read_start) + + (f/defccallback uv_connection_cb) + ) @@ -183,3 +197,9 @@ (pixie.ffi/set! bt :base b) (pixie.ffi/set! bt :len size) bt)) + + +(defn throw-on-error [result] + (if (neg? result) + (throw (str "UV Error: " (uv/uv_err_name result))) + result)) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 48ff27db..94bd917f 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -238,6 +238,15 @@ def nth_char(self, idx): def capacity(self): return self._size + def free_data(self): + lltype.free(self._buffer, flavor="raw") + + + +@extend(proto._dispose_BANG_, Buffer) +def _dispose_voidp(self): + self.free_data() + @extend(proto._nth, Buffer) def _nth(self, idx): @@ -458,6 +467,24 @@ def __init__(self, raw_data): def raw_data(self): return rffi.cast(rffi.VOIDP, self._raw_data) + def free_data(self): + lltype.free(self._raw_data, flavor="raw") + +@extend(proto._dispose_BANG_, cvoidp) +def _dispose_voidp(self): + self.free_data() + + + +@as_var(u"pixie.ffi", u"prep-string") +def prep_string(s): + """Takes a Pixie string and returns a VoidP to that string. The string should be freed via dispose!, otherwise + memory leaks could result.""" + affirm(isinstance(s, String), u"Can only prep strings with prep-string") + utf8 = unicode_to_utf8(rt.name(s)) + raw = rffi.str2charp(utf8) + return VoidP(rffi.cast(rffi.VOIDP, raw)) + @as_var(u"pixie.ffi", u"unpack") def unpack(ptr, offset, tp): affirm(isinstance(ptr, VoidP) or isinstance(ptr, Buffer) or isinstance(ptr, CStruct), u"Type is not unpackable") @@ -718,6 +745,14 @@ def set_(self, k, val): +@as_var("pixie.ffi", "prep-ffi-call") +def prep_ffi_call__args(args): + fn = args[0] + affirm(isinstance(fn, CFunctionType), u"First arg must be a FFI function") + + + + import sys From 0ec3044c720c524eb2a509ccb97204a58ad30033 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 13 Mar 2015 23:45:56 -0600 Subject: [PATCH 027/349] ffi doc strings and cleanup --- pixie/ffi-infer.pxi | 3 ++- pixie/vm/libs/ffi.py | 30 ++++++++++++++++++++---------- tests/pixie/tests/test-ffi.pxi | 4 ++-- tests/pixie/tests/test-uv.pxi | 5 +++-- 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 49578c20..b0bf7e86 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -1,4 +1,5 @@ (ns pixie.ffi-infer + (require pixie.io :as io)) (defn -add-rel-path [rel] @@ -84,7 +85,7 @@ return 0; (defmulti edn-to-ctype :type) (defn callback-type [{:keys [arguments returns]}] - `(ffi-callback ~(vec (map edn-to-ctype arguments)) ~(edn-to-ctype returns))) + `(pixie.ffi/ffi-callback ~(vec (map edn-to-ctype arguments)) ~(edn-to-ctype returns))) (defmethod edn-to-ctype :pointer [{:keys [of-type] :as ptr}] diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 15e13167..f4836dc0 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -443,6 +443,8 @@ def raw_data(self): @as_var(u"pixie.ffi", u"unpack") def unpack(ptr, offset, tp): + """(unpack ptr offset tp) + Reads a value of type tp from offset of ptr.""" affirm(isinstance(ptr, VoidP) or isinstance(ptr, Buffer) or isinstance(ptr, CStruct), u"Type is not unpackable") affirm(isinstance(tp, CType), u"Packing type must be a CType") ptr = rffi.ptradd(ptr.raw_data(), offset.int_val()) @@ -450,6 +452,8 @@ def unpack(ptr, offset, tp): @as_var(u"pixie.ffi", u"pack!") def pack(ptr, offset, tp, val): + """(pack! ptr offset tp val) + Writes val at offset of ptr with the format tp""" affirm(isinstance(ptr, VoidP) or isinstance(ptr, Buffer) or isinstance(ptr, CStruct), u"Type is not unpackable") affirm(isinstance(tp, CType), u"Packing type must be a CType") ptr = rffi.ptradd(ptr.raw_data(), offset.int_val()) @@ -534,8 +538,11 @@ def _dispose(self): -@as_var(u"ffi-callback") +@as_var(u"pixie.ffi", u"ffi-callback") def ffi_callback(args, ret_type): + """(ffi-callback args ret-type) + Creates a ffi callback type. Args is a vector of CType args. Ret-type is the CType return + type of the callback. Returns a ffi callback type that can be used with ffi-prep-callback.""" args_w = [None] * rt.count(args) for x in range(rt.count(args)): @@ -549,8 +556,12 @@ def ffi_callback(args, ret_type): return CFunctionType(args_w, ret_type) -@as_var(u"ffi-prep-callback") +@as_var(u"pixie.ffi", u"ffi-prep-callback") def ffi_prep_callback(tp, f): + """(ffi-prep-callback callback-tp fn) + Prepares a Pixie function for use as a c callback. callback-tp is a ffi callback type, + fn is a pixie function (can be a closure, native fn or any object that implements -invoke. + Returns a function pointer that can be passed to c and invoked as a callback.""" affirm(isinstance(tp, CFunctionType), u"First argument to ffi-prep-callback must be a CFunctionType") raw_closure = rffi.cast(rffi.VOIDP, clibffi.closureHeap.alloc()) @@ -652,6 +663,9 @@ def set_val(self, k, v): @as_var("pixie.ffi", "c-struct") def c_struct(name, size, spec): + """(c-struct name size spec) + Creates a CStruct named name, of size size, with the given spec. Spec is a vector + of vectors. Each row of the format [field-name type offset]""" d = {} for x in range(rt.count(spec)): row = rt.nth(spec, rt.wrap(x)) @@ -669,6 +683,8 @@ def c_struct(name, size, spec): @as_var("pixie.ffi", "cast") def c_cast(frm, to): + """(cast from to) + Converts a VoidP to a CStruct. From is either a VoidP or a CStruct, to is a CStruct type.""" if not isinstance(to, CStructType): runtime_error(u"Expected a CStruct type to cast to, got " + rt.name(rt.str(to))) @@ -677,14 +693,6 @@ def c_cast(frm, to): return to.cast_to(frm) -@as_var("pixie.ffi", "free") -def c_free(frm): - if not isinstance(frm, CStruct) and not isinstance(frm, VoidP): - runtime_error(u"Can only free CStructs or CVoidP") - - lltype.free(frm.raw_data(), flavor="raw") - - return nil @extend(proto._val_at, CStructType.base_type) def val_at(self, k, not_found): @@ -692,6 +700,8 @@ def val_at(self, k, not_found): @as_var("pixie.ffi", "set!") def set_(self, k, val): + """(set! ptr k val) + Sets a field k of struct ptr to value val""" return self.set_val(k, val) diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index 71502c8e..8ea60649 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -39,11 +39,11 @@ (t/deftest test-ffi-callbacks (let [MAX 255 - qsort-cb (ffi-callback [CVoidP CVoidP] CInt) + qsort-cb (pixie.ffi/ffi-callback [CVoidP CVoidP] CInt) qsort (ffi-fn libc "qsort" [CVoidP CInt CInt qsort-cb] CInt) buf (buffer MAX)] - (using [cb (ffi-prep-callback qsort-cb (fn [x y] + (using [cb (pixie.ffi/ffi-prep-callback qsort-cb (fn [x y] (if (> (pixie.ffi/unpack x 0 CUInt8) (pixie.ffi/unpack y 0 CUInt8)) -1 diff --git a/tests/pixie/tests/test-uv.pxi b/tests/pixie/tests/test-uv.pxi index 3998ab37..4167955e 100644 --- a/tests/pixie/tests/test-uv.pxi +++ b/tests/pixie/tests/test-uv.pxi @@ -1,6 +1,7 @@ (ns pixie.test-uv (require pixie.uv :as uv) - (require pixie.test :as t)) + (require pixie.test :as t) + (require pixie.ffi :as ffi)) (t/deftest timer-tests @@ -8,7 +9,7 @@ result (atom false) loop (uv/uv_loop_t) timer (uv/uv_timer_t)] - (reset! cb (ffi-prep-callback uv/uv_timer_cb + (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb (fn [handle] (reset! result true) (uv/uv_timer_stop timer) From 54794eb8339f3da378d782a18ea2f8932f6a74e3 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sat, 14 Mar 2015 11:10:33 +0000 Subject: [PATCH 028/349] Fix line comment bug and improve reader tests Previously, code like (1 2 3 ;foo ) would fail to parse, because LineCommentReader would attempt to return the next form, which was `)`, causing an error. To fix this I changed the semantics of `read` to allow it to not return a form at all (signalled by returning the reader itself, as in https://github.com/clojure/tools.reader), for situations like `;`. Unsure if this is the best approach to fixing, open to discussion. Another option could be to treat comments as whitespace. Also, the reader tests had some cases where they wouldn't verify the input properly, so I fixed those as well. --- pixie/vm/reader.py | 34 +++++++++++++++++++++------------- pixie/vm/test/test_reader.py | 20 ++++++++++++++++++-- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 3049ae2f..fedb558b 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -221,7 +221,9 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - lst.append(read(rdr, True)) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + lst.append(itm) class UnmatchedListReader(ReaderHandler): def invoke(self, rdr, ch): @@ -237,7 +239,9 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - acc = rt.conj(acc, read(rdr, True)) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + acc = rt.conj(acc, itm) class UnmatchedVectorReader(ReaderHandler): def invoke(self, rdr, ch): @@ -253,9 +257,14 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - k = read(rdr, True) - v = read(rdr, False) - acc = rt._assoc(acc, k, v) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + k = itm + itm = rdr + while itm == rdr: + itm = read(rdr, False, always_return_form=False) + v = itm + acc = rt._assoc(acc, k, v) return acc class UnmatchedMapReader(ReaderHandler): @@ -573,17 +582,13 @@ def invoke(self, rdr, ch): class LineCommentReader(ReaderHandler): def invoke(self, rdr, ch): self.skip_line(rdr) - return read(rdr, True) + return rdr def skip_line(self, rdr): while True: ch = rdr.read() if ch == u"\n": return - elif ch == u"\r": - ch2 = rdr.read() - if ch2 == u"\n": - return handlers = {u"(": ListReader(), u")": UnmatchedListReader(), @@ -723,7 +728,7 @@ def throw_syntax_error_with_data(rdr, txt): -def read(rdr, error_on_eof): +def read(rdr, error_on_eof, always_return_form=True): try: eat_whitespace(rdr) except EOFError as ex: @@ -742,6 +747,8 @@ def read(rdr, error_on_eof): macro = handlers.get(ch, None) if macro is not None: itm = macro.invoke(rdr, ch) + if always_return_form and itm == rdr: + return read(rdr, error_on_eof, always_return_form=always_return_form) elif is_digit(ch): itm = read_number(rdr, ch) @@ -759,8 +766,9 @@ def read(rdr, error_on_eof): else: itm = read_symbol(rdr, ch) - if rt.has_meta_QMARK_(itm): - itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) + if itm != rdr: + if rt.has_meta_QMARK_(itm): + itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) return itm diff --git a/pixie/vm/test/test_reader.py b/pixie/vm/test/test_reader.py index 33a08152..19539f0c 100644 --- a/pixie/vm/test/test_reader.py +++ b/pixie/vm/test/test_reader.py @@ -4,6 +4,8 @@ from pixie.vm.numbers import Integer from pixie.vm.symbol import symbol, Symbol from pixie.vm.persistent_vector import PersistentVector +from pixie.vm.persistent_hash_map import PersistentHashMap +from pixie.vm.primitives import nil import pixie.vm.rt as rt import unittest @@ -17,7 +19,14 @@ u"(platform+ 1 2)": (symbol(u"platform+"), 1, 2), u"[42 43 44]": [42, 43, 44], u"(1 2 ; 7 8 9\n3)": (1, 2, 3,), - u"(1 2 ; 7 8 9\r\n3)": (1, 2, 3,)} + u"(1 2 ; 7 8 9\r\n3)": (1, 2, 3,), + u"(1 2 ; 7 8 9\r\n)": (1, 2,), + u"(1 2 ; 7 8 9\n)": (1, 2,), + u"[1 2 ; 7 8 9\n]": [1, 2,], + u"(1 2; 7 8 9\n)": (1, 2,), + u";foo\n(1 2; 7 8 9\n)": (1, 2,), + u"{\"foo\" 1 ;\"bar\" 2\n\"baz\" 3}": {"foo": 1, "baz": 3}, + u"{\"foo\" ; \"bar\" 2\n1 \"baz\" 3}": {"foo": 1, "baz": 3}} class TestReader(unittest.TestCase): def _compare(self, frm, to): @@ -27,6 +36,7 @@ def _compare(self, frm, to): for x in to: self._compare(frm.first(), x) frm = frm.next() + assert frm == nil elif isinstance(to, int): assert isinstance(frm, Integer) assert frm._int_val == to @@ -38,9 +48,15 @@ def _compare(self, frm, to): elif isinstance(to, list): assert isinstance(frm, PersistentVector) - for x in range(len(to)): + for x in range(max(len(to), rt._count(frm)._int_val)): self._compare(rt.nth(frm, rt.wrap(x)), to[x]) + elif isinstance(to, dict): + assert isinstance(frm, PersistentHashMap) + for key in dict.keys(to): + self._compare(frm.val_at(rt.wrap(key), ""), to[key]) + + assert rt._count(frm)._int_val == len(dict.keys(to)) else: raise Exception("Don't know how to handle " + str(type(to))) From ddbc00dd1e523eba0e6a7111202f48ce489fe839 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sat, 14 Mar 2015 14:59:00 +0000 Subject: [PATCH 029/349] Allow macro characters as character literals Previously ``` (def a \)) ``` would fail to parse. This commit fixes that. --- pixie/vm/reader.py | 2 +- pixie/vm/test/test_reader.py | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index fedb558b..2ba86059 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -329,7 +329,7 @@ def invoke(self, rdr, ch): acc.append(v) def read_token(rdr): - acc = u"" + acc = rdr.read() while True: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): diff --git a/pixie/vm/test/test_reader.py b/pixie/vm/test/test_reader.py index 19539f0c..96e8d458 100644 --- a/pixie/vm/test/test_reader.py +++ b/pixie/vm/test/test_reader.py @@ -3,6 +3,7 @@ from pixie.vm.cons import Cons from pixie.vm.numbers import Integer from pixie.vm.symbol import symbol, Symbol +from pixie.vm.string import Character from pixie.vm.persistent_vector import PersistentVector from pixie.vm.persistent_hash_map import PersistentHashMap from pixie.vm.primitives import nil @@ -26,7 +27,11 @@ u"(1 2; 7 8 9\n)": (1, 2,), u";foo\n(1 2; 7 8 9\n)": (1, 2,), u"{\"foo\" 1 ;\"bar\" 2\n\"baz\" 3}": {"foo": 1, "baz": 3}, - u"{\"foo\" ; \"bar\" 2\n1 \"baz\" 3}": {"foo": 1, "baz": 3}} + u"{\"foo\" ; \"bar\" 2\n1 \"baz\" 3}": {"foo": 1, "baz": 3}, + u"(\\a)": (Character(ord("a")),), + u"(\\))": (Character(ord(")")),), + u"(\\()": (Character(ord("(")),), + u"(\\;)": (Character(ord(";")),)} class TestReader(unittest.TestCase): def _compare(self, frm, to): @@ -57,6 +62,11 @@ def _compare(self, frm, to): self._compare(frm.val_at(rt.wrap(key), ""), to[key]) assert rt._count(frm)._int_val == len(dict.keys(to)) + + elif isinstance(to, Character): + assert isinstance(frm, Character) + assert to._char_val == frm._char_val + else: raise Exception("Don't know how to handle " + str(type(to))) From 9dcf7ffcbb1759ee4076385c6fd3f5df35325886 Mon Sep 17 00:00:00 2001 From: Peter Monks Date: Sat, 14 Mar 2015 08:04:21 -0700 Subject: [PATCH 030/349] Commented out pixie.fs tests that work locally but segfault on travis-ci. --- tests/pixie/tests/test-fs.pxi | 49 +++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/tests/pixie/tests/test-fs.pxi b/tests/pixie/tests/test-fs.pxi index e5edaffb..5a8ba3b2 100644 --- a/tests/pixie/tests/test-fs.pxi +++ b/tests/pixie/tests/test-fs.pxi @@ -29,32 +29,35 @@ (fs/file file-c)])) 1))) -(t/deftest test-walking - (let [dir-a "tests/pixie/tests/fs"] - (t/assert= (set (fs/walk (fs/dir dir-a))) - #{(fs/dir (str dir-a "/parent")) - (fs/file (str dir-a "/parent/foo.txt")) - (fs/file (str dir-a "/parent/bar.txt")) - (fs/dir (str dir-a "/parent/child")) - (fs/file (str dir-a "/parent/child/foo.txt")) - (fs/file (str dir-a "/parent/child/bar.txt"))}) +(comment + ; Although these pass locally, they don't appear to work on travis-ci (segfault) + (t/deftest test-walking + (let [dir-a "tests/pixie/tests/fs"] + (t/assert= (set (fs/walk (fs/dir dir-a))) + #{(fs/dir (str dir-a "/parent")) + (fs/file (str dir-a "/parent/foo.txt")) + (fs/file (str dir-a "/parent/bar.txt")) + (fs/dir (str dir-a "/parent/child")) + (fs/file (str dir-a "/parent/child/foo.txt")) + (fs/file (str dir-a "/parent/child/bar.txt"))}) - (t/assert= (set (fs/walk-files (fs/dir dir-a))) - #{(fs/file (str dir-a "/parent/foo.txt")) - (fs/file (str dir-a "/parent/bar.txt")) - (fs/file (str dir-a "/parent/child/foo.txt")) - (fs/file (str dir-a "/parent/child/bar.txt"))}) + (t/assert= (set (fs/walk-files (fs/dir dir-a))) + #{(fs/file (str dir-a "/parent/foo.txt")) + (fs/file (str dir-a "/parent/bar.txt")) + (fs/file (str dir-a "/parent/child/foo.txt")) + (fs/file (str dir-a "/parent/child/bar.txt"))}) - (t/assert= (set (fs/walk-dirs (fs/dir dir-a))) - #{(fs/dir (str dir-a "/parent")) - (fs/dir (str dir-a "/parent/child"))}))) + (t/assert= (set (fs/walk-dirs (fs/dir dir-a))) + #{(fs/dir (str dir-a "/parent")) + (fs/dir (str dir-a "/parent/child"))}))) -(t/deftest test-list - (let [dir-a "tests/pixie/tests/fs/parent"] - (t/assert= (set (fs/list (fs/dir dir-a))) - #{(fs/file (str dir-a "/foo.txt")) - (fs/file (str dir-a "/bar.txt")) - (fs/dir (str dir-a "/child"))}))) + (t/deftest test-list + (let [dir-a "tests/pixie/tests/fs/parent"] + (t/assert= (set (fs/list (fs/dir dir-a))) + #{(fs/file (str dir-a "/foo.txt")) + (fs/file (str dir-a "/bar.txt")) + (fs/dir (str dir-a "/child"))}))) +) (t/deftest test-rel? (let [dir-a (fs/dir "tests/pixie/tests/fs") From 58a12d4b30c3afdb5d0bcf9e9a4b19652fd27c79 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sat, 14 Mar 2015 15:56:18 -0600 Subject: [PATCH 031/349] added a bit of code to support multiple threads --- pixie/io.pxi | 17 ++++++++++++++--- pixie/stacklets.pxi | 24 ++++++++++++++++++++++++ pixie/uv.pxi | 4 ++-- pixie/vm/libs/libedit.py | 2 +- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index ed8378ed..5664180c 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -2,7 +2,8 @@ (require pixie.streams :as st :refer :all) (require pixie.uv :as uv) (require pixie.stacklets :as st) - (require pixie.ffi :as ffi)) + (require pixie.ffi :as ffi) + (require pixie.ffi-infer :as ffi-infer)) (defmacro defuvfsfn [nm args return] `(defn ~nm ~args @@ -176,15 +177,25 @@ bind-addr (uv/sockaddr_in) _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) on-new-connetion (atom nil)] - (reset! (ffi-prep-callback + (reset! on-new-connetion + (ffi-prep-callback uv/uv_connection_cb (fn [server status] (when (not (= status -1)) (println "Got Client!!!!!!!"))))) (uv/uv_tcp_init (uv/uv_default_loop) server) - (uv/uv_tcp_bind server bind_addr) + (uv/uv_tcp_bind server bind-addr 0) (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) (st/yield-control))) +(st/apply-blocking println "FROM OTHER THREAD <---!!!!!") + + (tcp-server "0.0.0.0" 4242 nil) +(comment + (defmacro make-readline-async [] + `(let [libname ~(ffi-infer/compile-library {:prefix "pixie.io.readline" + :includes ["uv.h" "editline/readline.h"]})])) + + (ffi-infer/compile-library)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index ff96a3dc..19dc3ca6 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -122,3 +122,27 @@ (defn promise [] (->Promise nil (atom []) false)) + +(defprotocol IThreadPool + (-execute [this work-fn])) + + +;; Super basic Thread Pool, yes, this should be improved + +(deftype ThreadPool [] + IThreadPool + (-execute [this work-fn] + (-thread (fn [] (work-fn))))) + +(def basic-thread-pool (->ThreadPool)) + +(defn -run-in-other-thread [work-fn] + (-execute basic-thread-pool work-fn)) + + +(defn apply-blocking [f & args] + (call-cc (fn [k] + (-run-in-other-thread + (fn [] + (let [result (apply f args)] + (-run-later (fn [] (run-and-process k result))))))))) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 3cab69ae..d984d52a 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -178,7 +178,7 @@ ; TCP Networking (f/defcstruct uv_tcp_t []) - (f/defc-raw-struct sockaddr_in) + (f/defc-raw-struct sockaddr_in []) (f/defcfn uv_tcp_init) (f/defcfn uv_ip4_addr) (f/defcfn uv_tcp_bind) @@ -201,5 +201,5 @@ (defn throw-on-error [result] (if (neg? result) - (throw (str "UV Error: " (uv/uv_err_name result))) + (throw (str "UV Error: " (uv_err_name result))) result)) diff --git a/pixie/vm/libs/libedit.py b/pixie/vm/libs/libedit.py index a5a20203..090eff3f 100644 --- a/pixie/vm/libs/libedit.py +++ b/pixie/vm/libs/libedit.py @@ -14,7 +14,7 @@ libraries=["edit"]) def llexternal(*args, **kwargs): - return rffi.llexternal(*args, compilation_info=compilation_info, **kwargs) + return rffi.llexternal(*args, compilation_info=compilation_info, releasegil=True, **kwargs) __readline = llexternal('readline', [rffi.CCHARP], rffi.CCHARP) From f6f5c56955fc324f0bb586f34a22dbc97f4baa8a Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sat, 14 Mar 2015 17:10:39 -0600 Subject: [PATCH 032/349] async repl is getting closer --- pixie/io.pxi | 6 +++--- pixie/repl.pxi | 20 ++++++++++++++++++++ pixie/stacklets.pxi | 4 +++- pixie/vm/reader.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ pixie/vm/rt.py | 2 ++ 5 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 pixie/repl.pxi diff --git a/pixie/io.pxi b/pixie/io.pxi index 5664180c..48ad51f8 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -188,11 +188,11 @@ (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) (st/yield-control))) - -(st/apply-blocking println "FROM OTHER THREAD <---!!!!!") +(comment + (st/apply-blocking println "FROM OTHER THREAD <---!!!!!") -(tcp-server "0.0.0.0" 4242 nil) + (tcp-server "0.0.0.0" 4242 nil)) (comment (defmacro make-readline-async [] `(let [libname ~(ffi-infer/compile-library {:prefix "pixie.io.readline" diff --git a/pixie/repl.pxi b/pixie/repl.pxi new file mode 100644 index 00000000..f00e79c2 --- /dev/null +++ b/pixie/repl.pxi @@ -0,0 +1,20 @@ +(ns pixie.repl + (require pixie.stacklets :as st) + (require pixie.io :as io) + (require pixie.ffi-infer :as f)) + +(f/with-config {:library "edit" + :includes ["editline/readline.h"]} + (f/defcfn readline)) + + +(defn run-repl [] + (let [rdr (reader-fn (fn [] (str (st/apply-blocking readline "user->>>") "\n")))] + (loop [x 1] + (when (< x 3) + + (let [form (read rdr false)] + (println (eval form)) + (recur (inc x))))))) + +(run-repl) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 19dc3ca6..a912e7c0 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -83,7 +83,9 @@ (defn -with-stacklets [fn] (let [[h f] ((new-stacklet fn) nil)] (f h) - (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT))) + (loop [] + (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT) + (recur)))) (defmacro with-stacklets [& body] `(-with-stacklets diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 3049ae2f..cb91cfd4 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -2,6 +2,7 @@ import pixie.vm.object as object from pixie.vm.object import affirm, runtime_error import pixie.vm.code as code +from pixie.vm.code import as_var from pixie.vm.primitives import nil, true, false import pixie.vm.numbers as numbers from pixie.vm.cons import cons @@ -89,6 +90,40 @@ def unread(self, ch): assert self._string_reader is not None self._string_reader.unread(ch) + +class UserSpaceReader(PlatformReader): + def __init__(self, reader_fn): + self._string_reader = None + self._reader_fn = reader_fn + + + def read(self): + if self._string_reader is None: + result = rt.name(self._reader_fn.invoke([])) + if result == u"": + raise EOFError() + self._string_reader = StringReader(result) + + try: + return self._string_reader.read() + except EOFError: + self._string_reader = None + return self.read() + + def reset_line(self): + self._string_reader = None + + def unread(self, ch): + assert self._string_reader is not None + self._string_reader.unread(ch) + +@as_var(u"reader-fn") +def reader_fn(fn): + """(reader-fn f) + Creates a new reader that can be passed to read, that will call the given f when a new string + of input is needed.""" + return MetaDataReader(UserSpaceReader(fn)) + class LinePromise(object.Object): _type = object.Type(u"pixie.stdlib.LinePromise") def type(self): @@ -764,5 +799,14 @@ def read(rdr, error_on_eof): return itm +@as_var("read") +def _read_(rdr, error_on_eof): + """(read rdr error-on-eof) + Reads a single form from the input reader. If error-on-eof is true, an error will be thrown if eof is reached + and a valid form has not been parsed. Else will return eof""" + assert isinstance(rdr, PlatformReader) + return read(rdr, rt.is_true(error_on_eof)) + + diff --git a/pixie/vm/rt.py b/pixie/vm/rt.py index ce6dbe9c..bfc835a6 100644 --- a/pixie/vm/rt.py +++ b/pixie/vm/rt.py @@ -157,6 +157,8 @@ def reinit(): globals()["__inited__"] = True + globals()["is_true"] = lambda x: False if x is false or x is nil or x is None else True + From 195559e6f2d33565bca05e4ef8d706dc023291fc Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sun, 15 Mar 2015 10:17:58 +0000 Subject: [PATCH 033/349] A couple of small doc and typo fixes --- pixie/io.pxi | 2 +- pixie/stdlib.pxi | 10 +++++----- pixie/string.pxi | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 46524dbf..6c38dcdb 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -144,7 +144,7 @@ (defn popen-read - {:doc "Open a file for reading, returning a IInputStream" + {:doc "Open a process for reading, returning a IInputStream" :added "0.1"} [command] (assert (string? command) "Command must be a string") diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 067e52c9..68cef62e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -636,14 +636,14 @@ returns true" (defn nth {:doc "Returns the element at the idx. If the index is not found it will return an error. - However, if you specify a not-found parameter, it will substitue that instead" + However, if you specify a not-found parameter, it will substitute that instead" :signatures [[coll idx] [coll idx not-found]] :added "0.1"} ([coll idx] (-nth coll idx)) ([coll idx not-found] (-nth-not-found coll idx not-found))) (defn first - {:doc "Returns the first item in coll, if coll implements IIndexed nth will be used to retreive + {:doc "Returns the first item in coll, if coll implements IIndexed nth will be used to retrieve the item from the collection." :signatures [[coll]] :added "0.1"} @@ -653,7 +653,7 @@ returns true" (-first coll))) (defn second - {:doc "Returns the second item in coll, if coll implements IIndexed nth will be used to retreive + {:doc "Returns the second item in coll, if coll implements IIndexed nth will be used to retrieve the item from the collection." :signatures [[coll]] :added "0.1"} @@ -663,7 +663,7 @@ returns true" (first (next coll)))) (defn third - {:doc "Returns the third item in coll, if coll implements IIndexed nth will be used to retreive + {:doc "Returns the third item in coll, if coll implements IIndexed nth will be used to retrieve the item from the collection." :signatures [[coll]] :added "0.1"} @@ -673,7 +673,7 @@ returns true" (first (next (next coll))))) (defn fourth - {:doc "Returns the fourth item in coll, if coll implements IIndexed nth will be used to retreive + {:doc "Returns the fourth item in coll, if coll implements IIndexed nth will be used to retrieve the item from the collection." :signatures [[coll]] :added "0.1"} diff --git a/pixie/string.pxi b/pixie/string.pxi index 48b2f8dd..496d3363 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -37,18 +37,18 @@ (str (substring s 0 i) r (substring s (+ i (count x))))))) (defn join - {:doc "Join the elements of the collection using an optional seperator." + {:doc "Join the elements of the collection using an optional separator" :examples [["(require pixie.string :as s)"] ["(s/join [1 2 3])" nil "123"] ["(s/join \", \" [1 2 3])" nil "1, 2, 3"]]} ([coll] (join "" coll)) - ([seperator coll] + ([separator coll] (loop [s (seq coll) res ""] (cond (nil? s) res (nil? (next s)) (str res (first s)) - :else (recur (next s) (str res (first s) seperator)))))) + :else (recur (next s) (str res (first s) separator)))))) (defn blank? "True if s is nil, empty, or contains only whitespace." From 517637ca5630e34e36105ecde3a93144b44b7025 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 15 Mar 2015 16:01:50 +0000 Subject: [PATCH 034/349] Sort arities when creating arity errors Before they just got spat out in order of definition. Uses rpthons listsort to do sorting. --- pixie/vm/code.py | 27 ++++++++++++++++++++++++--- tests/pixie/tests/test-fns.pxi | 12 +++++++----- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 9e3ad263..c8c4f456 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -3,6 +3,7 @@ from pixie.vm.object import affirm, runtime_error from pixie.vm.primitives import nil, false from rpython.rlib.rarithmetic import r_uint +from rpython.rlib.listsort import TimSort from rpython.rlib.jit import elidable_promote, promote import rpython.rlib.jit as jit import pixie.vm.rt as rt @@ -124,6 +125,21 @@ def stack_size(self): def invoke_with(self, args, this_fn): return self.invoke(args) +def join_last(words, sep): + """ + Joins by commas and uses 'sep' on last word. + + Eg. join_last(['dog', 'cat', 'rat'] , 'and') = 'dog, cat and rat' + """ + if len(words) == 1: + return words[0] + else: + if len(words) == 2: + s = words[0] + u" " + sep + u" " + words[1] + else: + s = u", ".join(words[0:-1]) + s += u" " + sep + u" " + words[-1] + return s class MultiArityFn(BaseCode): _type = object.Type(u"pixie.stdlib.MultiArityFn") @@ -153,13 +169,18 @@ def get_fn(self, arity): return self._rest_fn acc = [] - for x in self._arities: + sorted = TimSort(self.get_arities()) + sorted.sort() + for x in sorted.list: acc.append(unicode(str(x))) if self._rest_fn: - acc.append(unicode(str(self._rest_fn.required_arity())) + u" or more") + acc.append(unicode(str(self._rest_fn.required_arity())) + u"+") + + runtime_error(u"Wrong number of arguments " + unicode(str(arity)) + u" for function '" + unicode(self._name) + u"'. Expected " + join_last(acc, u"or")) - runtime_error(u"Wrong number of arguments " + unicode(str(arity)) + u" for function '" + unicode(self._name) + u"'. Expected " + u",".join(acc)) + def get_arities(self): + return self._arities.keys() def invoke(self, args): return self.invoke_with(args, self) diff --git a/tests/pixie/tests/test-fns.pxi b/tests/pixie/tests/test-fns.pxi index 12f74bc9..23915d0c 100644 --- a/tests/pixie/tests/test-fns.pxi +++ b/tests/pixie/tests/test-fns.pxi @@ -42,17 +42,19 @@ "Invalid number of arguments 1 for function 'arity-2'. Expected 2" (arity-2 :foo)) (t/assert-throws? RuntimeException - "Wrong number of arguments 2 for function 'arity-0-or-1'. Expected 1,0" + "Wrong number of arguments 2 for function 'arity-0-or-1'. Expected 0 or 1" (arity-0-or-1 :foo :bar)) (t/assert-throws? RuntimeException - "Wrong number of arguments 3 for function 'arity-0-or-1'. Expected 1,0" + "Wrong number of arguments 3 for function 'arity-0-or-1'. Expected 0 or 1" (arity-0-or-1 :foo :bar :baz)) (t/assert-throws? RuntimeException - "Wrong number of arguments 2 for function 'arity-1-or-3'. Expected 3,1" + "Wrong number of arguments 2 for function 'arity-1-or-3'. Expected 1 or 3" (arity-1-or-3 :foo :bar)) (t/assert-throws? RuntimeException - "Wrong number of arguments 0 for function 'arity-1-or-3'. Expected 3,1" + "Wrong number of arguments 0 for function 'arity-1-or-3'. Expected 1 or 3" (arity-1-or-3)) (t/assert-throws? RuntimeException - "Wrong number of arguments 2 for function 'arity-0-or-1-or-3-or-more'. Expected 1,0,3 or more" + "Wrong number of arguments 2 for function 'arity-0-or-1-or-3-or-more'. Expected 0, 1 or 3+" (arity-0-or-1-or-3-or-more :foo :bar)))) + +(t/deftest test-code-arities) From 3b515123b110207ff4ac25e5e7daec793ed1a51a Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 15 Mar 2015 16:03:21 +0000 Subject: [PATCH 035/349] Catch EOFErrors while reading things Throws better errors when trying to parse lists, vectors, maps, sets and strings --- pixie/vm/reader.py | 66 ++++++++++++++++------------- tests/pixie/tests/test-readeval.pxi | 40 +++++++++++++++++ 2 files changed, 77 insertions(+), 29 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 2ba86059..803f3359 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -210,8 +210,12 @@ class ListReader(ReaderHandler): def invoke(self, rdr, ch): lst = [] while True: - eat_whitespace(rdr) + try: + eat_whitespace(rdr) + except EOFError: + throw_syntax_error_with_data(rdr, u"Unmatched list open '('") ch = rdr.read() + if ch == u")": if len(lst) == 0: return EmptyList() @@ -219,11 +223,10 @@ def invoke(self, rdr, ch): for x in range(len(lst) - 1, -1, -1): acc = cons(lst[x], acc) return acc - + rdr.unread(ch) - itm = read(rdr, True, always_return_form=False) - if itm != rdr: - lst.append(itm) + + lst.append(read(rdr, True)) class UnmatchedListReader(ReaderHandler): def invoke(self, rdr, ch): @@ -233,15 +236,17 @@ class VectorReader(ReaderHandler): def invoke(self, rdr, ch): acc = EMPTY_VECTOR while True: - eat_whitespace(rdr) + try: + eat_whitespace(rdr) + except EOFError: + throw_syntax_error_with_data(rdr, u"Unmatched vector open '['") + ch = rdr.read() if ch == u"]": return acc rdr.unread(ch) - itm = read(rdr, True, always_return_form=False) - if itm != rdr: - acc = rt.conj(acc, itm) + acc = rt.conj(acc, read(rdr, True)) class UnmatchedVectorReader(ReaderHandler): def invoke(self, rdr, ch): @@ -251,25 +256,24 @@ class MapReader(ReaderHandler): def invoke(self, rdr, ch): acc = EMPTY_MAP while True: - eat_whitespace(rdr) + try: + eat_whitespace(rdr) + except EOFError: + throw_syntax_error_with_data(rdr, u"Unmatched map open '{'") + ch = rdr.read() if ch == u"}": return acc rdr.unread(ch) - itm = read(rdr, True, always_return_form=False) - if itm != rdr: - k = itm - itm = rdr - while itm == rdr: - itm = read(rdr, False, always_return_form=False) - v = itm - acc = rt._assoc(acc, k, v) + k = read(rdr, True) + v = read(rdr, False) + acc = rt._assoc(acc, k, v) return acc class UnmatchedMapReader(ReaderHandler): def invoke(self, rdr, ch): - affirm(False, u"Unmatched Map brace ") + affirm(False, u"Unmatched Map brace '}'") class QuoteReader(ReaderHandler): def invoke(self, rdr, ch): @@ -303,7 +307,7 @@ def invoke(self, rdr, ch): try: v = rdr.read() except EOFError: - return throw_syntax_error_with_data(rdr, u"umatched quote") + return throw_syntax_error_with_data(rdr, u"Unmatched string quote '\"'") if v == "\"": return rt.wrap(u"".join(acc)) @@ -329,7 +333,7 @@ def invoke(self, rdr, ch): acc.append(v) def read_token(rdr): - acc = rdr.read() + acc = u"" while True: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): @@ -558,7 +562,10 @@ class SetReader(ReaderHandler): def invoke(self, rdr, ch): acc = EMPTY_SET while True: - eat_whitespace(rdr) + try: + eat_whitespace(rdr) + except EOFError: + throw_syntax_error_with_data(rdr, u"Unmatched set open '#{'") ch = rdr.read() if ch == u"}": return acc @@ -582,13 +589,17 @@ def invoke(self, rdr, ch): class LineCommentReader(ReaderHandler): def invoke(self, rdr, ch): self.skip_line(rdr) - return rdr + return read(rdr, True) def skip_line(self, rdr): while True: ch = rdr.read() if ch == u"\n": return + elif ch == u"\r": + ch2 = rdr.read() + if ch2 == u"\n": + return handlers = {u"(": ListReader(), u")": UnmatchedListReader(), @@ -728,7 +739,7 @@ def throw_syntax_error_with_data(rdr, txt): -def read(rdr, error_on_eof, always_return_form=True): +def read(rdr, error_on_eof): try: eat_whitespace(rdr) except EOFError as ex: @@ -747,8 +758,6 @@ def read(rdr, error_on_eof, always_return_form=True): macro = handlers.get(ch, None) if macro is not None: itm = macro.invoke(rdr, ch) - if always_return_form and itm == rdr: - return read(rdr, error_on_eof, always_return_form=always_return_form) elif is_digit(ch): itm = read_number(rdr, ch) @@ -766,9 +775,8 @@ def read(rdr, error_on_eof, always_return_form=True): else: itm = read_symbol(rdr, ch) - if itm != rdr: - if rt.has_meta_QMARK_(itm): - itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) + if rt.has_meta_QMARK_(itm): + itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) return itm diff --git a/tests/pixie/tests/test-readeval.pxi b/tests/pixie/tests/test-readeval.pxi index 01be1a3d..dbafe99f 100644 --- a/tests/pixie/tests/test-readeval.pxi +++ b/tests/pixie/tests/test-readeval.pxi @@ -15,3 +15,43 @@ (t/assert= (read-string "false") false) (t/assert= (read-string "true") true) (t/assert= (read-string "(foo (bar (baz)))") '(foo (bar (baz))))) + +(t/deftest test-list-unclosed-list-fail + (t/assert-throws? RuntimeException + "Unmatched list open '('" + (read-string "(")) + (t/assert-throws? RuntimeException + "Unmatched list open '('" + (read-string "((foo bar)"))) + +(t/deftest test-vector-unclosed-list-fail + (t/assert-throws? RuntimeException + "Unmatched vector open '['" + (read-string "[")) + (t/assert-throws? RuntimeException + "Unmatched vector open '['" + (read-string "[[foo bar]"))) + +(t/deftest test-map-unclosed-list-fail + (t/assert-throws? RuntimeException + "Unmatched map open '{'" + (read-string "{")) + (t/assert-throws? RuntimeException + "Unmatched map open '{'" + (read-string "{foo {a b}"))) + +(t/deftest test-set-unclosed-list-fail + (t/assert-throws? RuntimeException + "Unmatched set open '#{'" + (read-string "#{")) + (t/assert-throws? RuntimeException + "Unmatched set open '#{'" + (read-string "#{foo #{a}"))) + +(t/deftest test-string-unclosed-fail + (t/assert-throws? RuntimeException + "Unmatched string quote '\"'" + (read-string "\"")) + (t/assert-throws? RuntimeException + "Unmatched string quote '\"'" + (read-string "\"foo"))) From 4257329b617b8d769099cb9d01748b5450ea86b7 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 15 Mar 2015 23:17:27 +0000 Subject: [PATCH 036/349] Make errors work in compiled mode --- pixie/vm/primitives.py | 5 ++++- pixie/vm/reader.py | 41 ++++++++++++++++++++++------------------- pixie/vm/stdlib.py | 4 ++-- 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/pixie/vm/primitives.py b/pixie/vm/primitives.py index acb37963..6bab30aa 100644 --- a/pixie/vm/primitives.py +++ b/pixie/vm/primitives.py @@ -4,6 +4,9 @@ class Nil(object.Object): _type = object.Type(u"pixie.stdlib.Nil") + def __repr__(self): + return u"nil" + def type(self): return Nil._type @@ -19,4 +22,4 @@ def type(self): true = Bool() -false = Bool() \ No newline at end of file +false = Bool() diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 803f3359..daac8913 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -41,7 +41,7 @@ class PlatformReader(object.Object): def read(self): assert False - def unread(self, ch): + def unread(self): pass def reset_line(self): @@ -61,7 +61,7 @@ def read(self): self._idx += 1 return ch - def unread(self, ch): + def unread(self): self._idx -= 1 class PromptReader(PlatformReader): @@ -85,9 +85,9 @@ def read(self): def reset_line(self): self._string_reader = None - def unread(self, ch): + def unread(self): assert self._string_reader is not None - self._string_reader.unread(ch) + self._string_reader.unread() class LinePromise(object.Object): _type = object.Type(u"pixie.stdlib.LinePromise") @@ -168,7 +168,7 @@ def get_metadata(self): FILE_KW, rt.wrap(self._filename)) - def unread(self, ch): + def unread(self): affirm(not self._has_unread, u"Can't unread twice") self._has_unread = True self._prev_chr = self._cur_ch @@ -199,7 +199,7 @@ def eat_whitespace(rdr): ch = rdr.read() if is_whitespace(ch): continue - rdr.unread(ch) + rdr.unread() return class ReaderHandler(py_object): @@ -213,6 +213,7 @@ def invoke(self, rdr, ch): try: eat_whitespace(rdr) except EOFError: + rdr.unread() throw_syntax_error_with_data(rdr, u"Unmatched list open '('") ch = rdr.read() @@ -224,7 +225,7 @@ def invoke(self, rdr, ch): acc = cons(lst[x], acc) return acc - rdr.unread(ch) + rdr.unread() lst.append(read(rdr, True)) @@ -239,13 +240,14 @@ def invoke(self, rdr, ch): try: eat_whitespace(rdr) except EOFError: + rdr throw_syntax_error_with_data(rdr, u"Unmatched vector open '['") ch = rdr.read() if ch == u"]": return acc - rdr.unread(ch) + rdr.unread() acc = rt.conj(acc, read(rdr, True)) class UnmatchedVectorReader(ReaderHandler): @@ -265,7 +267,7 @@ def invoke(self, rdr, ch): if ch == u"}": return acc - rdr.unread(ch) + rdr.unread() k = read(rdr, True) v = read(rdr, False) acc = rt._assoc(acc, k, v) @@ -288,7 +290,7 @@ def invoke(self, rdr, ch): itm = read(rdr, True) nms = rt.name(rt.ns.deref()) else: - rdr.unread(ch) + rdr.unread() itm = read(rdr, True) affirm(isinstance(itm, Symbol), u"Can't keyword quote a non-symbol") @@ -337,7 +339,7 @@ def read_token(rdr): while True: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): - rdr.unread(ch) + rdr.unread() return acc acc += ch @@ -469,7 +471,7 @@ def invoke(self, rdr, ch): if ch == "@": sym = UNQUOTE_SPLICING else: - rdr.unread(ch) + rdr.unread() form = read(rdr, True) return rt.list(sym, form) @@ -496,7 +498,7 @@ def invoke(self, rdr, ch): return read_symbol(rdr, ch) ch = rdr.read() - rdr.unread(ch) + rdr.unread() if is_whitespace(ch) or is_terminating_macro(ch): return ArgReader.register_next_arg(1) @@ -536,7 +538,7 @@ def invoke(self, rdr, ch): try: ARG_ENV.set_value(rt.assoc(EMPTY_MAP, ARG_MAX, rt.wrap(-1))) - rdr.unread(ch) + rdr.unread() form = read(rdr, True) args = EMPTY_VECTOR @@ -570,7 +572,7 @@ def invoke(self, rdr, ch): if ch == u"}": return acc - rdr.unread(ch) + rdr.unread() acc = acc.conj(read(rdr, True)) dispatch_handlers = { @@ -683,7 +685,7 @@ def read_number(rdr, ch): while True: ch = rdr.read() if is_whitespace(ch) or ch in handlers: - rdr.unread(ch) + rdr.unread() break acc.append(ch) except EOFError: @@ -701,7 +703,7 @@ def read_symbol(rdr, ch): while True: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): - rdr.unread(ch) + rdr.unread() break acc.append(ch) except EOFError: @@ -756,6 +758,7 @@ def read(rdr, error_on_eof): meta = nil macro = handlers.get(ch, None) + itm = nil if macro is not None: itm = macro.invoke(rdr, ch) @@ -765,11 +768,11 @@ def read(rdr, error_on_eof): elif ch == u"-": ch2 = rdr.read() if is_digit(ch2): - rdr.unread(ch2) + rdr.unread() itm = read_number(rdr, ch) else: - rdr.unread(ch2) + rdr.unread() itm = read_symbol(rdr, ch) else: diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 4cfe5d05..0d84d625 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -732,7 +732,7 @@ def _ici(meta): return InterpreterCodeInfo(line, line_number.int_val() if line_number is not nil else 0, col_number.int_val() if col_number is not nil else 0, - rt.name(file) if file is not nil else u"") # @wrap_fn @@ -808,4 +808,4 @@ def ex_msg(e): @extend(_doc, code.NativeFn._type) def _doc(self): assert isinstance(self, code.NativeFn) - return rt.wrap(self._doc) \ No newline at end of file + return rt.wrap(self._doc) From 8b0034845e4e819f0811cd940399d341a3e16e0c Mon Sep 17 00:00:00 2001 From: Arsene Rei Date: Mon, 16 Mar 2015 21:26:17 -0700 Subject: [PATCH 037/349] Add clean Makefile task --- Makefile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Makefile b/Makefile index bb5cda71..59a30e03 100644 --- a/Makefile +++ b/Makefile @@ -69,3 +69,9 @@ compile_src: clean_pxic: find * -name "*.pxic" | xargs rm + +clean: clean_pxic + rm -rf ./lib + rm -rf ./include + rm -f ./pixie-vm + rm -f ./*.pyc From 0eaff7da98d01e06e6349f2355c2720103c24066 Mon Sep 17 00:00:00 2001 From: Arsene Rei Date: Mon, 16 Mar 2015 21:27:07 -0700 Subject: [PATCH 038/349] Move externals build dir into project --- Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 59a30e03..46511f39 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ all: help -EXTERNALS=../externals +EXTERNALS=externals PYTHON ?= python PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy @@ -73,5 +73,6 @@ clean_pxic: clean: clean_pxic rm -rf ./lib rm -rf ./include + rm -rf ./externals rm -f ./pixie-vm rm -f ./*.pyc From c956093ae4c80487a1ded77c368260c9cb587275 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 17 Mar 2015 06:03:33 -0600 Subject: [PATCH 039/349] async repl, bug fixes, etc --- Makefile | 4 ++ pixie/ffi-infer.pxi | 8 ---- pixie/io.pxi | 39 +++++++++------- pixie/repl.pxi | 27 +++++++----- pixie/stacklets.pxi | 38 +++++++++++----- pixie/vm/reader.py | 55 ++++++++++++++++------- pixie/vm/test/test_compile.py | 2 +- pixie/vm/test/test_reader.py | 2 +- target.py | 83 ++++++++++++++++++++--------------- 9 files changed, 157 insertions(+), 101 deletions(-) diff --git a/Makefile b/Makefile index 37645acb..16cdf85b 100644 --- a/Makefile +++ b/Makefile @@ -24,6 +24,10 @@ build_with_jit: fetch_externals build_no_jit: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target.py +compile_basics: + @echo -e "\e[31mWARNING: Compiling core libs. If you want to modify one of these files delete the .pxic files first\e[0m" + ./pixie-vm -c pixie/uv.pxi -c pixie/io.pxi -c pixie/stacklets.pxi -c pixie/stdlib.pxi + build_preload_with_jit: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --opt=jit target_preload.py 2>&1 >/dev/null | grep -v 'WARNING' diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 8056b57e..e6964524 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -248,14 +248,6 @@ return 0; -(compile-library - {:prefix "foo" - :includes ["uv.h"]} - "int foo(int bar) - { - return 42; - }") - (comment diff --git a/pixie/io.pxi b/pixie/io.pxi index 48ad51f8..483c9f9f 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,5 +1,6 @@ (ns pixie.io (require pixie.streams :as st :refer :all) + (require pixie.io-blocking :as io-blocking) (require pixie.uv :as uv) (require pixie.stacklets :as st) (require pixie.ffi :as ffi) @@ -169,24 +170,28 @@ (dispose! c) result)) +(defn run-command [command] + (st/apply-blocking io-blocking/run-command command)) -(defn tcp-server [ip port on-connection] - (assert (string? ip) "Ip should be a string") - (assert (integer? port) "Port should be a int") - (let [server (uv/uv_tcp_t) - bind-addr (uv/sockaddr_in) - _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) - on-new-connetion (atom nil)] - (reset! on-new-connetion - (ffi-prep-callback - uv/uv_connection_cb - (fn [server status] - (when (not (= status -1)) - (println "Got Client!!!!!!!"))))) - (uv/uv_tcp_init (uv/uv_default_loop) server) - (uv/uv_tcp_bind server bind-addr 0) - (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) - (st/yield-control))) +(comment + + (defn tcp-server [ip port on-connection] + (assert (string? ip) "Ip should be a string") + (assert (integer? port) "Port should be a int") + (let [server (uv/uv_tcp_t) + bind-addr (uv/sockaddr_in) + _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) + on-new-connetion (atom nil)] + (reset! on-new-connetion + (ffi-prep-callback + uv/uv_connection_cb + (fn [server status] + (when (not (= status -1)) + (println "Got Client!!!!!!!"))))) + (uv/uv_tcp_init (uv/uv_default_loop) server) + (uv/uv_tcp_bind server bind-addr 0) + (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) + (st/yield-control)))) (comment (st/apply-blocking println "FROM OTHER THREAD <---!!!!!") diff --git a/pixie/repl.pxi b/pixie/repl.pxi index f00e79c2..c9c8e9a4 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -8,13 +8,20 @@ (f/defcfn readline)) -(defn run-repl [] - (let [rdr (reader-fn (fn [] (str (st/apply-blocking readline "user->>>") "\n")))] - (loop [x 1] - (when (< x 3) - - (let [form (read rdr false)] - (println (eval form)) - (recur (inc x))))))) - -(run-repl) +(defn repl [] + (let [rdr (reader-fn (fn [] + (let [prompt (if (= 0 pixie.stdlib/*reading-form*) + (str (name pixie.stdlib/*ns*) " => ") + "") + line (st/apply-blocking readline prompt)] + (if line + (str line "\n") + ""))))] + (loop [] + (try (let [form (read rdr false)] + (if (= form eof) + (exit 0) + (println (eval form)))) + (catch ex + (println "ERROR: \n" ex))) + (recur)))) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index a912e7c0..e122c91b 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -4,8 +4,12 @@ ;; If we don't do this, compiling this file doesn't work since the def will clear out ;; the existing value. -(if (undefined? (var stacklet-loop-h)) - (def stacklet-loop-h (atom nil))) +(when (undefined? (var stacklet-loop-h)) + (def stacklet-loop-h (atom nil)) + (def running-threads (atom 0)) + (def main-loop-running? (atom false)) + (def main-loop-lock (-create-lock)) + (-acquire-lock main-loop-lock true)) @@ -34,7 +38,11 @@ (f) (catch ex (println ex)))))) (uv/uv_async_init (uv/uv_default_loop) a @cb) - (uv/uv_async_send a))) + (uv/uv_async_send a) + (when (not @main-loop-running?) + (reset! main-loop-running? true) + (-release-lock main-loop-lock)) + nil)) (defn yield-control [] @@ -53,7 +61,7 @@ (fn [handle] (try (run-and-process k) - (uv/uv_timer_stop timer) + (uv/uv_timer_stop timer) (-dispose! @cb) (catch ex (println ex)))))) @@ -70,22 +78,29 @@ (defmacro spawn [& body] `(-spawn (fn [h# _] - (try - (reset! stacklet-loop-h h#) - (let [result# (do ~@body)] - (call-cc (fn [_] nil))) - (catch e - (println e)))))) + (try + (swap! running-threads inc) + (reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (swap! running-threads dec) + (call-cc (fn [_] nil))) + (catch e + (println e)))))) (defn -with-stacklets [fn] + (swap! running-threads inc) + (reset! main-loop-running? true) (let [[h f] ((new-stacklet fn) nil)] (f h) (loop [] (uv/uv_run (uv/uv_default_loop) uv/UV_RUN_DEFAULT) - (recur)))) + (when (> @running-threads 0) + (reset! main-loop-running? false) + (-acquire-lock main-loop-lock true) + (recur))))) (defmacro with-stacklets [& body] `(-with-stacklets @@ -93,6 +108,7 @@ (try (reset! stacklet-loop-h h#) (let [result# (do ~@body)] + (swap! running-threads dec) (call-cc (fn [_] nil))) (catch e (println e)))))) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index cb91cfd4..ef5cbc1a 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -21,6 +21,10 @@ from rpython.rlib.rbigint import rbigint from rpython.rlib.rsre import rsre_re as re +READING_FORM_VAR = code.intern_var(u"pixie.stdlib", u"*reading-form*") +READING_FORM_VAR.set_dynamic() +READING_FORM_VAR.set_root(false) + LINE_NUMBER_KW = keyword(u"line-number") COLUMN_NUMBER_KW = keyword(u"column-number") LINE_KW = keyword(u"line") @@ -100,6 +104,7 @@ def __init__(self, reader_fn): def read(self): if self._string_reader is None: result = rt.name(self._reader_fn.invoke([])) + code._dynamic_vars.set_var_value(READING_FORM_VAR, rt.wrap(READING_FORM_VAR.deref().int_val() + 1)) if result == u"": raise EOFError() self._string_reader = StringReader(result) @@ -256,7 +261,7 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - lst.append(read(rdr, True)) + lst.append(read_inner(rdr, True)) class UnmatchedListReader(ReaderHandler): def invoke(self, rdr, ch): @@ -272,7 +277,7 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - acc = rt.conj(acc, read(rdr, True)) + acc = rt.conj(acc, read_inner(rdr, True)) class UnmatchedVectorReader(ReaderHandler): def invoke(self, rdr, ch): @@ -288,8 +293,8 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - k = read(rdr, True) - v = read(rdr, False) + k = read_inner(rdr, True) + v = read_inner(rdr, False) acc = rt._assoc(acc, k, v) return acc @@ -299,7 +304,7 @@ def invoke(self, rdr, ch): class QuoteReader(ReaderHandler): def invoke(self, rdr, ch): - itm = read(rdr, True) + itm = read_inner(rdr, True) return cons(symbol(u"quote"), cons(itm)) class KeywordReader(ReaderHandler): @@ -307,11 +312,11 @@ def invoke(self, rdr, ch): nms = u"" ch = rdr.read() if ch == u":": - itm = read(rdr, True) + itm = read_inner(rdr, True) nms = rt.name(rt.ns.deref()) else: rdr.unread(ch) - itm = read(rdr, True) + itm = read_inner(rdr, True) affirm(isinstance(itm, Symbol), u"Can't keyword quote a non-symbol") if nms: @@ -407,7 +412,7 @@ def invoke(self, rdr, ch): class DerefReader(ReaderHandler): def invoke(self, rdr, ch): - return rt.cons(symbol(u"-deref"), rt.cons(read(rdr, True), nil)) + return rt.cons(symbol(u"-deref"), rt.cons(read_inner(rdr, True), nil)) QUOTE = symbol(u"quote") @@ -430,7 +435,7 @@ def is_unquote_splicing(form): class SyntaxQuoteReader(ReaderHandler): def invoke(self, rdr, ch): - form = read(rdr, True) + form = read_inner(rdr, True) with code.bindings(GEN_SYM_ENV, EMPTY_MAP): result = self.syntax_quote(form) @@ -493,13 +498,13 @@ def invoke(self, rdr, ch): else: rdr.unread(ch) - form = read(rdr, True) + form = read_inner(rdr, True) return rt.list(sym, form) class MetaReader(ReaderHandler): def invoke(self, rdr, ch): - meta = read(rdr, True) - obj = read(rdr, True) + meta = read_inner(rdr, True) + obj = read_inner(rdr, True) if isinstance(meta, Keyword): meta = rt.hashmap(meta, true) @@ -522,7 +527,7 @@ def invoke(self, rdr, ch): if is_whitespace(ch) or is_terminating_macro(ch): return ArgReader.register_next_arg(1) - n = read(rdr, True) + n = read_inner(rdr, True) if rt.eq(n, ARG_AMP): return ArgReader.register_next_arg(-1) if not isinstance(n, numbers.Integer): @@ -559,7 +564,7 @@ def invoke(self, rdr, ch): ARG_ENV.set_value(rt.assoc(EMPTY_MAP, ARG_MAX, rt.wrap(-1))) rdr.unread(ch) - form = read(rdr, True) + form = read_inner(rdr, True) args = EMPTY_VECTOR percent_args = ARG_ENV.deref() @@ -590,7 +595,7 @@ def invoke(self, rdr, ch): return acc rdr.unread(ch) - acc = acc.conj(read(rdr, True)) + acc = acc.conj(read_inner(rdr, True)) dispatch_handlers = { u"{": SetReader(), @@ -608,7 +613,7 @@ def invoke(self, rdr, ch): class LineCommentReader(ReaderHandler): def invoke(self, rdr, ch): self.skip_line(rdr) - return read(rdr, True) + return read_inner(rdr, True) def skip_line(self, rdr): while True: @@ -738,9 +743,13 @@ def read_symbol(rdr, ch): class EOF(object.Object): _type = object.Type(u"EOF") + def type(self): + return EOF._type + eof = EOF() +code.intern_var(u"pixie.stdlib", u"eof").set_root(eof) @@ -758,7 +767,7 @@ def throw_syntax_error_with_data(rdr, txt): -def read(rdr, error_on_eof): +def read_inner(rdr, error_on_eof): try: eat_whitespace(rdr) except EOFError as ex: @@ -799,6 +808,16 @@ def read(rdr, error_on_eof): return itm + +def read(rdr, error_on_eof): + code._dynamic_vars.push_binding_frame() + code._dynamic_vars.set_var_value(READING_FORM_VAR, rt.wrap(0)) + try: + form = read_inner(rdr, error_on_eof) + return form + finally: + code._dynamic_vars.pop_binding_frame() + @as_var("read") def _read_(rdr, error_on_eof): """(read rdr error-on-eof) @@ -810,3 +829,5 @@ def _read_(rdr, error_on_eof): + + diff --git a/pixie/vm/test/test_compile.py b/pixie/vm/test/test_compile.py index eb73801d..6793e333 100644 --- a/pixie/vm/test/test_compile.py +++ b/pixie/vm/test/test_compile.py @@ -1,4 +1,4 @@ -from pixie.vm.reader import read, StringReader, eof +from pixie.vm.reader import read_inner, StringReader, eof from pixie.vm.object import Type from pixie.vm.cons import Cons from pixie.vm.numbers import Integer diff --git a/pixie/vm/test/test_reader.py b/pixie/vm/test/test_reader.py index 33a08152..d8f17d94 100644 --- a/pixie/vm/test/test_reader.py +++ b/pixie/vm/test/test_reader.py @@ -1,4 +1,4 @@ -from pixie.vm.reader import read, StringReader +from pixie.vm.reader import read_inner, StringReader from pixie.vm.object import Object from pixie.vm.cons import Cons from pixie.vm.numbers import Integer diff --git a/target.py b/target.py index d7f7ca3d..5bd33e85 100644 --- a/target.py +++ b/target.py @@ -1,5 +1,5 @@ from pixie.vm.compiler import compile, with_ns, NS_VAR -from pixie.vm.reader import StringReader, read, eof, PromptReader, MetaDataReader +from pixie.vm.reader import StringReader, read_inner, eof, PromptReader, MetaDataReader from pixie.vm.interpreter import interpret from rpython.jit.codewriter.policy import JitPolicy from rpython.rlib.jit import JitHookInterface, Counters @@ -54,44 +54,55 @@ def __init__(self, args): self._argv = args def inner_invoke(self, args): - from pixie.vm.keyword import keyword import pixie.vm.rt as rt - from pixie.vm.string import String - import pixie.vm.persistent_vector as vector - - print "Pixie 0.1 - Interactive REPL" - print "(" + platform.name + ", " + platform.cc + ")" - print ":exit-repl or Ctrl-D to quit" - print "----------------------------" - - with with_ns(u"user"): - NS_VAR.deref().include_stdlib() - - acc = vector.EMPTY - for x in self._argv: - acc = rt.conj(acc, rt.wrap(x)) - - PROGRAM_ARGUMENTS.set_root(acc) + from pixie.vm.code import intern_var + rt.load_ns(rt.wrap(u"pixie/repl.pxi")) - rdr = MetaDataReader(PromptReader()) + repl = intern_var(u"pixie.repl", u"repl") with with_ns(u"user"): - while True: - try: - val = read(rdr, False) - if val is eof: - break - val = interpret(compile(val)) - self.set_recent_vars(val) - except WrappedException as ex: - print "Error: ", ex._ex.__repr__() - rdr.reset_line() - self.set_error_var(ex._ex) - continue - if val is keyword(u"exit-repl"): - break - val = rt._repr(val) - assert isinstance(val, String), "str should always return a string" - print unicode_to_utf8(val._str) + repl.invoke([]) + + + + # def inner_invoke(self, args): + # from pixie.vm.keyword import keyword + # import pixie.vm.rt as rt + # from pixie.vm.string import String + # import pixie.vm.persistent_vector as vector + # + # print "Pixie 0.1 - Interactive REPL" + # print "(" + platform.name + ", " + platform.cc + ")" + # print ":exit-repl or Ctrl-D to quit" + # print "----------------------------" + # + # with with_ns(u"user"): + # NS_VAR.deref().include_stdlib() + # + # acc = vector.EMPTY + # for x in self._argv: + # acc = rt.conj(acc, rt.wrap(x)) + # + # PROGRAM_ARGUMENTS.set_root(acc) + # + # rdr = MetaDataReader(PromptReader()) + # with with_ns(u"user"): + # while True: + # try: + # val = read(rdr, False) + # if val is eof: + # break + # val = interpret(compile(val)) + # self.set_recent_vars(val) + # except WrappedException as ex: + # print "Error: ", ex._ex.__repr__() + # rdr.reset_line() + # self.set_error_var(ex._ex) + # continue + # if val is keyword(u"exit-repl"): + # break + # val = rt._repr(val) + # assert isinstance(val, String), "str should always return a string" + # print unicode_to_utf8(val._str) def set_recent_vars(self, val): if rt.eq(val, STAR_1.deref()): From 97b06baf2bb8cb676aec489868416bfc41e23f67 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 17 Mar 2015 06:41:59 -0600 Subject: [PATCH 040/349] tests pass, probably about time to merge --- pixie/io-blocking.pxi | 4 ++-- pixie/io.pxi | 6 +++--- pixie/stacklets.pxi | 11 ++++++----- pixie/vm/libs/ffi.py | 14 ++++++++++++-- pixie/vm/reader.py | 4 ++-- 5 files changed, 25 insertions(+), 14 deletions(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 18ded14a..326d5aca 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -119,8 +119,8 @@ read-count)) (read-byte [this] (fgetc fp)) - IClosable - (close [this] + IDisposable + (-dispose! [this] (pclose fp)) IReduce (-reduce [this f init] diff --git a/pixie/io.pxi b/pixie/io.pxi index 483c9f9f..045e14b5 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -10,7 +10,7 @@ `(defn ~nm ~args (let [f (fn [k#] (let [cb# (atom nil)] - (reset! cb# (ffi-prep-callback uv/uv_fs_cb + (reset! cb# (ffi/ffi-prep-callback uv/uv_fs_cb (fn [req#] (try (st/run-and-process k# (~return (pixie.ffi/cast req# uv/uv_fs_t))) @@ -46,7 +46,7 @@ read-count)) IDisposable (-dispose! [this] - (pixie.ffi/free uvbuf) + (dispose! uvbuf) (fs_close fp)) IReduce (-reduce [this f init] @@ -183,7 +183,7 @@ _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) on-new-connetion (atom nil)] (reset! on-new-connetion - (ffi-prep-callback + (ffi/ffi-prep-callback uv/uv_connection_cb (fn [server status] (when (not (= status -1)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index e122c91b..ac570593 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -1,5 +1,6 @@ (ns pixie.stacklets - (require pixie.uv :as uv)) + (require pixie.uv :as uv) + (require pixie.ffi :as ffi)) ;; If we don't do this, compiling this file doesn't work since the def will clear out ;; the existing value. @@ -30,7 +31,7 @@ (defn -run-later [f] (let [a (uv/uv_async_t) cb (atom nil)] - (reset! cb (ffi-prep-callback uv/uv_async_cb + (reset! cb (ffi/ffi-prep-callback uv/uv_async_cb (fn [handle] (try (uv/uv_close a close_cb) @@ -49,15 +50,15 @@ (call-cc (fn [k] (-run-later (partial run-and-process k))))) -(def close_cb (ffi-prep-callback uv/uv_close_cb - pixie.ffi/free)) +(def close_cb (ffi/ffi-prep-callback uv/uv_close_cb + pixie.ffi/dispose!)) ;;; Sleep (defn sleep [ms] (let [f (fn [k] (let [cb (atom nil) timer (uv/uv_timer_t)] - (reset! cb (ffi-prep-callback uv/uv_timer_cb + (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb (fn [handle] (try (run-and-process k) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index f56a0754..ead55775 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -4,7 +4,7 @@ from pixie.vm.object import runtime_error from pixie.vm.keyword import Keyword import pixie.vm.stdlib as proto -from pixie.vm.code import as_var, affirm, extend +from pixie.vm.code import as_var, affirm, extend, wrap_fn import pixie.vm.rt as rt from rpython.rtyper.lltypesystem import rffi, lltype, llmemory from pixie.vm.primitives import nil, true, false @@ -709,6 +709,14 @@ def set_val(self, k, v): return nil + def free_data(self): + lltype.free(self._buffer, flavor="raw") + +@wrap_fn +def _dispose_cstruct(self): + self.free_data() + + @as_var("pixie.ffi", "c-struct") def c_struct(name, size, spec): @@ -728,7 +736,9 @@ def c_struct(name, size, spec): d[nm] = (tp, offset.int_val()) - return CStructType(rt.name(name), size.int_val(), d) + tp = CStructType(rt.name(name), size.int_val(), d) + proto._dispose_BANG_.extend(tp, _dispose_cstruct) + return tp @as_var("pixie.ffi", "cast") def c_cast(frm, to): diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index df67d7fb..4c61f3c7 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -118,9 +118,9 @@ def read(self): def reset_line(self): self._string_reader = None - def unread(self, ch): + def unread(self): assert self._string_reader is not None - self._string_reader.unread(ch) + self._string_reader.unread() @as_var(u"reader-fn") def reader_fn(fn): From 004fa83861ea996aed5301c1118fbfd9c2e88938 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 16 Mar 2015 23:51:56 +0000 Subject: [PATCH 041/349] Not delete all of @justinj's comment reading fixes --- pixie/vm/reader.py | 43 +++++++++++++++++------------ tests/pixie/tests/test-readeval.pxi | 3 ++ 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index daac8913..8aa53bd2 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -213,7 +213,6 @@ def invoke(self, rdr, ch): try: eat_whitespace(rdr) except EOFError: - rdr.unread() throw_syntax_error_with_data(rdr, u"Unmatched list open '('") ch = rdr.read() @@ -226,8 +225,9 @@ def invoke(self, rdr, ch): return acc rdr.unread() - - lst.append(read(rdr, True)) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + lst.append(itm) class UnmatchedListReader(ReaderHandler): def invoke(self, rdr, ch): @@ -248,7 +248,10 @@ def invoke(self, rdr, ch): return acc rdr.unread() - acc = rt.conj(acc, read(rdr, True)) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + acc = rt.conj(acc, itm) + class UnmatchedVectorReader(ReaderHandler): def invoke(self, rdr, ch): @@ -268,9 +271,15 @@ def invoke(self, rdr, ch): return acc rdr.unread() - k = read(rdr, True) - v = read(rdr, False) - acc = rt._assoc(acc, k, v) + itm = read(rdr, True, always_return_form=False) + if itm != rdr: + k = itm + itm = rdr + while itm == rdr: + itm = read(rdr, False, always_return_form=False) + v = itm + acc = rt._assoc(acc, k, v) + return acc class UnmatchedMapReader(ReaderHandler): @@ -335,7 +344,7 @@ def invoke(self, rdr, ch): acc.append(v) def read_token(rdr): - acc = u"" + acc = rdr.read() while True: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): @@ -591,17 +600,13 @@ def invoke(self, rdr, ch): class LineCommentReader(ReaderHandler): def invoke(self, rdr, ch): self.skip_line(rdr) - return read(rdr, True) + return rdr def skip_line(self, rdr): while True: ch = rdr.read() if ch == u"\n": return - elif ch == u"\r": - ch2 = rdr.read() - if ch2 == u"\n": - return handlers = {u"(": ListReader(), u")": UnmatchedListReader(), @@ -740,8 +745,7 @@ def throw_syntax_error_with_data(rdr, txt): raise object.WrappedException(err) - -def read(rdr, error_on_eof): +def read(rdr, error_on_eof, always_return_form=True): try: eat_whitespace(rdr) except EOFError as ex: @@ -758,9 +762,11 @@ def read(rdr, error_on_eof): meta = nil macro = handlers.get(ch, None) - itm = nil if macro is not None: itm = macro.invoke(rdr, ch) + if always_return_form and itm == rdr: + return read(rdr, error_on_eof, always_return_form=always_return_form) + elif is_digit(ch): itm = read_number(rdr, ch) @@ -778,8 +784,9 @@ def read(rdr, error_on_eof): else: itm = read_symbol(rdr, ch) - if rt.has_meta_QMARK_(itm): - itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) + if itm != rdr: + if rt.has_meta_QMARK_(itm): + itm = rt.with_meta(itm, rt.merge(meta, rt.meta(itm))) return itm diff --git a/tests/pixie/tests/test-readeval.pxi b/tests/pixie/tests/test-readeval.pxi index dbafe99f..196ce3af 100644 --- a/tests/pixie/tests/test-readeval.pxi +++ b/tests/pixie/tests/test-readeval.pxi @@ -55,3 +55,6 @@ (t/assert-throws? RuntimeException "Unmatched string quote '\"'" (read-string "\"foo"))) + +(t/deftest test-comments-in-forms + (t/assert= (read-string "(foo ; a comment\n )") '(foo))) From ece8c167ebbe0e14e9520e635c16e38701d84b40 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 17 Mar 2015 16:47:27 -0600 Subject: [PATCH 042/349] adds a async namespace. Includes futures and promises --- pixie/async.pxi | 34 ++++++++++++++++++++++++++++++++ pixie/stacklets.pxi | 25 ----------------------- tests/pixie/tests/test-async.pxi | 15 ++++++++++++++ 3 files changed, 49 insertions(+), 25 deletions(-) create mode 100644 pixie/async.pxi create mode 100644 tests/pixie/tests/test-async.pxi diff --git a/pixie/async.pxi b/pixie/async.pxi new file mode 100644 index 00000000..11ccb268 --- /dev/null +++ b/pixie/async.pxi @@ -0,0 +1,34 @@ +(ns pixie.async + (require pixie.stacklets :as st)) + + +(deftype Promise [val pending-callbacks delivered?] + IDeref + (-deref [self] + (println "waiting... " delivered?) + (if delivered? + val + (do + (st/call-cc (fn [k] + (swap! pending-callbacks conj + (fn [v] + (st/-run-later (partial st/run-and-process k v))))))))) + IFn + (-invoke [self v] + (println "delivering....") + (assert (not delivered?) "Can only deliver a promise once") + (set-field! self :val v) + (set-field! self :delivered? true) + (println @pending-callbacks) + (doseq [f @pending-callbacks] + (f v)) + (reset! pending-callbacks nil) + nil)) + +(defn promise [] + (->Promise nil (atom []) false)) + +(defmacro future [& body] + `(let [p# (promise)] + (st/spawn (p# (do ~@body))) + p#)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index ac570593..5673afcf 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -118,34 +118,9 @@ (with-stacklets (f))) - -(deftype Promise [val pending-callbacks delivered?] - IDeref - (-deref [self] - (if delivered? - val - (do - (call-cc (fn [k] - (swap! pending-callbacks conj - (fn [v] - (-run-later (partial run-and-process k v))))))))) - IFn - (-invoke [self v] - (assert (not delivered?) "Can only deliver a promise once") - (set-field! self :val v) - (println @pending-callbacks) - (doseq [f @pending-callbacks] - (f v)) - (reset! pending-callbacks nil) - nil)) - -(defn promise [] - (->Promise nil (atom []) false)) - (defprotocol IThreadPool (-execute [this work-fn])) - ;; Super basic Thread Pool, yes, this should be improved (deftype ThreadPool [] diff --git a/tests/pixie/tests/test-async.pxi b/tests/pixie/tests/test-async.pxi new file mode 100644 index 00000000..7d2055e2 --- /dev/null +++ b/tests/pixie/tests/test-async.pxi @@ -0,0 +1,15 @@ +(ns pixie.tests.test-async + (require pixie.stacklets :as st) + (require pixie.async :as async :refer :all) + (require pixie.test :as t :refer :all)) + + +(deftest test-future-deref + (let [f (future 42)] + (assert= @f 42))) + +(deftest test-future-deref-chain + (let [f1 (future 42) + f2 (future @f1) + f3 (future @f2)] + (assert= @f3 42))) From fe85dc1b42ed36d39027abd033056dada6c86700 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 17 Mar 2015 16:49:15 -0600 Subject: [PATCH 043/349] remove debug printlns --- pixie/async.pxi | 3 --- 1 file changed, 3 deletions(-) diff --git a/pixie/async.pxi b/pixie/async.pxi index 11ccb268..2907936a 100644 --- a/pixie/async.pxi +++ b/pixie/async.pxi @@ -5,7 +5,6 @@ (deftype Promise [val pending-callbacks delivered?] IDeref (-deref [self] - (println "waiting... " delivered?) (if delivered? val (do @@ -15,11 +14,9 @@ (st/-run-later (partial st/run-and-process k v))))))))) IFn (-invoke [self v] - (println "delivering....") (assert (not delivered?) "Can only deliver a promise once") (set-field! self :val v) (set-field! self :delivered? true) - (println @pending-callbacks) (doseq [f @pending-callbacks] (f v)) (reset! pending-callbacks nil) From bcd8e978d6b9ae37e345823cf11655875e2041ca Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Tue, 17 Mar 2015 21:59:50 +0000 Subject: [PATCH 044/349] Add more comments tests and fix case I missed I fixed the comment problem for lists, vectors, and maps, but missed sets, so I've fixed that now. --- pixie/vm/reader.py | 4 +++- tests/pixie/tests/test-readeval.pxi | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 9e587fee..97be5baa 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -623,7 +623,9 @@ def invoke(self, rdr, ch): return acc rdr.unread() - acc = acc.conj(read_inner(rdr, True)) + itm = read_inner(rdr, True, always_return_form=False) + if itm != rdr: + acc = acc.conj(itm) dispatch_handlers = { u"{": SetReader(), diff --git a/tests/pixie/tests/test-readeval.pxi b/tests/pixie/tests/test-readeval.pxi index 196ce3af..4344bff6 100644 --- a/tests/pixie/tests/test-readeval.pxi +++ b/tests/pixie/tests/test-readeval.pxi @@ -14,6 +14,7 @@ (t/assert= (read-string "\"fo\\\\o\"") "fo\\o") (t/assert= (read-string "false") false) (t/assert= (read-string "true") true) + (t/assert= (read-string "#{1 2 3}") #{1 2 3}) (t/assert= (read-string "(foo (bar (baz)))") '(foo (bar (baz))))) (t/deftest test-list-unclosed-list-fail @@ -57,4 +58,8 @@ (read-string "\"foo"))) (t/deftest test-comments-in-forms - (t/assert= (read-string "(foo ; a comment\n )") '(foo))) + (t/assert= (read-string "(foo ; a comment\n )") '(foo)) + (t/assert= (read-string "[foo ; a comment\n ]") '[foo]) + (t/assert= (read-string "{:foo :bar ; a comment\n }") '{:foo :bar}) + (t/assert= (read-string "#{:foo ; a comment\n }") '#{:foo}) + (t/assert= (read-string "{:foo ; a comment\n :bar }") '{:foo :bar})) From e600b341fe89026a29ff172443e785a22adc0591 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 15:27:52 -0600 Subject: [PATCH 045/349] fixed dynamic vars for stacklets --- pixie/stacklets.pxi | 24 ++++++++++++--------- pixie/vm/code.py | 37 ++++++++++++++++++++++++++------ pixie/vm/reader.py | 4 ++-- pixie/vm/rt.py | 9 +++++--- pixie/vm/stdlib.py | 14 ++++++++++++ tests/pixie/tests/test-async.pxi | 14 ++++++++++++ 6 files changed, 80 insertions(+), 22 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 5673afcf..ec03ae31 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -24,8 +24,10 @@ (f h)))) (defn call-cc [f] - (let [[h val] (@stacklet-loop-h f)] + (let [frames (-get-current-var-frames nil) + [h val] (@stacklet-loop-h f)] (reset! stacklet-loop-h h) + (-set-current-var-frames nil frames) val)) (defn -run-later [f] @@ -78,15 +80,17 @@ (-run-later (partial run-and-process k))))) (defmacro spawn [& body] - `(-spawn (fn [h# _] - (try - (swap! running-threads inc) - (reset! stacklet-loop-h h#) - (let [result# (do ~@body)] - (swap! running-threads dec) - (call-cc (fn [_] nil))) - (catch e - (println e)))))) + `(let [frames (-get-current-var-frames nil)] + (-spawn (fn [h# _] + (-set-current-var-frames nil frames) + (try + (swap! running-threads inc) + (reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (swap! running-threads dec) + (call-cc (fn [_] nil))) + (catch e + (println e))))))) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index c8c4f456..852b6f79 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -5,6 +5,7 @@ from rpython.rlib.rarithmetic import r_uint from rpython.rlib.listsort import TimSort from rpython.rlib.jit import elidable_promote, promote +from rpython.rlib.objectmodel import we_are_translated import rpython.rlib.jit as jit import pixie.vm.rt as rt @@ -377,21 +378,32 @@ def type(self): class DynamicVars(py_object): def __init__(self): - self._vars = [{}] + self._vars = rt.cons(rt.hashmap(), nil) def push_binding_frame(self): - self._vars.append(self._vars[-1].copy()) + self._vars = rt.cons(rt.first(self._vars), self._vars) def pop_binding_frame(self): - self._vars.pop() + self._vars = rt.next(self._vars) + + def current_frame(self): + return rt.first(self._vars) + + def get_current_frames(self): + return self._vars + + def set_current_frames(self, vars): + self._vars = vars def get_var_value(self, var, not_found): - return self._vars[-1].get(var, not_found) + return rt._val_at(self.current_frame(), var, not_found) def set_var_value(self, var, val): - self._vars[-1][var] = val + cur_frame = self.current_frame() + self.pop_binding_frame() + self._vars = rt.cons(rt._assoc(cur_frame, var, val), self._vars) + -_dynamic_vars = DynamicVars() class Var(BaseCode): @@ -443,7 +455,14 @@ def get_root(self, rev): def deref(self): if self.is_dynamic(): - return self.get_dynamic_value() + if we_are_translated(): + return self.get_dynamic_value() + else: + ## NOT RPYTHON + if globals().has_key("_dynamic_vars"): + return self.get_dynamic_value() + else: + return self.get_root(self._rev) else: val = self.get_root(self._rev) affirm(val is not undefined, u"Var " + self._name + u" is undefined") @@ -961,3 +980,7 @@ def __enter__(self): def __exit__(self, exc_type, exc_val, exc_tb): _dynamic_vars.pop_binding_frame() + + +def init(): + globals()["_dynamic_vars"] = DynamicVars() diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 9e587fee..b80bd77b 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -32,13 +32,13 @@ GEN_SYM_ENV = code.intern_var(u"pixie.stdlib.reader", u"*gen-sym-env*") GEN_SYM_ENV.set_dynamic() -GEN_SYM_ENV.set_value(EMPTY_MAP) +GEN_SYM_ENV.set_root(EMPTY_MAP) ARG_AMP = symbol(u"&") ARG_MAX = keyword(u"max-arg") ARG_ENV = code.intern_var(u"pixie.stdlib.reader", u"*arg-env*") ARG_ENV.set_dynamic() -ARG_ENV.set_value(nil) +ARG_ENV.set_root(nil) class PlatformReader(object.Object): _type = object.Type(u"PlatformReader") diff --git a/pixie/vm/rt.py b/pixie/vm/rt.py index bfc835a6..794a4c3b 100644 --- a/pixie/vm/rt.py +++ b/pixie/vm/rt.py @@ -49,6 +49,7 @@ def wrapper(*args): import sys #sys.setrecursionlimit(10000) # Yeah we blow the stack sometimes, we promise it's not a bug + import pixie.vm.code as code import pixie.vm.numbers as numbers import pixie.vm.bits import pixie.vm.interpreter @@ -71,8 +72,6 @@ def wrapper(*args): import pixie.vm.string_builder import pixie.vm.stacklet - numbers.init() - @specialize.argtype(0) def wrap(x): if isinstance(x, bool): @@ -145,7 +144,7 @@ def reinit(): # stacklet.with_stacklets(run_load_stdlib) init_fns = [u"reduce", u"get", u"reset!", u"assoc", u"key", u"val", u"keys", u"vals", u"vec", u"load-file", u"compile-file", - u"load-ns", u"hashmap"] + u"load-ns", u"hashmap", u"cons", u"-assoc", u"-val-at"] for x in init_fns: globals()[py_str(code.munge(x))] = unwrap(code.intern_var(u"pixie.stdlib", x)) @@ -159,6 +158,10 @@ def reinit(): globals()["is_true"] = lambda x: False if x is false or x is nil or x is None else True + numbers.init() + code.init() + + diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index a4c319ba..560578a2 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -813,3 +813,17 @@ def ex_msg(e): def _doc(self): assert isinstance(self, code.NativeFn) return rt.wrap(self._doc) + + +@as_var("-get-current-var-frames") +def _get_current_var_frames(self): + """(-get-current-var-frames) + Returns the current var frames, will be a cons list of hash maps containing mappings of vars to dynamic values""" + return code._dynamic_vars.get_current_frames() + +@as_var("-set-current-var-frames") +def _set_current_var_frames(self, frames): + """(-set-current-var-frames frames) + Sets the current var frames. Frames should be a cons list of hashmaps containing mappings of vars to dynamic + values. Setting this value to anything but this data format will cause undefined errors.""" + code._dynamic_vars.set_current_frames(frames) \ No newline at end of file diff --git a/tests/pixie/tests/test-async.pxi b/tests/pixie/tests/test-async.pxi index 7d2055e2..d5764af6 100644 --- a/tests/pixie/tests/test-async.pxi +++ b/tests/pixie/tests/test-async.pxi @@ -13,3 +13,17 @@ f2 (future @f1) f3 (future @f2)] (assert= @f3 42))) + +(def *some-var* 0) +(set-dynamic! (var *some-var*)) + +(deftest test-dynamic-var-propagation + (set! (var *some-var*) 0) + (assert= *some-var* 0) + (let [fr @(future (do (println "running") + (let [old-val *some-var*] + (set! (var *some-var*) 42) + [old-val *some-var*])))] + + (assert= fr [0 42]) + (assert= *some-var* 0))) From d40c9759bf69e6c9cb4b23bb17984165255dd265 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 16:07:46 -0600 Subject: [PATCH 046/349] added ring buffer and tests --- pixie/buffers.pxi | 79 ++++++++++++++++++++++++++++++ tests/pixie/tests/test-buffers.pxi | 25 ++++++++++ 2 files changed, 104 insertions(+) create mode 100644 pixie/buffers.pxi create mode 100644 tests/pixie/tests/test-buffers.pxi diff --git a/pixie/buffers.pxi b/pixie/buffers.pxi new file mode 100644 index 00000000..757bc8b0 --- /dev/null +++ b/pixie/buffers.pxi @@ -0,0 +1,79 @@ +(ns pixie.buffers) + +(defn acopy [src src-start dest dest-start len] + (loop [cnt 0] + (when (< cnt len) + (aset dest + (+ dest-start cnt) + (aget src (+ src-start cnt))) + (recur (inc cnt))))) + + +(defprotocol IMutableBuffer + (remove! [this]) + (add! [this]) + (full? [this])) + +(defprotocol IResizableMutableBuffer + (add-unbounded! [this val]) + (resize! [this new-size])) + +(deftype RingBuffer [head tail length arr] + IMutableBuffer + (remove! [this] + (when-not (zero? length) + (let [x (aget arr tail)] + (aset arr tail nil) + (set-field! this :tail (int (rem (inc tail) (alength arr)))) + (set-field! this :length (dec length)) + x))) + (add! [this x] + (assert (< length (alength arr))) + (aset arr head x) + (set-field! this :head (int (rem (inc head) (alength arr)))) + (set-field! this :length (inc length)) + nil) + + (full? [this] + (= length (alength arr))) + + + IResizableMutableBuffer + (resize! [this new-size] + (let [new-arr (make-array new-size)] + (cond + (< tail head) + (do (acopy arr tail new-arr 0 length) + (set-field! this :tail 0) + (set-field! this :head length) + (set-field! this :arr new-arr)) + + (> tail head) + (do (acopy arr tail new-arr 0 (- (alength arr) tail)) + (acopy arr 0 new-arr (- (alength arr) tail) head) + (set-field! this :tail 0) + (set-field! this :head length) + (set-field! this :arr new-arr)) + + + (full? this) + (do (acopy arr tail new-arr 0 length) + (set-field! this :tail 0) + (set-field! this :head length) + (set-field! this :arr new-arr)) + + + :else + (do (set-field! this :tail 0) + (set-field! this :head 0) + (set-field! this :arr new-arr))))) + + (add-unbounded! [this val] + (when (full? this) + (resize! this (* 2 length))) + (add! this val))) + + +(defn ring-buffer [size] + (assert (> size 0) "Can't create a ring buffer of size <= 0") + (->RingBuffer 0 0 0 (make-array size))) diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi new file mode 100644 index 00000000..382ffc8f --- /dev/null +++ b/tests/pixie/tests/test-buffers.pxi @@ -0,0 +1,25 @@ +(ns pixie.tests.test-buffers + (require pixie.test :refer :all) + (require pixie.buffers :refer :all)) + + +(deftest test-adding-and-removing-from-buffer + (let [buffer (ring-buffer 10)] + (dotimes [x 100] + (add! buffer x) + (assert= x (remove! buffer))))) + +(deftest test-adding-multiple-items + (let [buffer (ring-buffer 10)] + (dotimes [x 10] + (add! buffer x)) + (dotimes [x 10] + (assert= x (remove! buffer))))) + +(deftest test-adding-multiple-items-with-resize + (dotimes [y 100] + (let [buffer (ring-buffer 2)] + (dotimes [x y] + (add-unbounded! buffer x)) + (dotimes [x y] + (assert= x (remove! buffer)))))) From 641d49ae5d2ede0c04909c9a8fde47a87a06179a Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 16:40:07 -0600 Subject: [PATCH 047/349] implemented a few other buffer types --- pixie/buffers.pxi | 54 +++++++++++++++++++++++++++++- pixie/vm/stdlib.py | 2 +- tests/pixie/tests/test-buffers.pxi | 10 ++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/pixie/buffers.pxi b/pixie/buffers.pxi index 757bc8b0..76ee9fb7 100644 --- a/pixie/buffers.pxi +++ b/pixie/buffers.pxi @@ -71,9 +71,61 @@ (add-unbounded! [this val] (when (full? this) (resize! this (* 2 length))) - (add! this val))) + (add! this val)) + + ICounted + (-count [this] + length)) (defn ring-buffer [size] (assert (> size 0) "Can't create a ring buffer of size <= 0") (->RingBuffer 0 0 0 (make-array size))) + + +(defn fixed-buffer [size] + (ring-buffer size)) + + +(deftype DroppingBuffer [buf] + IMutableBuffer + (full? [this] + false) + (remove! [this] + (remove! buf)) + (add! [this val] + (when-not (full? buf) + (add! buf val))) + + ICounted + (-count [this] + (count buf))) + +(defn dropping-buffer [size] + (->DroppingBuffer (ring-buffer size))) + + +(deftype SlidingBuffer [buf] + IMutableBuffer + (full? [this] + false) + (remove! [this] + (remove! buf)) + (add! [this val] + (when (full? buf) + (remove! buf)) + (add! buf val)) + + ICounted + (-count [this] + (count buf))) + + +(extend -reduce IMutableBuffer + (fn [buf f acc] + (loop [acc acc] + (if (reduced? acc) + @acc + (if (> 0 (count buf)) + (recur (f acc (remove! buf))) + acc))))) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index a4c319ba..9f6923c4 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -668,7 +668,7 @@ def _try_catch(main_fn, catch_fn, final): if not we_are_translated(): print "Python Error Info: ", ex.__dict__, ex raise - ex = RuntimeException(rt.wrap(u"Some error")) + ex = RuntimeException(rt.wrap(u"Some error: " + unicode(str(ex)))) else: ex = RuntimeException(nil) return catch_fn.invoke([ex]) diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi index 382ffc8f..55f78ada 100644 --- a/tests/pixie/tests/test-buffers.pxi +++ b/tests/pixie/tests/test-buffers.pxi @@ -23,3 +23,13 @@ (add-unbounded! buffer x)) (dotimes [x y] (assert= x (remove! buffer)))))) + + +(def drain-buffer (partial into [])) + +(deftest test-dropping-buffer + (let [buf (dropping-buffer 4)] + (dotimes [x 5] + (println (count buf) "x" x) + (add! buf x)) + (assert= [1 2 3 4] (drain-buffer buf)))) From e2d5f4b0ab7bd4c78c68c4814548121e43be65cc Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 16:49:45 -0600 Subject: [PATCH 048/349] fixes #234 --- pixie/vm/custom_types.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 0434ba36..25a5e7e7 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -1,4 +1,4 @@ -from pixie.vm.object import Object, Type, affirm +from pixie.vm.object import Object, Type, affirm, runtime_error import rpython.rlib.jit as jit from rpython.rlib.rarithmetic import r_uint from pixie.vm.code import as_var @@ -16,7 +16,10 @@ def __init__(self, name, slots): @jit.elidable_promote() def get_slot_idx(self, nm): - return self._slots[nm] + val = self._slots.get(nm, -1) + if val == -1: + runtime_error(u"Invalid field named " + rt.name(rt.str(nm)) + u" on type " + rt.name(rt.str(self))) + return val def set_mutable(self, nm): if not self.is_mutable(nm): From 7f879128b5d276873049482f507f066446880e28 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 17:14:07 -0600 Subject: [PATCH 049/349] added deftype fix for shadowing protocol method names, fixed failing buffer tests --- pixie/buffers.pxi | 2 +- pixie/stdlib.pxi | 2 +- tests/pixie/tests/test-buffers.pxi | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pixie/buffers.pxi b/pixie/buffers.pxi index 76ee9fb7..4813d624 100644 --- a/pixie/buffers.pxi +++ b/pixie/buffers.pxi @@ -126,6 +126,6 @@ (loop [acc acc] (if (reduced? acc) @acc - (if (> 0 (count buf)) + (if (pos? (count buf)) (recur (f acc (remove! buf))) acc))))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 791f53d4..4165876e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1131,7 +1131,7 @@ Creates new maps if the keys are not present." ~@body)]) rest fields)] - `(fn ~fn-name ~args ~@body))) + `(fn ~(symbol (str fn-name "_" nm)) ~args ~@body))) bodies (reduce (fn [res body] (cond diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi index 55f78ada..ea4abf4c 100644 --- a/tests/pixie/tests/test-buffers.pxi +++ b/tests/pixie/tests/test-buffers.pxi @@ -32,4 +32,4 @@ (dotimes [x 5] (println (count buf) "x" x) (add! buf x)) - (assert= [1 2 3 4] (drain-buffer buf)))) + (assert= [0 1 2 3] (drain-buffer buf)))) From 9e05111d13aa084a568d33b50824350ca0235554 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 20:44:20 -0600 Subject: [PATCH 050/349] fix jit error with custom type errors --- pixie/vm/custom_types.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 25a5e7e7..1fd5c4ab 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -16,10 +16,7 @@ def __init__(self, name, slots): @jit.elidable_promote() def get_slot_idx(self, nm): - val = self._slots.get(nm, -1) - if val == -1: - runtime_error(u"Invalid field named " + rt.name(rt.str(nm)) + u" on type " + rt.name(rt.str(self))) - return val + return self._slots.get(nm, -1) def set_mutable(self, nm): if not self.is_mutable(nm): @@ -51,18 +48,27 @@ def type(self): def set_field(self, name, val): self._custom_type.set_mutable(name) idx = self._custom_type.get_slot_idx(name) + if idx == -1: + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + self._fields[idx] = val return self @jit.elidable_promote() def get_field_immutable(self, name): idx = self._custom_type.get_slot_idx(name) + if idx == -1: + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + return self._fields[idx] def get_field(self, name): if self._custom_type.is_mutable(name): idx = self._custom_type.get_slot_idx(name) + if idx == -1: + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + return self._fields[idx] else: return self.get_field_immutable(name) From 3ab8ee4b17132ec1b15aad7c2c6b19ac819d052b Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 18 Mar 2015 21:16:46 -0600 Subject: [PATCH 051/349] one more fix for the jit --- pixie/vm/custom_types.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 1fd5c4ab..0a91145d 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -55,23 +55,19 @@ def set_field(self, name, val): return self @jit.elidable_promote() - def get_field_immutable(self, name): - idx = self._custom_type.get_slot_idx(name) - if idx == -1: - runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) - + def get_field_immutable(self, idx): return self._fields[idx] def get_field(self, name): - if self._custom_type.is_mutable(name): - idx = self._custom_type.get_slot_idx(name) - if idx == -1: - runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + idx = self._custom_type.get_slot_idx(name) + if idx == -1: + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + if self._custom_type.is_mutable(name): return self._fields[idx] else: - return self.get_field_immutable(name) + return self.get_field_immutable(idx) def set_field_by_idx(self, idx, val): affirm(isinstance(idx, r_uint), u"idx must be a r_uint") From 5401318d3724d2c46c8b80409b1de04ac7ee1b68 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 19 Mar 2015 06:05:19 -0600 Subject: [PATCH 052/349] add tests and finish up sliding buffers --- pixie/buffers.pxi | 3 +++ tests/pixie/tests/test-buffers.pxi | 11 +++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/pixie/buffers.pxi b/pixie/buffers.pxi index 4813d624..cc3c4ce6 100644 --- a/pixie/buffers.pxi +++ b/pixie/buffers.pxi @@ -120,6 +120,9 @@ (-count [this] (count buf))) +(defn sliding-buffer [size] + (->SlidingBuffer (ring-buffer size))) + (extend -reduce IMutableBuffer (fn [buf f acc] diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi index ea4abf4c..92a99c94 100644 --- a/tests/pixie/tests/test-buffers.pxi +++ b/tests/pixie/tests/test-buffers.pxi @@ -30,6 +30,13 @@ (deftest test-dropping-buffer (let [buf (dropping-buffer 4)] (dotimes [x 5] - (println (count buf) "x" x) (add! buf x)) - (assert= [0 1 2 3] (drain-buffer buf)))) + (assert= [0 1 2 3] (drain-buffer buf)) + (assert (not (full? buf))))) + +(deftest test-sliding-buffer + (let [buf (sliding-buffer 4)] + (dotimes [x 5] + (add! buf x)) + (assert= [1 2 3 4] (drain-buffer buf)) + (assert (not (full? buf))))) From 09dc2bff560afb967ff9c4d069fe507276f5220d Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 19 Mar 2015 07:01:51 -0600 Subject: [PATCH 053/349] added the basics of channels --- pixie/buffers.pxi | 12 +++ pixie/channels.pxi | 121 ++++++++++++++++++++++++++++ pixie/stdlib.pxi | 4 + tests/pixie/tests/test-channels.pxi | 42 ++++++++++ 4 files changed, 179 insertions(+) create mode 100644 pixie/channels.pxi create mode 100644 tests/pixie/tests/test-channels.pxi diff --git a/pixie/buffers.pxi b/pixie/buffers.pxi index cc3c4ce6..5e6009db 100644 --- a/pixie/buffers.pxi +++ b/pixie/buffers.pxi @@ -123,6 +123,18 @@ (defn sliding-buffer [size] (->SlidingBuffer (ring-buffer size))) +(defn empty-buffer? [buf] + (= (count buf) 0)) + + +(deftype NullBuffer [] + IMutableBuffer + (full? [this] + true) + ICounted + (-count [this] 0)) + +(def null-buffer (->NullBuffer)) (extend -reduce IMutableBuffer (fn [buf f acc] diff --git a/pixie/channels.pxi b/pixie/channels.pxi new file mode 100644 index 00000000..65934678 --- /dev/null +++ b/pixie/channels.pxi @@ -0,0 +1,121 @@ +(ns pixie.channels + (require pixie.stacklets :as st) + (require pixie.buffers :as b)) + +(defprotocol ICancelable + (-canceled? [this] "Determines if a request (such as a callback) that can be canceled")) + +(defprotocol IReadPort + (-take! [this cfn] "Take a value from this port passing it to a cancellable function")) + +(defprotocol IWritePort + (-put! [this itm cfn] "Write a value to this port passing true if the write succeeds and the + callback isn't canceled")) + +(deftype OpCell [val cfn] + IIndexed + (-nth [this idx] + (cond + (= idx 0) val + (= idx 1) cfn + :else (throw "Index out of range"))) + (-nth-not-found [this idx not-found] + (cond + (= idx 0) val + (= idx 1) cfn + :else not-found)) + ICounted + (-count [this] + 2) + ICancelable + (-canceled? [this] + (canceled? cfn))) + +(defn canceled? [this] + (-canceled? this)) + + +(defn -move-puts-to-buffer [puts buffer] + (loop [] + (if (or (b/full? buffer) + (b/empty-buffer? puts)) + nil + (let [[val cfn] (b/remove! puts)] + (if (cancelled? cfn) + (recur) + (do (st/-run-later (partial cfn true)) + (b/add! buffer val) + (recur))))))) + +(defn -get-non-canceled! [buffer] + (loop [] + (if (b/empty-buffer? buffer) + nil + (let [v (b/remove! buffer)] + (if (canceled? v) + (recur) + v))))) + + +(deftype MultiReaderWriterChannel [puts takes buffer closed? ops-since-last-clean] + IReadPort + (-take! [this cfn] + (if (canceled? cfn) + false + (if closed? + (do (-run-later (partial cfn nil)) + false) + (if (not (b/empty-buffer? buffer)) + (do (st/-run-later (partial cfn (b/remove! buffer))) + (-move-puts-to-buffer puts buffer)) + + (if-let [[v pcfn] (-get-non-canceled! puts)] + (do (st/-run-later (partial pcfn true)) + (st/-run-later (partial cfn v)) + true) + (do (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) + (b/add-unbounded! takes cfn) + true)))))) + (-put! [this val cfn] + (if (or (canceled? cfn)) + false + (if closed? + (do (-run-later (partial cfn false)) + false) + (if-let [tfn (-get-non-canceled! takes)] + (do (st/-run-later (partial tfn val)) + (st/-run-later (partial cfn true)) + true) + (if (not (b/full? buffer)) + (do (b/add! buffer val) + (st/-run-later (partial cfn true)) + true) + (do (b/add-unbounded! puts (->OpCell val cfn)) + (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) + true))))))) + +(defn chan + ([] + (chan 0)) + ([size-or-buffer] + (if (= 0 size-or-buffer) + (->MultiReaderWriterChannel (b/ring-buffer 8) + (b/ring-buffer 8) + b/null-buffer + false + 0) + (if (integer? size-or-buffer) + (->MultiReaderWriterChannel (b/ring-buffer 8) + (b/ring-buffer 8) + (b/fixed-buffer size-or-buffer) + false + 0) + (->MultiReaderWriterChannel (b/ring-buffer 8) + (b/ring-buffer 8) + size-or-buffer + false + 0))))) + + +(extend -canceled? IFn + (fn [this] false)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4165876e..d306cc86 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2186,3 +2186,7 @@ Expands to calls to `extend-type`." (when (branch? node) (mapcat walk (children node))))))] (walk root))) + +(defn mapv + ([f col] + (transduce (map f) conj col))) diff --git a/tests/pixie/tests/test-channels.pxi b/tests/pixie/tests/test-channels.pxi new file mode 100644 index 00000000..f314af1c --- /dev/null +++ b/tests/pixie/tests/test-channels.pxi @@ -0,0 +1,42 @@ +(ns pixie.tests.test-channels + (require pixie.test :refer :all) + (require pixie.channels :refer :all) + (require pixie.async :refer :all)) + + +(deftest simple-read-and-write + (let [takep (promise) + putp (promise) + c (chan)] + (assert (-put! c 42 putp)) + (assert (-take! c takep)) + + (assert= @takep 42) + (assert= @putp true))) + +(deftest simple-take-before-put + (let [takep (promise) + putp (promise) + c (chan)] + (assert (-take! c takep)) + (assert (-put! c 42 putp)) + + (assert= @takep 42) + (assert= @putp true))) + +(deftest simple-take-before-put-with-buffers + (let [c (chan 2) + takesp (mapv (fn [_] (promise)) + (range 10)) + putsp (mapv (fn [_] (promise)) + (range 10))] + (doseq [p takesp] + (assert (-take! c p))) + (dotimes [x 10] + (assert (-put! c x (nth putsp x)))) + + (doseq [p putsp] + (assert= @p true)) + + (dotimes [x 10] + (assert= @(nth takesp x) x)))) From 5152bbf6a0fb21f77e5198e9515e503a84503dfa Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 19 Mar 2015 16:13:06 -0600 Subject: [PATCH 054/349] added go blocks cps operations and fixed closing of channels --- pixie/channels.pxi | 25 +++++++++++++++++---- pixie/csp.pxi | 35 +++++++++++++++++++++++++++++ tests/pixie/tests/test-channels.pxi | 30 +++++++++++++++++++++++++ tests/pixie/tests/test-csp.pxi | 15 +++++++++++++ 4 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 pixie/csp.pxi create mode 100644 tests/pixie/tests/test-csp.pxi diff --git a/pixie/channels.pxi b/pixie/channels.pxi index 65934678..22324955 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -12,6 +12,10 @@ (-put! [this itm cfn] "Write a value to this port passing true if the write succeeds and the callback isn't canceled")) +(defprotocol ICloseable + (-close! [this] "Closes the channel, future writes will be rejected, future reads will + drain the channel before returning nil.")) + (deftype OpCell [val cfn] IIndexed (-nth [this idx] @@ -62,8 +66,10 @@ (-take! [this cfn] (if (canceled? cfn) false - (if closed? - (do (-run-later (partial cfn nil)) + (if (and closed? + (b/empty-buffer? buffer) + (b/empty-buffer? puts)) + (do (st/-run-later (partial cfn nil)) false) (if (not (b/empty-buffer? buffer)) (do (st/-run-later (partial cfn (b/remove! buffer))) @@ -76,11 +82,12 @@ (do (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) (b/add-unbounded! takes cfn) true)))))) + IWritePort (-put! [this val cfn] (if (or (canceled? cfn)) false (if closed? - (do (-run-later (partial cfn false)) + (do (st/-run-later (partial cfn false)) false) (if-let [tfn (-get-non-canceled! takes)] (do (st/-run-later (partial tfn val)) @@ -92,9 +99,19 @@ true) (do (b/add-unbounded! puts (->OpCell val cfn)) (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) - true))))))) + true)))))) + ICloseable + (-close! [this] + (set-field! this :closed? true) + (when (not (b/empty-buffer? takes)) + (loop [] + (when-let [tfn (-get-non-canceled! takes)] + (st/-run-later (partial tfn nil)) + (recur)))))) (defn chan + "Creates a CSP channel with the given buffer. If an integer is provided as the argument + creates a channel with a fixed buffer of that size. " ([] (chan 0)) ([size-or-buffer] diff --git a/pixie/csp.pxi b/pixie/csp.pxi new file mode 100644 index 00000000..c1e12152 --- /dev/null +++ b/pixie/csp.pxi @@ -0,0 +1,35 @@ +(ns pixie.csp + (require pixie.stacklets :as st) + (require pixie.buffers :as b) + (require pixie.channels :as chans)) + +(def chan chans/chan) + +(def -null-callback (fn [_] nil)) + +(defn put! + "Puts the value into the channel, calling the optional callback when the operation has + completed." + ([c v] + (chans/-put! c v -null-callback)) + ([c v f] + (chans/-put! c v f))) + +(defn take! + "Takes a value from a channel, calling the provided callback when completed" + ([c f] + (chans/-take! c f))) + +(defn >! [c v] + (st/call-cc (fn [k] + (chans/-put! c v (partial st/run-and-process k))))) + +(defn ! c) (range 10)))] + (assert= (map Date: Thu, 19 Mar 2015 16:24:02 -0600 Subject: [PATCH 055/349] not sure if this is a good idea yet, but I extended reduce to IReadPorts. --- pixie/csp.pxi | 20 +++++++++++++++++++- tests/pixie/tests/test-csp.pxi | 13 +++++++------ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/pixie/csp.pxi b/pixie/csp.pxi index c1e12152..8dfb4db0 100644 --- a/pixie/csp.pxi +++ b/pixie/csp.pxi @@ -5,6 +5,12 @@ (def chan chans/chan) +(defn close! + "Closes the channel, future writes will be rejected, future reads will + drain the channel before returning nil." + [c] + (chans/-close! c)) + (def -null-callback (fn [_] nil)) (defn put! @@ -31,5 +37,17 @@ (defmacro go [& body] `(let [ret-chan# (chans/chan 1)] - (st/spawn (put! ret-chan# (do ~@body))) + (st/spawn (put! ret-chan# (do ~@body)) + (close! ret-chan#)) ret-chan#)) + + +(extend -reduce chans/IReadPort + (fn [c f init] + (loop [acc init] + (if (reduced? acc) + @acc + (let [v (! c) (range 10)))] - (assert= (map ! c) (range 10)) + (close! c))] + (assert= (vec c) (range 10)) + (assert= ( Date: Thu, 19 Mar 2015 16:06:18 -0700 Subject: [PATCH 056/349] Added pixie/*.pxic to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 391f400b..e7206d68 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ pixie-vm .idea lib include +pixie/*.pxic From 548a1b2e7eab8cb56589dad45189fe06be7a38c5 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 19 Mar 2015 22:07:26 -0600 Subject: [PATCH 057/349] added commit and cancel and basic alt handlers --- pixie/channels.pxi | 37 ++++++++++++++++++++++++----- tests/pixie/tests/test-channels.pxi | 17 ++++++++++++- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index 22324955..de275303 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -3,7 +3,8 @@ (require pixie.buffers :as b)) (defprotocol ICancelable - (-canceled? [this] "Determines if a request (such as a callback) that can be canceled")) + (-canceled? [this] "Determines if a request (such as a callback) that can be canceled") + (-commit! [this])) (defprotocol IReadPort (-take! [this cfn] "Take a value from this port passing it to a cancellable function")) @@ -69,14 +70,18 @@ (if (and closed? (b/empty-buffer? buffer) (b/empty-buffer? puts)) - (do (st/-run-later (partial cfn nil)) + (do (-commit! cfn) + (st/-run-later (partial cfn nil)) false) (if (not (b/empty-buffer? buffer)) - (do (st/-run-later (partial cfn (b/remove! buffer))) + (do (-commit! cfn) + (st/-run-later (partial cfn (b/remove! buffer))) (-move-puts-to-buffer puts buffer)) (if-let [[v pcfn] (-get-non-canceled! puts)] - (do (st/-run-later (partial pcfn true)) + (do (-commit! pcfn) + (-commit! cfn) + (st/-run-later (partial pcfn true)) (st/-run-later (partial cfn v)) true) (do (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) @@ -87,14 +92,18 @@ (if (or (canceled? cfn)) false (if closed? - (do (st/-run-later (partial cfn false)) + (do (-commit! cfn) + (st/-run-later (partial cfn false)) false) (if-let [tfn (-get-non-canceled! takes)] - (do (st/-run-later (partial tfn val)) + (do (-commit! cfn) + (-commit! tfn) + (st/-run-later (partial tfn val)) (st/-run-later (partial cfn true)) true) (if (not (b/full? buffer)) (do (b/add! buffer val) + (-commit! cfn) (st/-run-later (partial cfn true)) true) (do (b/add-unbounded! puts (->OpCell val cfn)) @@ -106,6 +115,7 @@ (when (not (b/empty-buffer? takes)) (loop [] (when-let [tfn (-get-non-canceled! takes)] + (-commit! tfn) (st/-run-later (partial tfn nil)) (recur)))))) @@ -133,6 +143,21 @@ false 0))))) +(deftype AltHandler [atm f] + ICancelable + (-canceled? [this] + @atm) + (-commit! [this] + (reset! atm true)) + IFn + (-invoke [this & args] + (apply f args))) + +(defn alt-handlers [fns] + (mapv (partial ->AltHandler (atom false)) fns)) (extend -canceled? IFn (fn [this] false)) + +(extend -commit! IFn + (fn [this] nil)) diff --git a/tests/pixie/tests/test-channels.pxi b/tests/pixie/tests/test-channels.pxi index 8607a64b..9f35fe61 100644 --- a/tests/pixie/tests/test-channels.pxi +++ b/tests/pixie/tests/test-channels.pxi @@ -1,7 +1,8 @@ (ns pixie.tests.test-channels (require pixie.test :refer :all) (require pixie.channels :refer :all) - (require pixie.async :refer :all)) + (require pixie.async :refer :all) + (require pixie.stacklets :as st)) (deftest simple-read-and-write @@ -70,3 +71,17 @@ (-close! c) (assert= (mapv (partial -take! c) tps) [true true false]) (assert= (mapv deref tps) [0 1 nil]))) + +(deftest alt-handlers-only-invoke-one-callback + (let [completed (atom 0) + c (chan 5) + [f1 f2] (alt-handlers + [(fn [_] (swap! completed inc)) + (fn [_] (swap! completed inc))])] + (-take! c f1) + (-take! c f2) + (-put! c 1 (fn [_])) + (-put! c 2 (fn [_])) + (st/yield-control) + + (assert= @completed 1))) From 0a371b88c975d77b964e2acce8f3cde7adebde19 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 20 Mar 2015 15:26:23 -0600 Subject: [PATCH 058/349] adds ffi-voidp --- pixie/vm/libs/ffi.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index ead55775..1a30a535 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -196,6 +196,13 @@ def _ffi_fn__args(args): f = FFIFn(lib, rt.name(nm), new_args, ret_type, is_variadic) return f +@as_var("ffi-voidp") +def _ffi_voidp(lib, nm): + affirm(isinstance(lib, ExternalLib), u"First argument to ffi-voidp should be an external library") + name = rt.name(nm) + return VoidP(lib.get_fn_ptr(name)) + + From 398fc4a87603b0e71cf28755da8d382b84dca9d4 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 20 Mar 2015 15:46:13 -0600 Subject: [PATCH 059/349] add defglobal to ffi-infer --- pixie/ffi-infer.pxi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 822f55ae..b2db256b 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -62,6 +62,10 @@ [{:keys [name]}] (str "PixieChecker::DumpType<__typeof__(" name ")>();")) +(defmethod emit-infer-code :global + [_] + (str "std::cout <<\"[]\" << std::endl;")) + (defn start-string [] (str (apply str (map (fn [i] @@ -80,6 +84,7 @@ return 0; }") + ;; To Ctype conversion (defmulti edn-to-ctype (fn [n _] @@ -131,6 +136,10 @@ return 0; [{:keys [name]} {:keys [value type]}] `(def ~(symbol name) ~value)) +(defmethod generate-code :global + [{:keys [name]} _] + `(def ~(symbol name) (ffi-voidp *library* ~(str name)))) + (defmethod generate-code :function @@ -228,6 +237,10 @@ return 0; `(swap! *bodies* conj (assoc {:op :callback} :name ~(name nm)))) +(defmacro defglobal [nm] + `(swap! *bodies* conj (assoc {:op :global} + :name ~(name nm)))) + (defn compile-library [{:keys [prefix includes]} & source] (let [c-name (str "/tmp/" prefix ".c") From cc69dd0777b929147ccd01309d1c9227e54401c1 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sat, 21 Mar 2015 16:05:28 -0600 Subject: [PATCH 060/349] implemented alts! I think it's time to merge --- pixie/channels.pxi | 20 ++++++++++++++++++++ pixie/csp.pxi | 9 +++++++++ tests/pixie/tests/test-csp.pxi | 18 ++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index de275303..f6a89418 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -161,3 +161,23 @@ (extend -commit! IFn (fn [this] nil)) + +(defn alts! [ops k options] + (let [handler-atom (atom false)] + (reduce + (fn [_ op] + (if (vector? op) + (let [[c val] op + f (fn [v] + (st/-run-later (partial k [c v])))] + (-put! c val (->AltHandler handler-atom f))) + (let [c op + f (fn [v] + (st/-run-later (partial k [c v])))] + (-take! c (->AltHandler handler-atom f))))) + nil + ops) + (when (and (:default options) + (not @handler-atom)) + (reset! handler-atom true) + (st/-run-later (partial k [:default (:default options)]))))) diff --git a/pixie/csp.pxi b/pixie/csp.pxi index 8dfb4db0..5cd9ff71 100644 --- a/pixie/csp.pxi +++ b/pixie/csp.pxi @@ -51,3 +51,12 @@ (if (nil? v) acc (recur (f acc v)))))))) + + +(defn alts! + ([ops] + (st/call-cc (fn [k] + (chans/alts! ops (partial st/run-and-process k) {})))) + ([ops & opts] + (st/call-cc (fn [k] + (chans/alts! ops (partial st/run-and-process k) (apply hashmap opts)))))) diff --git a/tests/pixie/tests/test-csp.pxi b/tests/pixie/tests/test-csp.pxi index 1fc49306..ae65a572 100644 --- a/tests/pixie/tests/test-csp.pxi +++ b/tests/pixie/tests/test-csp.pxi @@ -14,3 +14,21 @@ (close! c))] (assert= (vec c) (range 10)) (assert= (! c1 1) + (>! c2 2) + (println (hash-set [c1 1] [c2 2])) + (assert (not (= c1 c2))) + (assert= (! c 1) + (assert= (alts! [c] :default 42) [c 1]))) From 8652879c40b75565655fdcdca1c152c32390e1d2 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sat, 21 Mar 2015 20:24:17 +0000 Subject: [PATCH 061/349] Implement map without using iterators, fixes #242 The fact that map was implemented with iterators caused the following to happen: ``` user => (def sqr #(* % %)) user => (def sqrs (map sqr [1 2 3])) user => sqrs user => (vec sqrs) [1 4 9] user => (vec sqrs) [] ``` This commit implements map differently and adds tests to ensure that it behaves as intended. The implementation is pretty similar to the CLJS one, there are just a few things that aren't available (since `map` is defined earlier in the pixie stdlib than the CLJS core). --- pixie/stdlib.pxi | 40 ++++++++++++------------------- tests/pixie/tests/test-stdlib.pxi | 8 +++++++ 2 files changed, 23 insertions(+), 25 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 791f53d4..4e426ad4 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -144,32 +144,22 @@ ([result] (xf result)) ([result item] (xf result (f item)))))) ([f coll] - (let [i (iterator coll)] - (loop [] - (if (at-end? i) - nil - (do (yield (f (current i))) - (move-next! i) - (recur)))))) + (lazy-seq* + (fn [] + (let [s (seq coll)] + (if s + (cons (f (first s)) + (map f (rest s))) + nil))))) ([f & colls] - (let [its (vec (map iterator colls))] - (loop [] - (let [args (if (at-end? (first its)) - nil - (reduce - (fn [acc i] - (if (at-end? i) - (reduced nil) - (let [new-acc (conj acc (current i))] - (move-next! i) - new-acc))) - [] - its))] - - (if args - (do (yield (apply f args)) - (recur))))))))) - + (let [step (fn step [cs] + (lazy-seq* + (fn [] + (let [ss (map seq cs)] + (if (every? identity ss) + (cons (map first ss) (step (map rest ss))) + nil)))))] + (map (fn [args] (apply f args)) (step colls)))))) (def reduce (fn [rf init col] (-reduce col rf init))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index c0c0b711..0f01e5fa 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -6,6 +6,14 @@ (doseq [v vs] (t/assert= (identity v) v)))) +(t/deftest test-map + (t/assert= (map inc [1 2 3]) [2 3 4]) + (t/assert= (map + [1 2 3] [4 5 6]) [5 7 9]) + (t/assert= (map + [1 2 3] [4 5 6] [7 8 9]) [12 15 18]) + (let [value (map identity [1 2 3])] + (t/assert= (seq value) [1 2 3]) + (t/assert= (seq value) [1 2 3]))) + (t/deftest test-mapcat (t/assert= (mapcat identity []) []) (t/assert= (mapcat first [[[1 2]] [[3] [:not :present]] [[4 5 6]]]) [1 2 3 4 5 6])) From 6ae8a30ece855255994e7de4fb077ecb0636158f Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sun, 22 Mar 2015 00:24:20 +0100 Subject: [PATCH 062/349] Make *1, *2 and *3 work. --- pixie/repl.pxi | 4 +++- pixie/stdlib.pxi | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pixie/repl.pxi b/pixie/repl.pxi index c9c8e9a4..38b94fde 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -21,7 +21,9 @@ (try (let [form (read rdr false)] (if (= form eof) (exit 0) - (println (eval form)))) + (let [x (eval form)] + (pixie.stdlib/-push-history x) + (println x)))) (catch ex (println "ERROR: \n" ex))) (recur)))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 791f53d4..c47f061f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2186,3 +2186,8 @@ Expands to calls to `extend-type`." (when (branch? node) (mapcat walk (children node))))))] (walk root))) + +(defn -push-history [x] + (def *3 *2) + (def *2 *1) + (def *1 x)) From 533921af91b2b86fabe800bca1dee1683db030ab Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sun, 22 Mar 2015 00:26:11 +0100 Subject: [PATCH 063/349] Make *e work. --- pixie/repl.pxi | 3 ++- pixie/stdlib.pxi | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/pixie/repl.pxi b/pixie/repl.pxi index 38b94fde..06298e7a 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -25,5 +25,6 @@ (pixie.stdlib/-push-history x) (println x)))) (catch ex - (println "ERROR: \n" ex))) + (pixie.stdlib/-set-*e ex) + (println "ERROR: \n" ex))) (recur)))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index c47f061f..427aebd0 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2191,3 +2191,6 @@ Expands to calls to `extend-type`." (def *3 *2) (def *2 *1) (def *1 x)) + +(defn -set-*e [e] + (def *e e)) From dc3f22a996121396ff8a1224fa3a1c83e07f1519 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sat, 21 Mar 2015 21:45:45 -0600 Subject: [PATCH 064/349] a bit of cleanup --- pixie/channels.pxi | 2 +- pixie/csp.pxi | 2 +- pixie/stdlib.pxi | 1 + tests/pixie/tests/test-csp.pxi | 1 - 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index f6a89418..1b48ecf8 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -177,7 +177,7 @@ (-take! c (->AltHandler handler-atom f))))) nil ops) - (when (and (:default options) + (when (and (contains? options :default) (not @handler-atom)) (reset! handler-atom true) (st/-run-later (partial k [:default (:default options)]))))) diff --git a/pixie/csp.pxi b/pixie/csp.pxi index 5cd9ff71..b20fa08c 100644 --- a/pixie/csp.pxi +++ b/pixie/csp.pxi @@ -56,7 +56,7 @@ (defn alts! ([ops] (st/call-cc (fn [k] - (chans/alts! ops (partial st/run-and-process k) {})))) + (chans/alts! ops (partial st/run-and-process k) nil)))) ([ops & opts] (st/call-cc (fn [k] (chans/alts! ops (partial st/run-and-process k) (apply hashmap opts)))))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index d306cc86..8bfa4690 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -292,6 +292,7 @@ (extend -with-meta Nil (fn [self _] nil)) (extend -at-end? Nil (fn [_] true)) (extend -deref Nil (fn [_] nil)) +(extend -contains-key Nil (fn [_ _] false)) (extend -hash Integer hash-int) diff --git a/tests/pixie/tests/test-csp.pxi b/tests/pixie/tests/test-csp.pxi index ae65a572..0b4cc396 100644 --- a/tests/pixie/tests/test-csp.pxi +++ b/tests/pixie/tests/test-csp.pxi @@ -23,7 +23,6 @@ (alts! [c1 c2])))] (>! c1 1) (>! c2 2) - (println (hash-set [c1 1] [c2 2])) (assert (not (= c1 c2))) (assert= ( Date: Sat, 21 Mar 2015 23:32:10 -0600 Subject: [PATCH 065/349] optimizations for lazy seqs, partial, and immutable_fields --- pixie/stdlib.pxi | 25 +++++++++++-------------- pixie/vm/array.py | 4 ++-- pixie/vm/code.py | 13 +++++++------ pixie/vm/custom_types.py | 4 ++-- pixie/vm/keyword.py | 2 +- pixie/vm/lazy_seq.py | 31 +++++++++++++++++++------------ pixie/vm/stdlib.py | 39 ++++++++++++++++++++++++++++++++++++++- pixie/vm/symbol.py | 2 +- 8 files changed, 81 insertions(+), 39 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 791f53d4..ad5426e9 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -241,16 +241,17 @@ (seq (next coll))) init))))) -(def indexed-reduce (fn indexed-reduce - [coll f init] - (let [max (count coll)] - (loop [init init - i 0] - (if (reduced? init) - @init - (if (-eq i max) - init - (recur (f init (nth coll i nil)) (+ i 1)))))))) +(def indexed-reduce + (fn indexed-reduce + [coll f init] + (let [max (count coll)] + (loop [init init + i 0] + (if (reduced? init) + @init + (if (-eq i max) + init + (recur (f init (nth coll i nil)) (+ i 1)))))))) (def rest (fn ^{:doc "Returns the elements after the first element, or () if there are no more elements." :signatures [[coll]] @@ -2156,10 +2157,6 @@ Expands to calls to `extend-type`." names) result#))) -(defn partial [f & args] - (fn [& args2] - (apply f (-> args vec (into args2))))) - (defn pst {:doc "Prints the trace of a Runtime Exception if given, or the last Runtime Exception in *e" :signatures [[] [e]] diff --git a/pixie/vm/array.py b/pixie/vm/array.py index 265001f7..597ea5e7 100644 --- a/pixie/vm/array.py +++ b/pixie/vm/array.py @@ -13,7 +13,7 @@ class Array(object.Object): _type = object.Type(u"pixie.stdlib.Array") - __immutable_fields__ = ["_list[*]"] + _immutable_fields_ = ["_list[*]"] def type(self): return Array._type @@ -76,7 +76,7 @@ def _seq(self): class ArraySeq(object.Object): _type = object.Type(u"pixie.stdlib.ArraySeq") - __immutable_fields__ = ["_idx", "_w_array"] + _immutable_fields_ = ["_idx", "_w_array"] def __init__(self, idx, array): self._idx = idx diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 852b6f79..548cb48a 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -91,6 +91,7 @@ def slice_from_start(from_list, count, extra=r_uint(0)): class BaseCode(object.Object): + _immutable_fields_ = ["_meta"] def __init__(self): assert isinstance(self, BaseCode) self._name = u"unknown" @@ -213,7 +214,7 @@ def invoke_with(self, args, this_fn): class Code(BaseCode): """Interpreted code block. Contains consts and """ _type = object.Type(u"pixie.stdlib.Code") - __immutable_fields__ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta"] + _immutable_fields_ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta"] def type(self): return Code._type @@ -271,7 +272,7 @@ def get_base_code(self): class VariadicCode(BaseCode): - __immutable_fields__ = ["_required_arity", "_code", "_meta"] + _immutable_fields_ = ["_required_arity", "_code", "_meta"] _type = object.Type(u"pixie.stdlib.VariadicCode") def type(self): @@ -314,7 +315,7 @@ def invoke_with(self, args, self_fn): class Closure(BaseCode): _type = object.Type(u"pixie.stdlib.Closure") - __immutable_fields__ = ["_closed_overs[*]", "_code", "_meta"] + _immutable_fields_ = ["_closed_overs[*]", "_code", "_meta"] def type(self): return Closure._type @@ -632,7 +633,7 @@ def invoke(self, args): class Protocol(object.Object): _type = object.Type(u"pixie.stdlib.Protocol") - __immutable_fields__ = ["_rev?"] + _immutable_fields_ = ["_rev?"] def type(self): return Protocol._type @@ -664,7 +665,7 @@ class PolymorphicFn(BaseCode): def type(self): return PolymorphicFn._type - __immutable_fields__ = ["_rev?"] + _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): BaseCode.__init__(self) @@ -738,7 +739,7 @@ class DoublePolymorphicFn(BaseCode): def type(self): return DefaultProtocolFn._type - __immutable_fields__ = ["_rev?"] + _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): BaseCode.__init__(self) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 0a91145d..0bf431ae 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -6,7 +6,7 @@ import pixie.vm.rt as rt class CustomType(Type): - __immutable_fields__ = ["_slots", "_rev?"] + _immutable_fields_ = ["_slots", "_rev?"] def __init__(self, name, slots): Type.__init__(self, name) @@ -36,7 +36,7 @@ def get_num_slots(self): return len(self._slots) class CustomTypeInstance(Object): - __immutable_fields__ = ["_type"] + _immutable_fields_ = ["_type"] def __init__(self, type, fields): affirm(isinstance(type, CustomType), u"Can't create a instance of a non custom type") self._custom_type = type diff --git a/pixie/vm/keyword.py b/pixie/vm/keyword.py index e1c14568..58538418 100644 --- a/pixie/vm/keyword.py +++ b/pixie/vm/keyword.py @@ -10,7 +10,7 @@ class Keyword(Object): _type = Type(u"pixie.stdlib.Keyword") - __immutable_fields__ = ["_hash"] + _immutable_fields_ = ["_hash"] def __init__(self, name): self._str = name self._w_name = None diff --git a/pixie/vm/lazy_seq.py b/pixie/vm/lazy_seq.py index 7d052585..b95c3c94 100644 --- a/pixie/vm/lazy_seq.py +++ b/pixie/vm/lazy_seq.py @@ -3,6 +3,7 @@ import pixie.vm.stdlib as proto from pixie.vm.code import extend, as_var import pixie.vm.rt as rt +import rpython.rlib.jit as jit class LazySeq(object.Object): @@ -16,6 +17,7 @@ def __init__(self, fn, meta=nil): self._meta = meta self._s = nil + @jit.jit_callback("lazy_seq_sval") def sval(self): if self._fn is None: return self._s @@ -24,6 +26,21 @@ def sval(self): self._fn = None return self._s + @jit.dont_look_inside + def lazy_seq_seq(self): + self.sval() + if self._s is not nil: + ls = self._s + while True: + if isinstance(ls, LazySeq): + ls = ls.sval() + continue + else: + self._s = ls + return rt.seq(self._s) + else: + return nil + @extend(proto._first, LazySeq) @@ -41,18 +58,8 @@ def _next(self): @extend(proto._seq, LazySeq) def _seq(self): assert isinstance(self, LazySeq) - self.sval() - if self._s is not nil: - ls = self._s - while True: - if isinstance(ls, LazySeq): - ls = ls.sval() - continue - else: - self._s = ls - return rt.seq(self._s) - else: - return nil + return self.lazy_seq_seq() + @as_var("lazy-seq*") def lazy_seq(f): diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 560578a2..4bc34c62 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -815,6 +815,42 @@ def _doc(self): return rt.wrap(self._doc) +class PartialFunction(code.NativeFn): + _immutable_fields_ = ["_partial_f", "_partial_args"] + def __init__(self, f, args): + self._partial_f = f + self._partial_args = args + + @jit.unroll_safe + def invoke(self, args): + new_args = [None] * (len(args) + len(self._partial_args)) + + for x in range(len(self._partial_args)): + new_args[x] = self._partial_args[x] + + plen = len(self._partial_args) + + for x in range(len(args)): + new_args[plen + x] = args[x] + + + return self._partial_f.invoke(new_args) + +@as_var("partial") +@jit.unroll_safe +def _partial__args(args): + """(partial f & args) + Creates a function that is a partial application of f. Thus ((partial + 1) 2) == 3""" + + f = args[0] + + new_args = [None] * (len(args) - 1) + + for x in range(len(new_args)): + new_args[x] = args[x + 1] + + return PartialFunction(f, new_args) + @as_var("-get-current-var-frames") def _get_current_var_frames(self): """(-get-current-var-frames) @@ -826,4 +862,5 @@ def _set_current_var_frames(self, frames): """(-set-current-var-frames frames) Sets the current var frames. Frames should be a cons list of hashmaps containing mappings of vars to dynamic values. Setting this value to anything but this data format will cause undefined errors.""" - code._dynamic_vars.set_current_frames(frames) \ No newline at end of file + code._dynamic_vars.set_current_frames(frames) + diff --git a/pixie/vm/symbol.py b/pixie/vm/symbol.py index 1fb9bbc3..6b0f2bfc 100644 --- a/pixie/vm/symbol.py +++ b/pixie/vm/symbol.py @@ -10,7 +10,7 @@ class Symbol(object.Object): _type = object.Type(u"pixie.stdlib.Symbol") - __immutable_fields__ = ["_hash"] + _immutable_fields_ = ["_hash"] def __init__(self, s, meta=nil): #assert isinstance(s, unicode) From 0a37ab3fe2e0396447e06f76dc264a05aa76ed6c Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Sun, 22 Mar 2015 10:36:19 +0100 Subject: [PATCH 066/349] print stuff in the repl using `prn`, not `println` you'll want this for strings, for example. --- pixie/repl.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/repl.pxi b/pixie/repl.pxi index 06298e7a..d10b6a44 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -23,7 +23,7 @@ (exit 0) (let [x (eval form)] (pixie.stdlib/-push-history x) - (println x)))) + (prn x)))) (catch ex (pixie.stdlib/-set-*e ex) (println "ERROR: \n" ex))) From 9b8425aeb1e25462625dd99eb38e5de311981d66 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sun, 22 Mar 2015 11:29:01 +0000 Subject: [PATCH 067/349] Improve assert-throws? macro Since `assert-throws?` throws an exception inside the try regardless of if the body throws, if the body *doesn't* throw, you get a sort of strange error message: ``` RuntimeException: Assert failed Expected message: exception! but got Assert failed Expected a exception: exception! ``` I fixed this, improved the messages a bit, and also added some extra arities for just checking that an expression throws, and also just checking the class of the exception, instead of always the class and the message. --- pixie/test.pxi | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/pixie/test.pxi b/pixie/test.pxi index cf77ccf2..26c3927b 100644 --- a/pixie/test.pxi +++ b/pixie/test.pxi @@ -61,15 +61,25 @@ yr# ~y] (assert (= xr# yr#) (str (show '~x xr#) " != " (show '~y yr#))))) -(defmacro assert-throws? [klass msg body] - `(try - ~body - (assert false (str "Expected a " ~klass " exception: " ~msg)) - (catch e# - (assert (= (type e#) ~klass) - (str "Expected exception of class " ~klass " but got " (type e#))) - (assert (= (ex-msg e#) ~msg) - (str "Expected message: " ~msg " but got " (ex-msg e#)))))) +(defmacro assert-throws? + ([body] + `(let [exn# (try (do ~body nil) (catch e# e#))] + (assert (not (nil? exn#)) + (str "Expected " (pr-str (quote ~body)) " to throw an exception")) + exn#)) + ([klass body] + `(let [exn# (assert-throws? ~body)] + (assert (= (type exn#) ~klass) + (str "Expected " (pr-str (quote ~body)) + " to throw exception of class " (pr-str ~klass) + " but got " (pr-str (type exn#)))) + exn#)) + ([klass msg body] + `(let [exn# (assert-throws? ~klass ~body)] + (assert (= (ex-msg exn#) ~msg) + (str "Expected " (pr-str (quote ~body)) + " to throw exception with message " (pr-str ~msg) + " but got " (pr-str (ex-msg exn#))))))) (defmacro assert [x] `(let [x# ~x] From 71d65fab4e63576b71d4cd4bf21576f3d980d2c0 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 22 Mar 2015 13:19:44 +0000 Subject: [PATCH 068/349] added set predicate also deleted unused import --- pixie/stdlib.pxi | 1 + pixie/vm/stdlib.py | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 791f53d4..9699d8c0 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -811,6 +811,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn keyword? [v] (instance? Keyword v)) (defn list? [v] (instance? PersistentList v)) +(defn set? [v] (instance? PersistentHashSet v)) (defn map? [v] (satisfies? IMap v)) (defn fn? [v] (satisfies? IFn v)) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 560578a2..f7e4fd98 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -420,7 +420,6 @@ def _load_file(filename, compile=False): import pixie.vm.reader as reader import pixie.vm.libs.pxic.writer as pxic_writer import os.path as path - from pixie.vm.persistent_vector import EMPTY as EMPTY_VECTOR import os @@ -826,4 +825,4 @@ def _set_current_var_frames(self, frames): """(-set-current-var-frames frames) Sets the current var frames. Frames should be a cons list of hashmaps containing mappings of vars to dynamic values. Setting this value to anything but this data format will cause undefined errors.""" - code._dynamic_vars.set_current_frames(frames) \ No newline at end of file + code._dynamic_vars.set_current_frames(frames) From 0a76f8ef71b078bed08c9e0c248c6c63e90807b2 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 23 Mar 2015 16:52:04 -0600 Subject: [PATCH 069/349] fix segfault --- pixie/vm/stdlib.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index f2735f75..79bff639 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -817,6 +817,7 @@ def _doc(self): class PartialFunction(code.NativeFn): _immutable_fields_ = ["_partial_f", "_partial_args"] def __init__(self, f, args): + code.NativeFn.__init__(self) self._partial_f = f self._partial_args = args @@ -835,6 +836,7 @@ def invoke(self, args): return self._partial_f.invoke(new_args) + @as_var("partial") @jit.unroll_safe def _partial__args(args): From cfb7379dfe7df20ab7fe8f83e3743391b909411d Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 23 Mar 2015 21:22:56 -0600 Subject: [PATCH 070/349] fixed bad immutable flags --- pixie/vm/array.py | 2 +- pixie/vm/keyword.py | 1 - pixie/vm/symbol.py | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/pixie/vm/array.py b/pixie/vm/array.py index 597ea5e7..3bde8642 100644 --- a/pixie/vm/array.py +++ b/pixie/vm/array.py @@ -13,7 +13,7 @@ class Array(object.Object): _type = object.Type(u"pixie.stdlib.Array") - _immutable_fields_ = ["_list[*]"] + _immutable_fields_ = ["_list"] def type(self): return Array._type diff --git a/pixie/vm/keyword.py b/pixie/vm/keyword.py index 58538418..f6ce6dbc 100644 --- a/pixie/vm/keyword.py +++ b/pixie/vm/keyword.py @@ -10,7 +10,6 @@ class Keyword(Object): _type = Type(u"pixie.stdlib.Keyword") - _immutable_fields_ = ["_hash"] def __init__(self, name): self._str = name self._w_name = None diff --git a/pixie/vm/symbol.py b/pixie/vm/symbol.py index 6b0f2bfc..390805d0 100644 --- a/pixie/vm/symbol.py +++ b/pixie/vm/symbol.py @@ -10,8 +10,6 @@ class Symbol(object.Object): _type = object.Type(u"pixie.stdlib.Symbol") - _immutable_fields_ = ["_hash"] - def __init__(self, s, meta=nil): #assert isinstance(s, unicode) self._str = s From d2435370361ce5804bba2fa39ef185e5d9a85c21 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 23 Mar 2015 22:28:15 -0600 Subject: [PATCH 071/349] add specialization for ints --- pixie/vm/custom_types.py | 48 +++++++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 0bf431ae..2e9776d7 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -2,6 +2,7 @@ import rpython.rlib.jit as jit from rpython.rlib.rarithmetic import r_uint from pixie.vm.code import as_var +from pixie.vm.numbers import Integer from pixie.vm.keyword import Keyword import pixie.vm.rt as rt @@ -46,12 +47,15 @@ def type(self): return self._custom_type def set_field(self, name, val): - self._custom_type.set_mutable(name) idx = self._custom_type.get_slot_idx(name) if idx == -1: runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) - self._fields[idx] = val + old_val = self._fields[idx] + if isinstance(old_val, AbstractMutableCell): + old_val.set_mutable_cell_value(self._custom_type, self._fields, name, idx, val) + else: + self._fields[idx] = val return self @jit.elidable_promote() @@ -65,9 +69,14 @@ def get_field(self, name): runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) if self._custom_type.is_mutable(name): - return self._fields[idx] + value = self._fields[idx] + else: + value = self.get_field_immutable(idx) + + if isinstance(value, AbstractMutableCell): + return value.get_mutable_cell_value() else: - return self.get_field_immutable(idx) + return value def set_field_by_idx(self, idx, val): affirm(isinstance(idx, r_uint), u"idx must be a r_uint") @@ -98,7 +107,10 @@ def _new__args(args): affirm(cnt - 1 != tp.get_num_slots(), u"Wrong number of initializer fields to custom type") arr = [None] * cnt for x in range(cnt): - arr[x] = args[x + 1] + val = args[x + 1] + if isinstance(val, Integer): + val = IntegerMutableCell(val.int_val()) + arr[x] = val return CustomTypeInstance(tp, arr) @as_var("set-field!") @@ -114,3 +126,29 @@ def get_field(inst, field): affirm(isinstance(field, Keyword), u"Field must be a keyword") return inst.get_field(field) + + +class AbstractMutableCell(Object): + _type = Type(u"pixie.stdlib.AbstractMutableCell") + def type(self): + return self._type + + def set_mutable_cell_value(self, ct, fields, nm, idx, value): + pass + + def get_mutable_cell_value(self): + pass + +class IntegerMutableCell(AbstractMutableCell): + def __init__(self, int_val): + self._mutable_integer_val = int_val + + def set_mutable_cell_value(self, ct, fields, nm, idx, value): + if not isinstance(value, Integer): + ct.set_mutable(nm) + fields[idx] = value + else: + self._mutable_integer_val = value.int_val() + + def get_mutable_cell_value(self): + return rt.wrap(self._mutable_integer_val) \ No newline at end of file From 0f2f45d1fc0648d1e8bcc7a842958b6c87735516 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 24 Mar 2015 06:47:53 -0600 Subject: [PATCH 072/349] specialize deftypes for ints and floats --- pixie/vm/custom_types.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 2e9776d7..05008d2a 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -2,7 +2,7 @@ import rpython.rlib.jit as jit from rpython.rlib.rarithmetic import r_uint from pixie.vm.code import as_var -from pixie.vm.numbers import Integer +from pixie.vm.numbers import Integer, Float from pixie.vm.keyword import Keyword import pixie.vm.rt as rt @@ -110,6 +110,9 @@ def _new__args(args): val = args[x + 1] if isinstance(val, Integer): val = IntegerMutableCell(val.int_val()) + elif isinstance(val, Float): + val = FloatMutableCell(val.float_val()) + arr[x] = val return CustomTypeInstance(tp, arr) @@ -146,9 +149,29 @@ def __init__(self, int_val): def set_mutable_cell_value(self, ct, fields, nm, idx, value): if not isinstance(value, Integer): ct.set_mutable(nm) - fields[idx] = value + if isinstance(value, Float): + fields[idx] = FloatMutableCell(value.float_val()) + else: + fields[idx] = value else: self._mutable_integer_val = value.int_val() def get_mutable_cell_value(self): - return rt.wrap(self._mutable_integer_val) \ No newline at end of file + return rt.wrap(self._mutable_integer_val) + +class FloatMutableCell(AbstractMutableCell): + def __init__(self, float_val): + self._mutable_float_val = float_val + + def set_mutable_cell_value(self, ct, fields, nm, idx, value): + if not isinstance(value, Float): + ct.set_mutable(nm) + if isinstance(value, Integer): + fields[idx] = IntegerMutableCell(value.int_val()) + else: + fields[idx] = value + else: + self._mutable_float_val = value.float_val() + + def get_mutable_cell_value(self): + return rt.wrap(self._mutable_float_val) \ No newline at end of file From 74c5e4b30b7bd7c7ee0c856bcf3278ceee003dd1 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 22:38:13 +0100 Subject: [PATCH 073/349] Add some useful constants to string.pxi --- pixie/string.pxi | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pixie/string.pxi b/pixie/string.pxi index 496d3363..8ab30b34 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -17,6 +17,17 @@ (def lower-case si/lower-case) (def upper-case si/upper-case) +; TODO: There should be locale-aware variants of these values +(def lower "abcdefghijklmnopqrstuvwxyz") +(def upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ") +(def digits "0123456789") +(def punctuation "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") +(def whitespace (str \space \newline \tab \backspace \formfeed \return)) +(def letters (str lower upper)) +(def printable (str letters digits punctuation whitespace)) +(def hexdigits "0123456789abcdefABCDEF") +(def octdigits "012345678") + (defn replace "Replace all occurrences of x in s with r." [s x r] @@ -54,7 +65,7 @@ "True if s is nil, empty, or contains only whitespace." [s] (if s - (let [white #{\space \newline \tab \backspace \formfeed \return} + (let [white (set whitespace) length (count s)] (loop [index 0] (if (= length index) From 621020f4047937d8d8626f8c6eb9784acf98b761 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 24 Mar 2015 16:04:19 -0600 Subject: [PATCH 074/349] removed jit abort warnings, will re-enable later if needed --- target.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/target.py b/target.py index 5bd33e85..b153fafe 100644 --- a/target.py +++ b/target.py @@ -18,10 +18,12 @@ import rpython.rlib.rpath as rpath import rpython.rlib.rpath as rposix from rpython.rlib.objectmodel import we_are_translated +from rpython.jit.codewriter.policy import log class DebugIFace(JitHookInterface): def on_abort(self, reason, jitdriver, greenkey, greenkey_repr, logops, operations): - print "Aborted Trace, reason: ", Counters.counter_names[reason], logops, greenkey_repr + # print "Aborted Trace, reason: ", Counters.counter_names[reason], logops, greenkey_repr + pass import sys, pdb From 07b20d883f69f31dcb968b71ae9f8e5a53845c91 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:06:55 +0100 Subject: [PATCH 075/349] Let pixie.string/index-of return nil instead of -1 when the substring was not found. This allows more concise code because now you can use if-let, or, etc. instead of having to write an explicit check for -1 every time. --- pixie/string.pxi | 16 +++++++--------- tests/pixie/tests/test-strings.pxi | 8 ++++---- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/pixie/string.pxi b/pixie/string.pxi index 8ab30b34..2ca53b83 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -3,7 +3,7 @@ ; reexport native string functions (def substring si/substring) -(def index-of si/index-of) +(def index-of (comp #(if (not= -1 %) %) si/index-of)) (def split si/split) (def ends-with? si/ends-with) @@ -34,18 +34,16 @@ (let [offset (if (zero? (count x)) (+ 1 (count r)) (count r))] (loop [start 0 s s] - (let [i (index-of s x start)] - (if (neg? i) - s - (recur (+ i offset) (str (substring s 0 i) r (substring s (+ i (count x)))))))))) + (if-let [i (index-of s x start)] + (recur (+ i offset) (str (substring s 0 i) r (substring s (+ i (count x))))) + s)))) (defn replace-first "Replace the first occurrence of x in s with r." [s x r] - (let [i (index-of s x)] - (if (neg? i) - s - (str (substring s 0 i) r (substring s (+ i (count x))))))) + (if-let [i (index-of s x)] + (str (substring s 0 i) r (substring s (+ i (count x)))) + s)) (defn join {:doc "Join the elements of the collection using an optional separator" diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 248d8ca2..27b3f13b 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -31,15 +31,15 @@ (let [s "heyhohuh"] (t/assert= (s/index-of s "hey") 0) (t/assert= (s/index-of s "ho") 3) - (t/assert= (s/index-of s "foo") -1) + (t/assert= (s/index-of s "foo") nil) (t/assert= (s/index-of s "h" 2) 3) (t/assert= (s/index-of s "h" 4) 5) (t/assert= (s/index-of s "hey" 0) 0) - (t/assert= (s/index-of s "hey" 1) -1) + (t/assert= (s/index-of s "hey" 1) nil) - (t/assert= (s/index-of s "h" 0 0) -1) - (t/assert= (s/index-of s "h" 1 2) -1))) + (t/assert= (s/index-of s "h" 0 0) nil) + (t/assert= (s/index-of s "h" 1 2) nil))) (t/deftest test-substring (let [s "heyhohuh"] From 30aac1b6cc4cf40fd74a67c3dc3ead4b5767ccf6 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:13:58 +0100 Subject: [PATCH 076/349] Add a macro for string interpolation to pixie.string. --- pixie/string.pxi | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/pixie/string.pxi b/pixie/string.pxi index 2ca53b83..36be0b86 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -72,3 +72,32 @@ (recur (inc index)) false)))) true)) + +(defmacro interp + ; TODO: This might merit special read syntax + {:doc "String interpolation." + :examples [["(require pixie.string :refer [interp])"] + ["(interp \"2 plus 2 is $(+ 2 2)$!\")" nil "2 plus 2 is 4!"] + ["(let [x \"locals\"] (interp \"You can use arbitrary forms; for example $x$\"))" + nil "You can use arbitrary forms; for example locals"] + ["(interp \"$$$$ is the escape for a literal $$\")" + nil "$$ is the escape for a literal $"] + ]} + [txt] + (loop [forms [], txt txt] + (cond + (empty? txt) `(str ~@ forms) + (starts-with? txt "$") + (let [pos (or (index-of txt "$" 1) + (throw "Unmatched $ in interp argument!")) + form-str (subs txt 1 pos) + form (if (empty? form-str) "$" + (read-string form-str)) + rest-str (subs txt (inc pos))] + (recur (conj forms form) rest-str)) + :else + (let [pos (or (index-of txt "$") + (count txt)) + form (subs txt 0 pos) + rest-str (subs txt pos)] + (recur (conj forms form) rest-str))))) From 93007e16ffc029ea617fa861d2293e989f636feb Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:22:24 +0100 Subject: [PATCH 077/349] Implement constantly. --- pixie/stdlib.pxi | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index e733bee2..bd30be04 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -861,6 +861,12 @@ If further arguments are passed, invokes the method named by symbol, passing the ([x y] (not (f x y))) ([x y & more] (not (apply f x y more)))))) +(defn constantly [x] + {:doc "Return a function that always returns x, no matter what it is called with." + :examples [["(let [f (constantly :me)] [(f 1) (f \"foo\") (f :abc) (f nil)])" + nil [:me :me :me :me]]]} + (fn [& _] x)) + (defn some {:doc "Checks if the predicate is true for any element of the collection. From 6a89ba01d3a4e6ad85989cee09fbc0ef771e5e9e Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:22:44 +0100 Subject: [PATCH 078/349] Implement repeatedly. --- pixie/stdlib.pxi | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index bd30be04..bf6a31fe 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1249,6 +1249,17 @@ and implements IAssociative, ILookup and IObject." ([n x] (take n (repeat x)))) +(defn repeatedly + {:doc "Returns a lazy seq that contains the return values of repeated calls to f. + + Yields an infinite seq with one argument. + With two arguments n specifies the number of elements." + :examples [["(into '(:batman!) (repeatedly 8 (fn [] :na)))" + nil (:na :na :na :na :na :na :na :na :batman!)]] + :signatures [[f] [n f]]} + ([f] (lazy-seq (cons (f) (repeatedly f)))) + ([n f] (take n (repeatedly f)))) + (defmacro doseq {:doc "Evaluates all elements of the seq, presumably for side effects. Returns nil." :added "0.1"} From 654829b6d0f7123831d5b8f79eadac8a0a63415d Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:25:53 +0100 Subject: [PATCH 079/349] Define the REPL history vars in stdlib.pxi instead of in target.py. --- pixie/stdlib.pxi | 4 ++++ target.py | 61 ------------------------------------------------ 2 files changed, 4 insertions(+), 61 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index bf6a31fe..72f11e10 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2197,10 +2197,14 @@ Expands to calls to `extend-type`." ([f col] (transduce (map f) conj col))) +(def *1) +(def *2) +(def *3) (defn -push-history [x] (def *3 *2) (def *2 *1) (def *1 x)) +(def *e) (defn -set-*e [e] (def *e e)) diff --git a/target.py b/target.py index 5bd33e85..9b908672 100644 --- a/target.py +++ b/target.py @@ -40,15 +40,6 @@ def jitpolicy(driver): LOAD_PATHS.set_root(nil) load_path = Var(u"pixie.stdlib", u"internal-load-path") -STAR_1 = intern_var(u"pixie.stdlib", u"*1") -STAR_1.set_root(nil) -STAR_2 = intern_var(u"pixie.stdlib", u"*2") -STAR_2.set_root(nil) -STAR_3 = intern_var(u"pixie.stdlib", u"*3") -STAR_3.set_root(nil) -STAR_E = intern_var(u"pixie.stdlib", u"*e") -STAR_E.set_root(nil) - class ReplFn(NativeFn): def __init__(self, args): self._argv = args @@ -62,58 +53,6 @@ def inner_invoke(self, args): with with_ns(u"user"): repl.invoke([]) - - - # def inner_invoke(self, args): - # from pixie.vm.keyword import keyword - # import pixie.vm.rt as rt - # from pixie.vm.string import String - # import pixie.vm.persistent_vector as vector - # - # print "Pixie 0.1 - Interactive REPL" - # print "(" + platform.name + ", " + platform.cc + ")" - # print ":exit-repl or Ctrl-D to quit" - # print "----------------------------" - # - # with with_ns(u"user"): - # NS_VAR.deref().include_stdlib() - # - # acc = vector.EMPTY - # for x in self._argv: - # acc = rt.conj(acc, rt.wrap(x)) - # - # PROGRAM_ARGUMENTS.set_root(acc) - # - # rdr = MetaDataReader(PromptReader()) - # with with_ns(u"user"): - # while True: - # try: - # val = read(rdr, False) - # if val is eof: - # break - # val = interpret(compile(val)) - # self.set_recent_vars(val) - # except WrappedException as ex: - # print "Error: ", ex._ex.__repr__() - # rdr.reset_line() - # self.set_error_var(ex._ex) - # continue - # if val is keyword(u"exit-repl"): - # break - # val = rt._repr(val) - # assert isinstance(val, String), "str should always return a string" - # print unicode_to_utf8(val._str) - - def set_recent_vars(self, val): - if rt.eq(val, STAR_1.deref()): - return - STAR_3.set_root(STAR_2.deref()) - STAR_2.set_root(STAR_1.deref()) - STAR_1.set_root(val) - - def set_error_var(self, ex): - STAR_E.set_root(ex) - class BatchModeFn(NativeFn): def __init__(self, args): self._file = args[0] From fe5eefb79bc0ad6ee4a661c1316c5b82277929d9 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:30:43 +0100 Subject: [PATCH 080/349] Implement map-invert. --- pixie/stdlib.pxi | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 72f11e10..d5af0017 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1049,6 +1049,15 @@ Creates new maps if the keys are not present." (assoc m k (apply update-inner-f (get m k) f ks))))] (apply update-inner-f m f ks))) +; FIXME: This causes compile_basics to fail on stacklets.pxi for some weird reason. +; (defn map-invert +; {:doc "Return a map where the vals are mapped to the keys." +; :examples [["(map-invert {:a :b, :c :d})" nil {:b :a, :d :c}]]} +; [m] +; (reduce (fn [m* ent] +; (assoc m* (val ent) (key ent))) +; {} m)) + (def subs pixie.string.internal/substring) (defmacro assert From 9977b6e02bd40b464e7215952d241b90dcda8afe Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 24 Mar 2015 23:50:23 +0100 Subject: [PATCH 081/349] Implement condp and case. --- pixie/stdlib.pxi | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index d5af0017..a8427e73 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -751,7 +751,6 @@ there's a value associated with the key. Use `some` for checking for values." ~then (cond ~@clauses)))) - (defmacro try [& body] (loop [catch nil catch-sym nil @@ -2141,6 +2140,23 @@ Expands to calls to `extend-type`." [~@body])))] `(or (seq ~(gen-loop [] bindings)) '()))) +;; TODO: docs, tests +;; TODO: implement :>> like in Clojure? +(defmacro condp [pred-form expr & clauses] + (let [x (gensym 'expr), pred (gensym 'pred)] + `(let [~x ~expr, ~pred ~pred-form] + (cond ~@(mapcat + (fn [[a b :as clause]] + (if (> (count clause) 1) + `((~pred ~a ~x) ~b) + `(:else ~a))) + (partition 2 clauses)))))) + +;; TODO: Not sure if I like the set idea... +(defmacro case [expr & args] + `(condp #(if (set? %1) (%1 %2) (= %1 %2)) + ~expr ~@args)) + (defmacro use [ns] `(do From a09fdb9650fbfed4a751a18fe425c6569ae68cb2 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 02:32:00 +0100 Subject: [PATCH 082/349] Add a comment that will hopefully prevent others from repeating my latest mistake. --- pixie/stdlib.pxi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a8427e73..569678b9 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1967,6 +1967,9 @@ user => (refer 'pixie.string :exclude '(substring))" (pred (first coll)) (recur pred (next coll)) :else false)) +; If you want a fn that uses destructuring in its parameter list, place +; it after this definition. If you don't, you will get compile failures +; in unrelated files. (defmacro fn {:doc "Creates a function. From 4c551420181e5d1aa7c9c5a9a16c57f5cc6cd80e Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 00:01:59 +0100 Subject: [PATCH 083/349] Implement flatten. --- pixie/stdlib.pxi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 569678b9..1421d1d8 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2221,6 +2221,19 @@ Expands to calls to `extend-type`." (mapcat walk (children node))))))] (walk root))) +(defn flatten [x] + ; TODO: laziness? + {:doc "Take any nested combination of ISeqable things, and return their contents + as a single, flat sequence. + + Calling this function on something that is not ISeqable returns a seq with that + value as its only element." + :examples [["(flatten [[1 2 [3 4] [5 6]] 7])" nil [1 2 3 4 5 6 7]]]} + (if (not (satisfies? ISeqable x)) [x] + (transduce (comp (map flatten) cat) + conj [] + (seq x)))) + (defn mapv ([f col] (transduce (map f) conj col))) From 8b59da425abeee964c51b6491ce1c75c74d61446 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 00:43:30 +0100 Subject: [PATCH 084/349] Implement partitionf. --- pixie/stdlib.pxi | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1421d1d8..58ba6396 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1596,6 +1596,14 @@ not enough elements were present." (when-let [s (seq coll)] (cons (take n s) (partition n step (drop step s)))))) +;; TODO: docs, tests +(defn partitionf [f coll] + (when-let [s (seq coll)] + (lazy-seq + (let [n (f s)] + (cons (take n s) + (partitionf f (drop n coll))))))) + (defn destructure [binding expr] (cond (symbol? binding) [binding expr] From d4d7a05faabe236b71e84290fc96223cefc5d6f0 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 00:44:05 +0100 Subject: [PATCH 085/349] Make partition return a lazy seq. --- pixie/stdlib.pxi | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 58ba6396..4ed561d2 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1593,8 +1593,9 @@ not enough elements were present." :added "0.1"} ([n coll] (partition n n coll)) ([n step coll] - (when-let [s (seq coll)] - (cons (take n s) (partition n step (drop step s)))))) + (when-let [s (seq coll)] + (lazy-seq + (cons (take n s) (partition n step (drop step s))))))) ;; TODO: docs, tests (defn partitionf [f coll] From 665e78bbd843b15fa690d4262a5c64253ce0e751 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 02:01:34 +0100 Subject: [PATCH 086/349] Make it possible to pass a vector of types/protocols to instance? and satisfies?. --- pixie/vm/stdlib.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 79bff639..2e16f608 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -337,16 +337,36 @@ def apply__args(args): @returns(bool) @as_var("instance?") def _instance(c, o): - affirm(isinstance(c, Type), u"c must be a type") + from pixie.vm.persistent_vector import PersistentVector + if isinstance(c, Type): + return true if istypeinstance(o, c) else false + elif isinstance(c, PersistentVector): + for i in range(rt.count(c)): + t = rt.nth(c, rt.wrap(i)) + affirm(isinstance(t, Type), u"every element of c must be a type") + if istypeinstance(o, t): + return true + return false + else: + affirm(False, u"c must be a type or a vector") - return true if istypeinstance(o, c) else false @returns(bool) @as_var("satisfies?") def _satisfies(proto, o): - affirm(isinstance(proto, Protocol), u"proto must be a Protocol") - - return true if proto.satisfies(o.type()) else false + from pixie.vm.persistent_vector import PersistentVector + t = o.type() + if isinstance(proto, Protocol): + return true if proto.satisfies(t) else false + elif isinstance(proto, PersistentVector): + for i in range(rt.count(proto)): + p = rt.nth(proto, rt.wrap(i)) + affirm(isinstance(p, Protocol), u"every element of proto must be a Protocol") + if p.satisfies(t): + return true + return false + else: + affirm(False, u"c must be a Protocol or a vector") import pixie.vm.rt as rt From 80373e8ee5e7ad7240fb5cddf0ce34f801ab61e4 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 02:43:34 +0100 Subject: [PATCH 087/349] Let list? also return true when the argument is a Cons. This means that (list? '(1 2 3)) is now true. --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4ed561d2..40014735 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -801,7 +801,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn string? [v] (instance? String v)) (defn keyword? [v] (instance? Keyword v)) -(defn list? [v] (instance? PersistentList v)) +(defn list? [v] (instance? [PersistentList Cons] v)) (defn set? [v] (instance? PersistentHashSet v)) (defn map? [v] (satisfies? IMap v)) (defn fn? [v] (satisfies? IFn v)) From 2195850eb331e667500ed8066ed2bf80a8cdd750 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 02:45:39 +0100 Subject: [PATCH 088/349] Implement juxt. --- pixie/stdlib.pxi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 40014735..5d5cc79d 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2243,6 +2243,11 @@ Expands to calls to `extend-type`." conj [] (seq x)))) +; TODO: tests, docs +(defn juxt [& fns] + (fn [& args] + (mapv #(apply % args) fns))) + (defn mapv ([f col] (transduce (map f) conj col))) From 3b779d9394bc6000e46c939012b9784fd900749e Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 02:46:11 +0100 Subject: [PATCH 089/349] Add a colon to the error message of assert. This makes it clear where the user-supplied message begins. (I had one occasion where I misinterpreted the message, until I had looked at the code.) --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 5d5cc79d..f6ae715d 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1067,7 +1067,7 @@ Creates new maps if the keys are not present." ([test msg] `(if ~test nil - (throw (str "Assert failed " ~msg))))) + (throw (str "Assert failed: " ~msg))))) (defmacro resolve {:doc "Resolve the var associated with the symbol in the current namespace." From b3b551869490dddcfb17116aaf8a19c36eb996a8 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:06:44 +0100 Subject: [PATCH 090/349] Have some return the first true value of the predicate instead of just true. --- pixie/stdlib.pxi | 12 +++++------- tests/pixie/tests/test-stdlib.pxi | 5 ++++- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index f6ae715d..e72f554b 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -867,16 +867,14 @@ If further arguments are passed, invokes the method named by symbol, passing the (fn [& _] x)) (defn some - {:doc "Checks if the predicate is true for any element of the collection. - -Stops if it finds such an element." + {:doc "Returns the first true value of the predicate for the elements of the collection." :signatures [[pred coll]] :added "0.1"} [pred coll] - (cond - (nil? (seq coll)) false - (pred (first coll)) true - :else (recur pred (next coll)))) + (if-let [coll (seq coll)] + (or (pred (first coll)) + (recur pred (next coll))) + false)) (extend -count MapEntry (fn [self] 2)) (extend -nth MapEntry (fn map-entry-nth [self idx] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 0f01e5fa..8a411d97 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -277,7 +277,10 @@ (t/assert= (some even? [2 3 6 8]) true) (t/assert= (some even? [1 3 5 8]) true) (t/assert= (some even? []) false) - (t/assert= (some odd? [2]) false)) + (t/assert= (some odd? [2]) false) + (t/assert= (some #{:x :y} [:a :b :x :y]) :x) + (t/assert= (some #{:x :y} [:a :b :c :y]) :y) + (t/assert= (some #{:x :y} [:a :b :c :d]) false)) (t/deftest test-filter (t/assert= (vec (filter (fn [x] true) [])) []) From e0efdc7654c35d19e16f5775c78bc9c3ca867d84 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:15:04 +0100 Subject: [PATCH 091/349] Uncomment map-invert. --- pixie/stdlib.pxi | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index e72f554b..48172688 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1046,15 +1046,6 @@ Creates new maps if the keys are not present." (assoc m k (apply update-inner-f (get m k) f ks))))] (apply update-inner-f m f ks))) -; FIXME: This causes compile_basics to fail on stacklets.pxi for some weird reason. -; (defn map-invert -; {:doc "Return a map where the vals are mapped to the keys." -; :examples [["(map-invert {:a :b, :c :d})" nil {:b :a, :d :c}]]} -; [m] -; (reduce (fn [m* ent] -; (assoc m* (val ent) (key ent))) -; {} m)) - (def subs pixie.string.internal/substring) (defmacro assert @@ -2246,6 +2237,14 @@ Expands to calls to `extend-type`." (fn [& args] (mapv #(apply % args) fns))) +(defn map-invert + {:doc "Return a map where the vals are mapped to the keys." + :examples [["(map-invert {:a :b, :c :d})" nil {:b :a, :d :c}]]} + [m] + (reduce (fn [m* ent] + (assoc m* (val ent) (key ent))) + {} m)) + (defn mapv ([f col] (transduce (map f) conj col))) From c44680e963b193245a5fb0945e481d7c178f2633 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:20:09 +0100 Subject: [PATCH 092/349] Add a docstring for partitionf. --- pixie/stdlib.pxi | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 48172688..b7a77981 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1586,8 +1586,12 @@ not enough elements were present." (lazy-seq (cons (take n s) (partition n step (drop step s))))))) -;; TODO: docs, tests (defn partitionf [f coll] + {:doc "A generalized version of partition. Instead of taking a constant number of elements, + this function calls f with the remaining collection to determine how many elements to + take." + :examples [["(fpartition first [1 :a, 2 :a b, 3 :a :b :c])" + nil ((1 :a) (2 :a :b) (3 :a :b :c))]]} (when-let [s (seq coll)] (lazy-seq (let [n (f s)] From 6c0ee5a975d555586380962aec1c3dfc407b45e0 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:21:57 +0100 Subject: [PATCH 093/349] Add a docstring for juxt. --- pixie/stdlib.pxi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index b7a77981..a9746f47 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2236,8 +2236,10 @@ Expands to calls to `extend-type`." conj [] (seq x)))) -; TODO: tests, docs (defn juxt [& fns] + {:doc "Returns a function that applies all fns to its arguments, + and returns a vector of the results." + :examples [["((juxt + - *) 2 3)" nil [5 -1 6]]]} (fn [& args] (mapv #(apply % args) fns))) From 64411dc9575089eed8558d238ed90d30dc2e2861 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:25:17 +0100 Subject: [PATCH 094/349] Implement reverse. --- pixie/stdlib.pxi | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a9746f47..c6f56a9f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2145,6 +2145,13 @@ Expands to calls to `extend-type`." [~@body])))] `(or (seq ~(gen-loop [] bindings)) '()))) +(defn reverse + ; TODO: We should probably have a protocol IReversible, so we can e.g. + ; reverse vectors efficiently, etc.. + [coll] + "Returns a collection that contains all the elements of the argument in reverse order." + (into () coll)) + ;; TODO: docs, tests ;; TODO: implement :>> like in Clojure? (defmacro condp [pred-form expr & clauses] From 3992bf3029b180e3e9083b3eff313df23dcf6a87 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:33:34 +0100 Subject: [PATCH 095/349] Docs and tests for condp --- pixie/stdlib.pxi | 10 ++++++++-- tests/pixie/tests/test-stdlib.pxi | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index c6f56a9f..112e25f8 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2152,9 +2152,15 @@ Expands to calls to `extend-type`." "Returns a collection that contains all the elements of the argument in reverse order." (into () coll)) -;; TODO: docs, tests ;; TODO: implement :>> like in Clojure? -(defmacro condp [pred-form expr & clauses] +(defmacro condp + "Takes a binary predicate, an expression and a number of two-form clauses. + Calls the predicate on the first value of each clause and the expression. + If the result is truthy returns the second value of the clause. + + If the number of arguments is odd and no clause matches, the last argument is returned. + If the number of arguments is even and no clause matches, nil is returned." + [pred-form expr & clauses] (let [x (gensym 'expr), pred (gensym 'pred)] `(let [~x ~expr, ~pred ~pred-form] (cond ~@(mapcat diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 8a411d97..f7610298 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -419,3 +419,14 @@ (t/deftest test-frequencies (t/assert= (frequencies [1 2 3 4 3 2 1]) {1 2, 2 2, 3 2, 4 1})) + +(t/deftest test-condp + (t/assert= (condp :dont-call-me :dont-use-me) nil) + (let [f (fn [x] + (condp = x + 0 :one + 1 :two + :whatever))] + (t/assert= (f 0) :one) + (t/assert= (f 1) :two) + (t/assert= (f 9) :whatever))) From 57577179697621177ae008de2ae1004901de7db8 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:38:56 +0100 Subject: [PATCH 096/349] Docs and tests for case --- pixie/stdlib.pxi | 13 +++++++++++-- tests/pixie/tests/test-stdlib.pxi | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 112e25f8..be39e096 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2170,8 +2170,17 @@ Expands to calls to `extend-type`." `(:else ~a))) (partition 2 clauses)))))) -;; TODO: Not sure if I like the set idea... -(defmacro case [expr & args] +(defmacro case + "Takes an expression and a number of two-form clauses. + Checks for each clause if the first part is equal to the expression. + If yes, returns the value of the second part. + + The first part of each clause can also be a set. If that is the case, the clause + matches when the result of the expression is in the set. + + If the number of arguments is odd and no clause matches, the last argument is returned. + If the number of arguments is even and no clause matches, nil is returned." + [expr & args] `(condp #(if (set? %1) (%1 %2) (= %1 %2)) ~expr ~@args)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index f7610298..2a99da4c 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -430,3 +430,17 @@ (t/assert= (f 0) :one) (t/assert= (f 1) :two) (t/assert= (f 9) :whatever))) + +(t/deftest test-case + (t/assert= (case :unused) nil) + (let [f (fn [x] + (case x + 1 :one + 2 :two + #{3 4} :large + :toolarge))] + (t/assert= (f 1) :one) + (t/assert= (f 2) :two) + (t/assert= (f 3) :large) + (t/assert= (f 4) :large) + (t/assert= (f 9) :toolarge))) From d644aca8c2f217b0dc7b481ed20edca49e73b90d Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 03:39:42 +0100 Subject: [PATCH 097/349] Fix my way of defining the natural numbers being slightly inconsistent with the rest of the universe. --- tests/pixie/tests/test-stdlib.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 2a99da4c..75e71785 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -424,11 +424,11 @@ (t/assert= (condp :dont-call-me :dont-use-me) nil) (let [f (fn [x] (condp = x - 0 :one - 1 :two + 1 :one + 2 :two :whatever))] - (t/assert= (f 0) :one) - (t/assert= (f 1) :two) + (t/assert= (f 1) :one) + (t/assert= (f 2) :two) (t/assert= (f 9) :whatever))) (t/deftest test-case From cd537bed418c01e830c2f86698c0a3ba64047c5c Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 04:51:15 +0100 Subject: [PATCH 098/349] Implement split-at. --- pixie/stdlib.pxi | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index be39e096..53171006 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1490,6 +1490,13 @@ The new value is thus `(apply f current-value-of-atom args)`." (recur (dec n) (next s)) s))) +(defn split-at + {:doc "Returns a vector of the first n elements of the collection, and the remaining elements." + :examples [["(split-at 2 [:a :b :c :d :e])" nil + [(:a :b) (:c :d :e)]]]} + [n coll] + [(take n coll) (drop n coll)]) + (defmacro while {:doc "Repeatedly executes body while test expression is true. Presumes some side-effect will cause test to become false/nil. Returns nil" From f4974404cd0c98afbd718f553c35897ac2146d7d Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 04:54:23 +0100 Subject: [PATCH 099/349] More consistent docstrings --- pixie/stdlib.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 53171006..a313b34c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2254,7 +2254,7 @@ Expands to calls to `extend-type`." (defn flatten [x] ; TODO: laziness? - {:doc "Take any nested combination of ISeqable things, and return their contents + {:doc "Takes any nested combination of ISeqable things, and return their contents as a single, flat sequence. Calling this function on something that is not ISeqable returns a seq with that @@ -2273,7 +2273,7 @@ Expands to calls to `extend-type`." (mapv #(apply % args) fns))) (defn map-invert - {:doc "Return a map where the vals are mapped to the keys." + {:doc "Returns a map where the vals are mapped to the keys." :examples [["(map-invert {:a :b, :c :d})" nil {:b :a, :d :c}]]} [m] (reduce (fn [m* ent] From 0c1ae9139a16fe0eaf7f71094ad7cc9e7b1e21a0 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 04:54:49 +0100 Subject: [PATCH 100/349] Add another example for flatten. --- pixie/stdlib.pxi | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a313b34c..c2df95cc 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2259,7 +2259,8 @@ Expands to calls to `extend-type`." Calling this function on something that is not ISeqable returns a seq with that value as its only element." - :examples [["(flatten [[1 2 [3 4] [5 6]] 7])" nil [1 2 3 4 5 6 7]]]} + :examples [["(flatten [[1 2 [3 4] [5 6]] 7])" nil [1 2 3 4 5 6 7]] + ["(flatten :this)" nil [:this]]]} (if (not (satisfies? ISeqable x)) [x] (transduce (comp (map flatten) cat) conj [] From 30f4f2cdab8f42cf6d74fc1991baa381428f5a53 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 25 Mar 2015 11:07:01 +0000 Subject: [PATCH 101/349] fix buffer-size-check --- pixie/io-blocking.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 326d5aca..5dd57346 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -18,7 +18,7 @@ (deftype FileStream [fp] IInputStream (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) + (assert (>= (buffer-capacity buffer) len) "Not enough capacity in the buffer") (let [read-count (fread buffer 1 len fp)] (set-buffer-count! buffer read-count) From 406a624891b73f374a2d44a547b0f87f2a5b841d Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 12:49:09 +0100 Subject: [PATCH 102/349] Let case and condp throw RuntimeExceptions when no clause matches. --- pixie/stdlib.pxi | 10 +++++----- tests/pixie/tests/test-stdlib.pxi | 8 ++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index c2df95cc..e2d6e742 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2166,7 +2166,7 @@ Expands to calls to `extend-type`." If the result is truthy returns the second value of the clause. If the number of arguments is odd and no clause matches, the last argument is returned. - If the number of arguments is even and no clause matches, nil is returned." + If the number of arguments is even and no clause matches, throws an exception." [pred-form expr & clauses] (let [x (gensym 'expr), pred (gensym 'pred)] `(let [~x ~expr, ~pred ~pred-form] @@ -2175,18 +2175,18 @@ Expands to calls to `extend-type`." (if (> (count clause) 1) `((~pred ~a ~x) ~b) `(:else ~a))) - (partition 2 clauses)))))) + (partition 2 clauses)) + :else (throw "No matching clause!"))))) (defmacro case "Takes an expression and a number of two-form clauses. Checks for each clause if the first part is equal to the expression. If yes, returns the value of the second part. - The first part of each clause can also be a set. If that is the case, the clause - matches when the result of the expression is in the set. + The first part of each clause can also be a set. If that is the case, the clause matches when the result of the expression is in the set. If the number of arguments is odd and no clause matches, the last argument is returned. - If the number of arguments is even and no clause matches, nil is returned." + If the number of arguments is even and no clause matches, throws an exception." [expr & args] `(condp #(if (set? %1) (%1 %2) (= %1 %2)) ~expr ~@args)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 75e71785..3f23d9db 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -421,7 +421,9 @@ {1 2, 2 2, 3 2, 4 1})) (t/deftest test-condp - (t/assert= (condp :dont-call-me :dont-use-me) nil) + (t/assert-throws? RuntimeException + "No matching clause!" + (condp :dont-call-me :dont-use-me)) (let [f (fn [x] (condp = x 1 :one @@ -432,7 +434,9 @@ (t/assert= (f 9) :whatever))) (t/deftest test-case - (t/assert= (case :unused) nil) + (t/assert-throws? RuntimeException + "No matching clause!" + (case :no-matter-what)) (let [f (fn [x] (case x 1 :one From 3fdbcad059b9efa4841483924d1d2ed31b8cab31 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 12:50:33 +0100 Subject: [PATCH 103/349] Fix example for partitionf. --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index e2d6e742..8a99daac 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1597,7 +1597,7 @@ not enough elements were present." {:doc "A generalized version of partition. Instead of taking a constant number of elements, this function calls f with the remaining collection to determine how many elements to take." - :examples [["(fpartition first [1 :a, 2 :a b, 3 :a :b :c])" + :examples [["(partitionf first [1 :a, 2 :a b, 3 :a :b :c])" nil ((1 :a) (2 :a :b) (3 :a :b :c))]]} (when-let [s (seq coll)] (lazy-seq From 4ba33b2bdccb1ce3877e972bf036f3a33be84cec Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 12:56:02 +0100 Subject: [PATCH 104/349] Revert the changes to instance? and satisfies?. This reverts commit 665e78bbd843b15fa690d4262a5c64253ce0e751. I will reimplement this in stdlib.pxi. --- pixie/vm/stdlib.py | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 2e16f608..79bff639 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -337,36 +337,16 @@ def apply__args(args): @returns(bool) @as_var("instance?") def _instance(c, o): - from pixie.vm.persistent_vector import PersistentVector - if isinstance(c, Type): - return true if istypeinstance(o, c) else false - elif isinstance(c, PersistentVector): - for i in range(rt.count(c)): - t = rt.nth(c, rt.wrap(i)) - affirm(isinstance(t, Type), u"every element of c must be a type") - if istypeinstance(o, t): - return true - return false - else: - affirm(False, u"c must be a type or a vector") + affirm(isinstance(c, Type), u"c must be a type") + return true if istypeinstance(o, c) else false @returns(bool) @as_var("satisfies?") def _satisfies(proto, o): - from pixie.vm.persistent_vector import PersistentVector - t = o.type() - if isinstance(proto, Protocol): - return true if proto.satisfies(t) else false - elif isinstance(proto, PersistentVector): - for i in range(rt.count(proto)): - p = rt.nth(proto, rt.wrap(i)) - affirm(isinstance(p, Protocol), u"every element of proto must be a Protocol") - if p.satisfies(t): - return true - return false - else: - affirm(False, u"c must be a Protocol or a vector") + affirm(isinstance(proto, Protocol), u"proto must be a Protocol") + + return true if proto.satisfies(o.type()) else false import pixie.vm.rt as rt From b233b136bb929127b2ac9a53125bb2cca2f4c984 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 14:08:55 +0100 Subject: [PATCH 105/349] Let satisfies? and instance? both take seqables as their first argument. This time this is implemented in pixie code. --- pixie/stdlib.pxi | 24 ++++++++++++++++++++++++ pixie/vm/compiler.py | 6 +++--- pixie/vm/libs/pxic/writer.py | 6 +++--- pixie/vm/persistent_vector.py | 2 +- pixie/vm/reader.py | 6 +++--- pixie/vm/stdlib.py | 20 ++++++++++---------- 6 files changed, 44 insertions(+), 20 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 8a99daac..1853fe83 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -164,6 +164,30 @@ (def reduce (fn [rf init col] (-reduce col rf init))) +(def instance? (fn ^{:doc "Checks if x is an instance of t. + + When t is seqable, checks if x is an instance of + any of the types contained therein."} + instance? [t x] + (if (-satisfies? ISeqable t) + (let [ts (seq t)] + (if (not ts) false + (or (-instance? (first ts) x) + (instance? (rest ts) x)))) + (-instance? t x)))) + +(def satisfies? (fn ^{:doc "Checks if x satisfies the protocol p. + + When p is seqable, checks if x satisfies all of + the protocols contained therein."} + satisfies? [p x] + (if (-satisfies? ISeqable p) + (let [ps (seq p)] + (if (not ps) true + (and (-satisfies? (first ps) x) + (satisfies? (rest ps) x)))) + (-satisfies? p x)))) + (def into (fn ^{:doc "Add the elements of `from` to the collection `to`." :signatures [[to from]] :added "0.1"} diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index b17b3b4f..c915214a 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -353,7 +353,7 @@ def compile_form(form, ctx): ctx.push_const(nil) return - if rt.satisfies_QMARK_(rt.ISeq.deref(), form) and form is not nil: + if rt._satisfies_QMARK_(rt.ISeq.deref(), form) and form is not nil: form = macroexpand(form) return compile_cons(form, ctx) if isinstance(form, numbers.Integer): @@ -425,7 +425,7 @@ def compile_form(form, ctx): compile_set_literal(form, ctx) return - if rt.satisfies_QMARK_(rt.IMap.deref(), form): + if rt._satisfies_QMARK_(rt.IMap.deref(), form): compile_map_literal(form, ctx) return @@ -480,7 +480,7 @@ def compile_fn(form, ctx): - if rt.satisfies_QMARK_(rt.ISeq.deref(), rt.first(form)): + if rt._satisfies_QMARK_(rt.ISeq.deref(), rt.first(form)): arities = [] while form is not nil: required_arity, argc = compile_fn_body(name, rt.first(rt.first(form)), rt.next(rt.first(form)), ctx) diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index 9b3e806d..ecd8865d 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -255,11 +255,11 @@ def write_object(obj, wtr): elif isinstance(obj, Var): #wtr.write_cached_obj(obj, write_var) write_var(obj, wtr) - elif rt.satisfies_QMARK_(rt.IMap.deref(), obj): + elif rt._satisfies_QMARK_(rt.IMap.deref(), obj): write_map(obj, wtr) - elif rt.satisfies_QMARK_(rt.IVector.deref(), obj): + elif rt._satisfies_QMARK_(rt.IVector.deref(), obj): write_vector(obj, wtr) - elif rt.satisfies_QMARK_(rt.ISeq.deref(), obj): + elif rt._satisfies_QMARK_(rt.ISeq.deref(), obj): write_seq(obj, wtr) elif isinstance(obj, Keyword): wtr.write_cached_obj(obj, write_keyword) diff --git a/pixie/vm/persistent_vector.py b/pixie/vm/persistent_vector.py index 26517cd4..65aaacfb 100644 --- a/pixie/vm/persistent_vector.py +++ b/pixie/vm/persistent_vector.py @@ -456,7 +456,7 @@ def _eq(self, obj): return false return true else: - if obj is nil or not rt.satisfies_QMARK_(proto.ISeqable, obj): + if obj is nil or not rt._satisfies_QMARK_(proto.ISeqable, obj): return false seq = rt.seq(obj) for i in range(0, intmask(self._cnt)): diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 4004157d..0e150600 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -449,12 +449,12 @@ def invoke(self, rdr, ch): LIST = symbol(u"list") def is_unquote(form): - return True if rt.satisfies_QMARK_(rt.ISeq.deref(), form) \ + return True if rt._satisfies_QMARK_(rt.ISeq.deref(), form) \ and rt.eq(rt.first(form), UNQUOTE) \ else False def is_unquote_splicing(form): - return True if rt.satisfies_QMARK_(rt.ISeq.deref(), form) \ + return True if rt._satisfies_QMARK_(rt.ISeq.deref(), form) \ and rt.eq(rt.first(form), UNQUOTE_SPLICING) \ else False @@ -537,7 +537,7 @@ def invoke(self, rdr, ch): if isinstance(meta, Symbol): meta = rt.hashmap(keyword(u"tag"), meta) - if rt.satisfies_QMARK_(rt.IMeta.deref(), obj): + if rt._satisfies_QMARK_(rt.IMeta.deref(), obj): return rt.with_meta(obj, rt.merge(meta, rt.meta(obj))) return obj diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 79bff639..6741063b 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -121,7 +121,7 @@ def default_hash(x): @as_var("first") def first(x): - if rt.satisfies_QMARK_(ISeq, x): + if rt._satisfies_QMARK_(ISeq, x): return rt._first(x) seq = rt.seq(x) @@ -131,7 +131,7 @@ def first(x): @as_var("next") def next(x): - if rt.satisfies_QMARK_(ISeq, x): + if rt._satisfies_QMARK_(ISeq, x): return rt.seq(rt._next(x)) seq = rt.seq(x) if seq is nil: @@ -145,7 +145,7 @@ def seq(x): @as_var("seq?") def seq_QMARK_(x): - return true if rt.satisfies_QMARK_(rt.ISeq.deref(), x) else false + return true if rt._satisfies_QMARK_(rt.ISeq.deref(), x) else false @as_var("-seq-eq") def _seq_eq(a, b): @@ -153,7 +153,7 @@ def _seq_eq(a, b): return true if a is nil or b is nil: return false - if not (rt.satisfies_QMARK_(rt.ISeqable.deref(), b) or rt.satisfies_QMARK_(rt.ISeq.deref(), b)): + if not (rt._satisfies_QMARK_(rt.ISeqable.deref(), b) or rt._satisfies_QMARK_(rt.ISeq.deref(), b)): return false a = rt.seq(a) @@ -286,7 +286,7 @@ def __with_meta(a, b): @returns(bool) @as_var("has-meta?") def __has_meta(a): - return true if rt.satisfies_QMARK_(rt.IMeta.deref(), a) else false + return true if rt._satisfies_QMARK_(rt.IMeta.deref(), a) else false @as_var("conj") def conj(a, b): @@ -313,8 +313,8 @@ def str__args(args): @jit.unroll_safe def apply__args(args): last_itm = args[len(args) - 1] - if not (rt.satisfies_QMARK_(rt.IIndexed.deref(), last_itm) and - rt.satisfies_QMARK_(rt.ICounted.deref(), last_itm)): + if not (rt._satisfies_QMARK_(rt.IIndexed.deref(), last_itm) and + rt._satisfies_QMARK_(rt.ICounted.deref(), last_itm)): last_itm = rt.vec(last_itm) fn = args[0] @@ -335,14 +335,14 @@ def apply__args(args): # return nil @returns(bool) -@as_var("instance?") +@as_var("-instance?") def _instance(c, o): affirm(isinstance(c, Type), u"c must be a type") return true if istypeinstance(o, c) else false @returns(bool) -@as_var("satisfies?") +@as_var("-satisfies?") def _satisfies(proto, o): affirm(isinstance(proto, Protocol), u"proto must be a Protocol") @@ -625,7 +625,7 @@ def identical(a, b): @as_var("vector?") def vector_QMARK_(a): - return true if rt.satisfies_QMARK_(rt.IVector.deref(), a) else false + return true if rt._satisfies_QMARK_(rt.IVector.deref(), a) else false @returns(bool) @as_var("eq") From eed57f857c601334ac22b4a5481eeb63561c1680 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 14:14:08 +0100 Subject: [PATCH 106/349] Add :signatures to satisfies? and instance?. --- pixie/stdlib.pxi | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1853fe83..773f8c8c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -167,7 +167,8 @@ (def instance? (fn ^{:doc "Checks if x is an instance of t. When t is seqable, checks if x is an instance of - any of the types contained therein."} + any of the types contained therein." + :signatures [[t x]]} instance? [t x] (if (-satisfies? ISeqable t) (let [ts (seq t)] @@ -179,7 +180,8 @@ (def satisfies? (fn ^{:doc "Checks if x satisfies the protocol p. When p is seqable, checks if x satisfies all of - the protocols contained therein."} + the protocols contained therein." + :signatures [[t x]]} satisfies? [p x] (if (-satisfies? ISeqable p) (let [ps (seq p)] From 67d8641eefd5a0c26d01dc31e00abab945dc74c9 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Wed, 25 Mar 2015 14:22:32 +0100 Subject: [PATCH 107/349] Add tests for satisfies? and instance?. --- tests/pixie/tests/test-stdlib.pxi | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 3f23d9db..3e9b50a4 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -448,3 +448,30 @@ (t/assert= (f 3) :large) (t/assert= (f 4) :large) (t/assert= (f 9) :toolarge))) + +(t/deftest test-instance? + (t/assert= (instance? Keyword :a) true) + (t/assert= (instance? Keyword 'a) false) + (t/assert= (instance? [Symbol Keyword] :a) true) + (t/assert= (instance? [Symbol Keyword] 'a) true) + (t/assert= (instance? [Symbol Keyword] 42) false) + (t/assert= (instance? [] :x) false) + (t/assert-throws? RuntimeException + "c must be a type" + (instance? :not-a-type 123)) + (t/assert-throws? RuntimeException + "c must be a type" + (instance? [Keyword :also-not-a-type] 123))) + +(t/deftest test-satisfies? + (t/assert= (satisfies? IIndexed [1 2]) true) + (t/assert= (satisfies? IIndexed '(1 2)) false) + (t/assert= (satisfies? [] :xyz) true) + (t/assert= (satisfies? [ILookup IIndexed] [1 2]) true) + (t/assert= (satisfies? [ILookup IIndexed] {1 2}) false) + (t/assert-throws? RuntimeException + "proto must be a Protocol" + (satisfies? :not-a-proto 123)) + (t/assert-throws? RuntimeException + "proto must be a Protocol" + (satisfies? [IIndexed :also-not-a-proto] [1 2]))) From 2acfbdbedd72d4d31b939968e8be12d1765bf92f Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 25 Mar 2015 16:20:24 -0600 Subject: [PATCH 108/349] fix some ffi bugs --- pixie/vm/libs/ffi.py | 19 ++++++++++++++----- pixie/vm/object.py | 10 ++++++++++ pixie/vm/threads.py | 4 ++-- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 1a30a535..0d346472 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -394,8 +394,9 @@ def ffi_set_value(self, ptr, val): vpnt = rffi.cast(rffi.VOIDPP, ptr) vpnt[0] = rffi.cast(rffi.VOIDP, val.raw_data()) else: - print val - affirm(False, u"Cannot encode this type") + frm_name = rt.name(rt.str(val.type())) + to_name = rt.name(rt.str(self)) + affirm(False, u"Cannot encode " + frm_name + u" as " + to_name) def ffi_size(self): @@ -445,7 +446,13 @@ def ffi_get_value(self, ptr): def ffi_set_value(self, ptr, val): pnt = rffi.cast(rffi.VOIDPP, ptr) - if isinstance(val, Buffer): + if isinstance(val, String): + pnt = rffi.cast(rffi.CCHARPP, ptr) + utf8 = unicode_to_utf8(rt.name(val)) + raw = rffi.str2charp(utf8) + pnt[0] = raw + return CCharPToken(raw) + elif isinstance(val, Buffer): pnt[0] = val.buffer() elif isinstance(val, VoidP): pnt[0] = val.raw_data() @@ -454,8 +461,10 @@ def ffi_set_value(self, ptr, val): elif isinstance(val, CStruct): pnt[0] = rffi.cast(rffi.VOIDP, val.raw_data()) else: - print val - affirm(False, u"Cannot encode this type") + frm_name = rt.name(rt.str(val.type())) + to_name = rt.name(rt.str(self)) + affirm(False, u"Cannot encode " + frm_name + u" as " + to_name) + def ffi_size(self): return rffi.sizeof(rffi.VOIDP) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 2abf674e..32bdd199 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -151,6 +151,16 @@ def runtime_error(msg): import pixie.vm.rt as rt raise WrappedException(RuntimeException(rt.wrap(msg))) +def safe_invoke(f, args): + try: + f.invoke(args) + except Exception as ex: + if isinstance(ex, WrappedException): + print "UNSAFE EXCEPTION", ex._ex.__repr__() + else: + print "UNSAFE EXCEPTION", ex + return None + class ErrorInfo(Object): _type = Type(u"pixie.stdlib.ErrorInfo") def type(self): diff --git a/pixie/vm/threads.py b/pixie/vm/threads.py index d34b47b8..5140608b 100644 --- a/pixie/vm/threads.py +++ b/pixie/vm/threads.py @@ -1,4 +1,4 @@ -from pixie.vm.object import Object, Type +from pixie.vm.object import Object, Type, safe_invoke from pixie.vm.primitives import true import rpython.rlib.rthread as rthread from pixie.vm.primitives import nil @@ -42,7 +42,7 @@ def bootstrap(): rthread.gc_thread_start() fn = bootstrapper.fn() bootstrapper.release() - fn.invoke([]) + safe_invoke(fn, []) rthread.gc_thread_die() bootstrapper = Bootstrapper() From 4059f4ca1988ee924d5f41d6c0f352b169ab1b68 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 26 Mar 2015 12:06:09 +0000 Subject: [PATCH 109/349] properly infer functions that return char* on platforms with unsigned chars --- pixie/ffi-infer.pxi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index b2db256b..e30a2e0f 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -97,8 +97,10 @@ return 0; (defmethod edn-to-ctype :pointer [{:keys [of-type] :as ptr} in-struct?] + (println ptr in-struct?) (cond - (and (= of-type {:signed? true :size 1 :type :int}) + (and (= (:size of-type) 1) + (= (:type of-type) :int) (not in-struct?)) 'pixie.stdlib/CCharP (= (:type of-type) :function) (callback-type of-type in-struct?) :else 'pixie.stdlib/CVoidP)) From 1d212836e8c3bd29e04944f2d6a6ce9c3b18d896 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 26 Mar 2015 12:08:03 +0000 Subject: [PATCH 110/349] remove debug line --- pixie/ffi-infer.pxi | 1 - 1 file changed, 1 deletion(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index e30a2e0f..5e3b086f 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -97,7 +97,6 @@ return 0; (defmethod edn-to-ctype :pointer [{:keys [of-type] :as ptr} in-struct?] - (println ptr in-struct?) (cond (and (= (:size of-type) 1) (= (:type of-type) :int) From 1838d80528c9cad6dcc1f09424dc5e506e673190 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 26 Mar 2015 17:11:27 +0000 Subject: [PATCH 111/349] add ISeekableStream protocol --- pixie/io-blocking.pxi | 51 +++++++++++++++++++++-------------- pixie/io.pxi | 7 +++++ pixie/streams.pxi | 5 ++++ tests/pixie/tests/test-io.pxi | 11 ++++++++ 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 5dd57346..f2ffb41a 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -3,6 +3,9 @@ (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) +(def fseek (ffi-fn libc "fseek" [CVoidP CInt CInt] CInt)) +(def ftell (ffi-fn libc "ftell" [CVoidP] CInt)) +(def -rewind (ffi-fn libc "rewind" [CVoidP] CVoidP)) (def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) (def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) (def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) @@ -15,6 +18,18 @@ (def DEFAULT-BUFFER-SIZE 1024) +(defn default-stream-reducer [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc))))) + (deftype FileStream [fp] IInputStream (read [this buffer len] @@ -25,21 +40,17 @@ read-count)) (read-byte [this] (fgetc buffer)) + ISeekableStream + (seek [this pos] + (fseek fp pos 0)) + (rewind [this] + (-rewind fp)) IDisposable (-dispose! [this] (fclose fp)) IReduce (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) + (default-stream-reducer this f init))) (defn open-read {:doc "Open a file for reading, returning a IInputStream" @@ -109,6 +120,15 @@ (dispose! c) result)) +(defn slurp-stream [stream] + (let [c stream + result (transduce + (map char) + string-builder + c)] + (dispose! c) + result)) + (deftype ProcessInputStream [fp] IInputStream (read [this buffer len] @@ -124,16 +144,7 @@ (pclose fp)) IReduce (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) + (default-stream-reducer this f init))) (defn popen-read diff --git a/pixie/io.pxi b/pixie/io.pxi index 045e14b5..6dfed2ff 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -44,6 +44,13 @@ (set-field! this :offset (+ offset read-count)) (set-buffer-count! buffer read-count) read-count)) + ISeekableStream + (position [this] + offset) + (rewind [this] + (set-field! this :offset 0)) + (seek [this pos] + (set-field! this :offset pos)) IDisposable (-dispose! [this] (dispose! uvbuf) diff --git a/pixie/streams.pxi b/pixie/streams.pxi index 05b4ad44..b39fa4f3 100644 --- a/pixie/streams.pxi +++ b/pixie/streams.pxi @@ -11,3 +11,8 @@ (defprotocol IByteOutputStream (write-byte [this byte])) + +(defprotocol ISeekableStream + (position [this]) + (seek [this position]) + (rewind [this])) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 09de53e3..c93e3dd9 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -1,5 +1,6 @@ (ns pixie.tests.test-io (require pixie.test :as t) + (require pixie.streams :as st :refer :all) (require pixie.io :as io)) (t/deftest test-file-reduction @@ -24,6 +25,16 @@ s (io/line-seq f)] (t/assert= (last s) "Second line."))) +(t/deftest test-seek + (let [f (io/open-read "tests/pixie/tests/test-io.txt")] + (io/read-line f) + (t/assert= (io/read-line f) "Second line.") + (io/rewind f) + (io/read-line f) + (t/assert= (io/read-line f) "Second line.") + (io/seek f (- (position f) 6)) + (t/assert= (io/read-line f) "line."))) + (t/deftest test-slurp-spit (let [val (vec (range 1280))] (io/spit "test.tmp" val) From eca7f7dc56ab86f9729ceb6162b4d2768f54bd7c Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Fri, 27 Mar 2015 11:26:49 +0100 Subject: [PATCH 112/349] Implement macroexpand-1. --- pixie/stdlib.pxi | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 773f8c8c..6276dd5d 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2311,6 +2311,24 @@ Expands to calls to `extend-type`." ([f col] (transduce (map f) conj col))) +(defn macroexpand-1 [form] + {:doc "If form is a macro call, returns the expanded form. + + Does nothing if not a macro call." + :signatures [[form]] + :examples [["(macroexpand-1 '(when condition this and-this))" + nil `(if condition (do this and-this))] + ["(macroexpand-1 ())" nil ()] + ["(macroexpand-1 [1 2])" nil [1 2]]]} + (if (or (not (list? form)) + (= () form)) + form + (let [[sym & args] form + fvar (resolve sym)] + (if (and fvar (macro? @fvar)) + (apply @fvar args) + form)))) + (def *1) (def *2) (def *3) From 2491d2b43dd869f4066ff5b0da57c2da57234479 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Sat, 28 Mar 2015 15:45:25 -0600 Subject: [PATCH 113/349] added basic utf8 encoder-decoder --- pixie/io.pxi | 18 ++++++++ pixie/streams/utf8.pxi | 55 +++++++++++++++++++++++++ tests/pixie/tests/streams/test-utf8.pxi | 17 ++++++++ 3 files changed, 90 insertions(+) create mode 100644 pixie/streams/utf8.pxi create mode 100644 tests/pixie/tests/streams/test-utf8.pxi diff --git a/pixie/io.pxi b/pixie/io.pxi index 6dfed2ff..e1d43b10 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -131,9 +131,27 @@ (set-buffer-count! buffer idx) (write downstream buffer))) +(deftype BufferedInputStream [upstream idx buffer] + IByteInputStream + (read-byte [this] + (when (= idx (count buffer)) + (set-field! this :idx 0) + (read upstream buffer (buffer-capacity buffer))) + (let [val (nth buffer idx)] + (set-field! this :idx (inc idx)) + val)) + IDisposable + (-dispose! [this] + (dispose! upstream) + (dispose! buffer))) + (defn buffered-output-stream [downstream size] (->BufferedOutputStream downstream 0 (buffer size))) +(defn buffered-input-stream [upstream size] + (let [b (buffer size)] + (set-buffer-count! b size) + (->BufferedInputStream upstream size b))) (defn throw-on-error [result] (when (neg? result) diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi new file mode 100644 index 00000000..baf8bd85 --- /dev/null +++ b/pixie/streams/utf8.pxi @@ -0,0 +1,55 @@ +(ns pixie.streams.utf8 + (require pixie.streams :refer :all)) + +(defprotocol IUTF8OutputStream + (write-char [this char])) + +(defprotocol IUTF8InputStream + (read-char [this])) + +(deftype UTF8OutputStream [out] + IUTF8OutputStream + (write-char [this ch] + (let [ch (int ch)] + (cond + (<= ch 0x7F) (write-byte out ch) + (<= ch 0x7FF) (do (write-byte out (bit-or 0xC0 (bit-shift-right ch 6))) + (write-byte out (bit-or 0x80 (bit-and ch 0x3F)))) + (<= ch 0xFFFF) (do (write-byte out (bit-or 0xE0 (bit-shift-right ch 12))) + (write-byte out (bit-or 0x80 (bit-and (bit-shift-right ch 6) 0x3F))) + (write-byte out (bit-or 0x80 (bit-and ch 0x3F)))) + (<= ch 0x1FFFFF) (do (write-byte out (bit-or 0xE0 (bit-shift-right ch 18))) + (write-byte out (bit-or 0x80 (bit-and (bit-shift-right ch 12) 0x3F))) + (write-byte out (bit-or 0x80 (bit-and (bit-shift-right ch 6) 0x3F))) + (write-byte out (bit-or 0x80 (bit-and ch 0x3F))) )))) + IDisposable + (-dispose! [this] + (dispose! out))) + + +(deftype UTF8InputStream [in] + IUTF8InputStream + (read-char [this] + (let [ch (int (read-byte in)) + [n bytes] (cond + (>= 0x7F ch) [ch 1] + (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2] + (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3] + (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4] + :else (assert false (str "Got bad code " ch)))] + (loop [i (dec bytes) + n n] + (if (pos? i) + (recur (dec i) + (bit-or (bit-shift-left n 6) + (bit-and (read-byte in) 0x3F))) + (char n))))) + IDisposable + (-dispose! [this] + (dispose! in))) + +(defn utf8-input-stream [i] + (->UTF8InputStream i)) + +(defn utf8-output-stream [o] + (->UTF8OutputStream o)) diff --git a/tests/pixie/tests/streams/test-utf8.pxi b/tests/pixie/tests/streams/test-utf8.pxi new file mode 100644 index 00000000..ede7a1c5 --- /dev/null +++ b/tests/pixie/tests/streams/test-utf8.pxi @@ -0,0 +1,17 @@ +(ns pixie.streams.test-utf8 + (require pixie.streams.utf8 :refer :all) + (require pixie.io :as io) + (require pixie.test :refer :all)) + + +(deftest test-writing-ints + (using [os (-> (io/open-write "/tmp/pixie-utf-test.txt") + (io/buffered-output-stream 1024) + utf8-output-stream)] + (dotimes [x 32000] + (write-char os (char x)))) + (using [is (-> (io/open-read "/tmp/pixie-utf-test.txt") + (io/buffered-input-stream 1024) + utf8-input-stream)] + (dotimes [x 32000] + (assert= x (int (read-char is)))))) From 5c5732b0591190d0de220f969372c9d220b80e66 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sun, 29 Mar 2015 16:40:43 +0100 Subject: [PATCH 114/349] Implement -seq for sets the same way as maps Sets were using iterators instead of just building a list (which were mentioned should be removed in #242), and I guess some of the iterator code doesn't work properly for maps, because executing `(seq #{4 7})` causes a segfault without this patch. I'm not really familar with the implementation of iterators over maps, but this is sort of an interesting bug because I've only been able to reproduce it with sets that have #{4 7} as a subset. --- pixie/stdlib.pxi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6276dd5d..149f7009 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -959,7 +959,9 @@ If further arguments are passed, invokes the method named by symbol, passing the (fn [v] (transduce cat unordered-hash-reducing-fn v))) -(extend -seq PersistentHashSet (fn [self] (seq (iterator self)))) +(extend -seq PersistentHashSet + (fn [s] + (reduce conj nil s))) (extend -str PersistentHashSet (fn [s] From f140b486cdd85ee47ce8895cf2be0778fcd31950 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 20 Mar 2015 10:55:41 +0000 Subject: [PATCH 115/349] Add basic functions for dealing with environment --- pixie/stdlib.pxi | 10 ++++++++ pixie/vm/libs/env.py | 55 ++++++++++++++++++++++++++++++++++++++++++++ pixie/vm/rt.py | 1 + pixie/vm/stdlib.py | 1 - 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 pixie/vm/libs/env.py diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6276dd5d..1db82f15 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2340,3 +2340,13 @@ Expands to calls to `extend-type`." (def *e) (defn -set-*e [e] (def *e e)) + +(extend -str Environment + (fn [v] + (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] + (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + +(extend -repr Environment + (fn [v] + (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] + (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) diff --git a/pixie/vm/libs/env.py b/pixie/vm/libs/env.py new file mode 100644 index 00000000..25bfb7ca --- /dev/null +++ b/pixie/vm/libs/env.py @@ -0,0 +1,55 @@ +from pixie.vm.code import as_var +from pixie.vm.object import Object, Type, runtime_error +from pixie.vm.primitives import nil +from pixie.vm.string import String +import pixie.vm.stdlib as proto +from pixie.vm.code import extend, as_var +import pixie.vm.rt as rt +import os + +class Environment(Object): + _type = Type(u"pixie.stdlib.Environment") + + def type(self): + return Environment._type + + def val_at(self, key, not_found): + if not isinstance(key, String): + runtime_error(u"Environment variables are strings ") + key_str = str(rt.name(key)) + try: + var = os.environ[key_str] + return rt.wrap(var) + except KeyError: + return not_found + + # TODO: Implement me. + # def dissoc(self): + # def asssoc(self): + + def reduce_vars(self, f, init): + for k, v in os.environ.items(): + init = f.invoke([init, rt.map_entry(rt.wrap(k), rt.wrap(v))]) + if rt.reduced_QMARK_(init): + return init + return init + + +@extend(proto._val_at, Environment) +def _val_at(self, key, not_found): + assert isinstance(self, Environment) + v = self.val_at(key, not_found) + return v + +@extend(proto._reduce, Environment) +def _reduce(self, f, init): + assert isinstance(self, Environment) + val = self.reduce_vars(f, init) + if rt.reduced_QMARK_(val): + return rt.deref(val) + + return val + +@as_var("pixie.stdlib", "env") +def _env(): + return Environment() diff --git a/pixie/vm/rt.py b/pixie/vm/rt.py index 794a4c3b..37fa0676 100644 --- a/pixie/vm/rt.py +++ b/pixie/vm/rt.py @@ -65,6 +65,7 @@ def wrapper(*args): import pixie.vm.map_entry import pixie.vm.libs.platform import pixie.vm.libs.ffi + import pixie.vm.libs.env import pixie.vm.symbol import pixie.vm.libs.path import pixie.vm.libs.string diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 6741063b..78eb48bd 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -864,4 +864,3 @@ def _set_current_var_frames(self, frames): Sets the current var frames. Frames should be a cons list of hashmaps containing mappings of vars to dynamic values. Setting this value to anything but this data format will cause undefined errors.""" code._dynamic_vars.set_current_frames(frames) - From 8071349815897926ee73f0e8618815f3fc6752c5 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 30 Mar 2015 06:53:23 -0600 Subject: [PATCH 116/349] added error handling to UTF8 streams --- benchmarks/deftype_fields.pxi | 7 ++++-- pixie/math.pxi | 6 ++++- pixie/streams/utf8.pxi | 42 +++++++++++++++++++++++------------ 3 files changed, 38 insertions(+), 17 deletions(-) diff --git a/benchmarks/deftype_fields.pxi b/benchmarks/deftype_fields.pxi index fbee851b..caf84fb8 100644 --- a/benchmarks/deftype_fields.pxi +++ b/benchmarks/deftype_fields.pxi @@ -11,6 +11,9 @@ b)) -(def adder (->Adder 1 0)) -(dotimes [x (* 1024 1024 1024)] + +(def adder (->Adder 1.0 0)) +(println "Starting....") +(dotimes [x (* 1024 1024 1024 20)] (assert (= (inc x) (add-them adder)))) +(println "Ending....") diff --git a/pixie/math.pxi b/pixie/math.pxi index 7c16889d..4b952398 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -23,4 +23,8 @@ (i/defcfn ceil) (i/defcfn fabs) (i/defcfn floor) - (i/defcfn fmod)) + (i/defcfn fmod) + + (i/defconst M_PI)) + +(def pi M_PI) diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi index baf8bd85..055733df 100644 --- a/pixie/streams/utf8.pxi +++ b/pixie/streams/utf8.pxi @@ -2,10 +2,10 @@ (require pixie.streams :refer :all)) (defprotocol IUTF8OutputStream - (write-char [this char])) + (write-char [this char] "Write a single character to the UTF8 stream")) (defprotocol IUTF8InputStream - (read-char [this])) + (read-char [this] "Read a single character from the UTF8 stream")) (deftype UTF8OutputStream [out] IUTF8OutputStream @@ -21,35 +21,49 @@ (<= ch 0x1FFFFF) (do (write-byte out (bit-or 0xE0 (bit-shift-right ch 18))) (write-byte out (bit-or 0x80 (bit-and (bit-shift-right ch 12) 0x3F))) (write-byte out (bit-or 0x80 (bit-and (bit-shift-right ch 6) 0x3F))) - (write-byte out (bit-or 0x80 (bit-and ch 0x3F))) )))) + (write-byte out (bit-or 0x80 (bit-and ch 0x3F)))) + :else (assert false (str "Cannot encode a UTF8 character of code " ch))))) IDisposable (-dispose! [this] (dispose! out))) -(deftype UTF8InputStream [in] +(deftype UTF8InputStream [in bad-char] IUTF8InputStream (read-char [this] (let [ch (int (read-byte in)) - [n bytes] (cond - (>= 0x7F ch) [ch 1] - (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2] - (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3] - (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4] - :else (assert false (str "Got bad code " ch)))] + [n bytes error?] (cond + (>= 0x7F ch) [ch 1] + (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2 false] + (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3 false] + (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4 false] + (= 0xF8 (bit-and ch 0xF8)) [(bit-and ch 3) 5 true] + (= 0xFC (bit-and ch 0xFE)) [(bit-and ch 1) 6 true] + :else [n 1 true])] (loop [i (dec bytes) n n] (if (pos? i) (recur (dec i) (bit-or (bit-shift-left n 6) (bit-and (read-byte in) 0x3F))) - (char n))))) + (if error? + (if bad-char + bad-char + (throw (str "Invalid UTF8 character decoded: " n))) + (char n)))))) IDisposable (-dispose! [this] (dispose! in))) -(defn utf8-input-stream [i] - (->UTF8InputStream i)) +(defn utf8-input-stream + "Creates a UTF8 decoder that reads characters from the given IByteInputStream. If a bad character is found + an error will be thrown, unless an optional bad-character marker character is provided." + ([i] + (->UTF8InputStream i nil)) + ([i bad-char] + (->UTF8InputStream i bad-char))) -(defn utf8-output-stream [o] +(defn utf8-output-stream + "Creates a UTF8 encoder that writes characters to the given IByteOutputStream." + [o] (->UTF8OutputStream o)) From 1eb6e0ae00f1ad42290dcbe8c0b1fdb8911933ff Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 30 Mar 2015 06:56:03 -0600 Subject: [PATCH 117/349] remove some accidentally commited files --- benchmarks/deftype_fields.pxi | 7 ++----- pixie/math.pxi | 6 +----- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/benchmarks/deftype_fields.pxi b/benchmarks/deftype_fields.pxi index caf84fb8..fbee851b 100644 --- a/benchmarks/deftype_fields.pxi +++ b/benchmarks/deftype_fields.pxi @@ -11,9 +11,6 @@ b)) - -(def adder (->Adder 1.0 0)) -(println "Starting....") -(dotimes [x (* 1024 1024 1024 20)] +(def adder (->Adder 1 0)) +(dotimes [x (* 1024 1024 1024)] (assert (= (inc x) (add-them adder)))) -(println "Ending....") diff --git a/pixie/math.pxi b/pixie/math.pxi index 4b952398..7c16889d 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -23,8 +23,4 @@ (i/defcfn ceil) (i/defcfn fabs) (i/defcfn floor) - (i/defcfn fmod) - - (i/defconst M_PI)) - -(def pi M_PI) + (i/defcfn fmod)) From 72e1bfc206cba5e4e170e50995c8d136f4bfe67c Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 30 Mar 2015 16:19:29 -0600 Subject: [PATCH 118/349] fix randomly failing tests in JIT mode --- pixie/vm/custom_types.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 05008d2a..0d6d126b 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -55,13 +55,18 @@ def set_field(self, name, val): if isinstance(old_val, AbstractMutableCell): old_val.set_mutable_cell_value(self._custom_type, self._fields, name, idx, val) else: + self._custom_type.set_mutable(name) self._fields[idx] = val return self @jit.elidable_promote() - def get_field_immutable(self, idx): + def _get_field_immutable(self, idx, rev): return self._fields[idx] + def get_field_immutable(self, idx): + tp = self._custom_type + assert isinstance(tp, CustomType) + return self._get_field_immutable(idx, tp._rev) def get_field(self, name): idx = self._custom_type.get_slot_idx(name) @@ -78,11 +83,6 @@ def get_field(self, name): else: return value - def set_field_by_idx(self, idx, val): - affirm(isinstance(idx, r_uint), u"idx must be a r_uint") - self._fields[idx] = val - return self - @as_var("create-type") def create_type(type_name, fields): From aef70b13851f15b1c719cd7a90567fd238a43a9b Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 30 Mar 2015 16:28:12 -0600 Subject: [PATCH 119/349] remove outdated failing timer test --- tests/pixie/tests/test-uv.pxi | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 tests/pixie/tests/test-uv.pxi diff --git a/tests/pixie/tests/test-uv.pxi b/tests/pixie/tests/test-uv.pxi deleted file mode 100644 index 4167955e..00000000 --- a/tests/pixie/tests/test-uv.pxi +++ /dev/null @@ -1,21 +0,0 @@ -(ns pixie.test-uv - (require pixie.uv :as uv) - (require pixie.test :as t) - (require pixie.ffi :as ffi)) - - -(t/deftest timer-tests - (let [cb (atom nil) - result (atom false) - loop (uv/uv_loop_t) - timer (uv/uv_timer_t)] - (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb - (fn [handle] - (reset! result true) - (uv/uv_timer_stop timer) - (-dispose! @cb)))) - (uv/uv_loop_init loop) - (uv/uv_timer_init loop timer) - (uv/uv_timer_start timer @cb 10 0) - (uv/uv_run loop uv/UV_RUN_ONCE) - (t/assert @result))) From 6905dfa3c826495995e16dd223c3e4b794ef9927 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 1 Apr 2015 10:44:20 +0100 Subject: [PATCH 120/349] clojure style :require --- pixie/async.pxi | 2 +- pixie/channels.pxi | 4 ++-- pixie/csp.pxi | 6 +++--- pixie/ffi-infer.pxi | 2 +- pixie/fs.pxi | 4 ++-- pixie/io-blocking.pxi | 2 +- pixie/io.pxi | 12 ++++++------ pixie/math.pxi | 2 +- pixie/repl.pxi | 6 +++--- pixie/stacklets.pxi | 4 ++-- pixie/stdlib.pxi | 19 ++++++++++++++++--- pixie/string.pxi | 2 +- pixie/test.pxi | 4 ++-- pixie/uv.pxi | 2 +- tests/pixie/tests/test-async.pxi | 6 +++--- tests/pixie/tests/test-buffers.pxi | 5 ++--- tests/pixie/tests/test-channels.pxi | 8 ++++---- 17 files changed, 51 insertions(+), 39 deletions(-) diff --git a/pixie/async.pxi b/pixie/async.pxi index 2907936a..ca7862f8 100644 --- a/pixie/async.pxi +++ b/pixie/async.pxi @@ -1,5 +1,5 @@ (ns pixie.async - (require pixie.stacklets :as st)) + (:require [pixie.stacklets :as st])) (deftype Promise [val pending-callbacks delivered?] diff --git a/pixie/channels.pxi b/pixie/channels.pxi index 1b48ecf8..c44cc060 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -1,6 +1,6 @@ (ns pixie.channels - (require pixie.stacklets :as st) - (require pixie.buffers :as b)) + (:require [pixie.stacklets :as st] + [pixie.buffers :as b])) (defprotocol ICancelable (-canceled? [this] "Determines if a request (such as a callback) that can be canceled") diff --git a/pixie/csp.pxi b/pixie/csp.pxi index b20fa08c..94ca90d9 100644 --- a/pixie/csp.pxi +++ b/pixie/csp.pxi @@ -1,7 +1,7 @@ (ns pixie.csp - (require pixie.stacklets :as st) - (require pixie.buffers :as b) - (require pixie.channels :as chans)) + (:require [pixie.stacklets :as st] + [pixie.buffers :as b] + [pixie.channels :as chans])) (def chan chans/chan) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 5e3b086f..f2074f53 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -1,5 +1,5 @@ (ns pixie.ffi-infer - (require pixie.io-blocking :as io)) + (:require [pixie.io-blocking :as io])) (defn -add-rel-path [rel] diff --git a/pixie/fs.pxi b/pixie/fs.pxi index a7745a7a..048e6f63 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -1,6 +1,6 @@ (ns pixie.fs - (require pixie.path :as path) - (require pixie.string :as string)) + (:require [pixie.path :as path] + [pixie.string :as string])) (defprotocol IFSPath diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index f2ffb41a..9b4f3943 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -1,5 +1,5 @@ (ns pixie.io-blocking - (require pixie.streams :as st :refer :all)) + (:require [pixie.streams :as st :refer :all])) (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) diff --git a/pixie/io.pxi b/pixie/io.pxi index e1d43b10..aa868411 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,10 +1,10 @@ (ns pixie.io - (require pixie.streams :as st :refer :all) - (require pixie.io-blocking :as io-blocking) - (require pixie.uv :as uv) - (require pixie.stacklets :as st) - (require pixie.ffi :as ffi) - (require pixie.ffi-infer :as ffi-infer)) + (:require [pixie.streams :as st :refer :all] + [pixie.io-blocking :as io-blocking] + [pixie.uv :as uv] + [pixie.stacklets :as st] + [pixie.ffi :as ffi] + [pixie.ffi-infer :as ffi-infer])) (defmacro defuvfsfn [nm args return] `(defn ~nm ~args diff --git a/pixie/math.pxi b/pixie/math.pxi index 7c16889d..47d45cd0 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -1,5 +1,5 @@ (ns pixie.math - (require pixie.ffi-infer :as i)) + (:require [pixie.ffi-infer :as i])) (i/with-config {:library "m" :cxx-flags ["-lm"] diff --git a/pixie/repl.pxi b/pixie/repl.pxi index d10b6a44..e8432cba 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -1,7 +1,7 @@ (ns pixie.repl - (require pixie.stacklets :as st) - (require pixie.io :as io) - (require pixie.ffi-infer :as f)) + (:require [pixie.stacklets :as st] + [pixie.io :as io] + [pixie.ffi-infer :as f])) (f/with-config {:library "edit" :includes ["editline/readline.h"]} diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index ec03ae31..c3d2b236 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -1,6 +1,6 @@ (ns pixie.stacklets - (require pixie.uv :as uv) - (require pixie.ffi :as ffi)) + (:require [pixie.uv :as uv] + [pixie.ffi :as ffi])) ;; If we don't do this, compiling this file doesn't work since the def will clear out ;; the existing value. diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a3c6c4f0..34cd0c52 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1105,9 +1105,22 @@ Creates new maps if the keys are not present." ret)))) (defmacro ns [nm & body] - `(do (in-ns ~(keyword (name nm))) - ~@body)) - + (let [bmap (reduce (fn [m b] + (update-in m [(first b)] (fnil conj []) (rest b))) + {} + body) + requires + (do + (assert (>= 1 (count (:require bmap))) + "Only one :require block can be defined per namespace") + (map (fn [r] `(require ~@r)) (first (:require bmap)))) + + old-style-requires + (map (fn [r] `(require ~@r)) + (bmap 'require))] + `(do (in-ns ~(keyword (name nm))) + ~@requires + ~@old-style-requires))) (defn symbol? [x] (identical? Symbol (type x))) diff --git a/pixie/string.pxi b/pixie/string.pxi index 36be0b86..fdbbcbb3 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -1,5 +1,5 @@ (ns pixie.string - (require pixie.string.internal :as si)) + (:require [pixie.string.internal :as si])) ; reexport native string functions (def substring si/substring) diff --git a/pixie/test.pxi b/pixie/test.pxi index 26c3927b..745efa00 100644 --- a/pixie/test.pxi +++ b/pixie/test.pxi @@ -1,6 +1,6 @@ (ns pixie.test - (require pixie.string :as s) - (require pixie.fs :as fs)) + (:require [pixie.string :as s] + [pixie.fs :as fs])) (def tests (atom {})) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index d984d52a..76417f47 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -1,5 +1,5 @@ (ns pixie.uv - (require pixie.ffi-infer :as f)) + (:require [pixie.ffi-infer :as f])) (f/with-config {:library "uv" :includes ["uv.h"]} diff --git a/tests/pixie/tests/test-async.pxi b/tests/pixie/tests/test-async.pxi index d5764af6..19fa3731 100644 --- a/tests/pixie/tests/test-async.pxi +++ b/tests/pixie/tests/test-async.pxi @@ -1,7 +1,7 @@ (ns pixie.tests.test-async - (require pixie.stacklets :as st) - (require pixie.async :as async :refer :all) - (require pixie.test :as t :refer :all)) + (:require [pixie.stacklets :as st] + [pixie.async :as async :refer :all] + [pixie.test :as t :refer :all])) (deftest test-future-deref diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi index 92a99c94..1afd5326 100644 --- a/tests/pixie/tests/test-buffers.pxi +++ b/tests/pixie/tests/test-buffers.pxi @@ -1,7 +1,6 @@ (ns pixie.tests.test-buffers - (require pixie.test :refer :all) - (require pixie.buffers :refer :all)) - + (:require [pixie.test :refer :all] + [pixie.buffers :refer :all])) (deftest test-adding-and-removing-from-buffer (let [buffer (ring-buffer 10)] diff --git a/tests/pixie/tests/test-channels.pxi b/tests/pixie/tests/test-channels.pxi index 9f35fe61..0cdebfd0 100644 --- a/tests/pixie/tests/test-channels.pxi +++ b/tests/pixie/tests/test-channels.pxi @@ -1,8 +1,8 @@ (ns pixie.tests.test-channels - (require pixie.test :refer :all) - (require pixie.channels :refer :all) - (require pixie.async :refer :all) - (require pixie.stacklets :as st)) + (:require [pixie.test :refer :all] + [pixie.channels :refer :all] + [pixie.async :refer :all] + [pixie.stacklets :as st])) (deftest simple-read-and-write From 0d6e1aef015a26b972ff99031ba87328b8c8a971 Mon Sep 17 00:00:00 2001 From: Peter Monks Date: Wed, 1 Apr 2015 17:10:10 -0700 Subject: [PATCH 121/349] Added UTF8 test Added temp file generated from tests to .gitignore --- .gitignore | 1 + tests/pixie/tests/test-utf8.pxi | 9 +++++++++ 2 files changed, 10 insertions(+) create mode 100644 tests/pixie/tests/test-utf8.pxi diff --git a/.gitignore b/.gitignore index e7206d68..43e35ec3 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ pixie-vm lib include pixie/*.pxic +test.tmp diff --git a/tests/pixie/tests/test-utf8.pxi b/tests/pixie/tests/test-utf8.pxi new file mode 100644 index 00000000..1c52ef01 --- /dev/null +++ b/tests/pixie/tests/test-utf8.pxi @@ -0,0 +1,9 @@ +(ns pixie.test.test-utf8 + (require pixie.test :as t)) + +(t/deftest test-utf8-string-val + (t/assert= "🍺=👍" "🍺=👍")) + +(t/deftest test-utf8-var-name + (let [🍺 "🍺=👍"] + (t/assert= 🍺 "🍺=👍"))) From 7ba81e3a1299e12bccbe1dacf088e80db40f38d0 Mon Sep 17 00:00:00 2001 From: Michael Trotter Date: Thu, 2 Apr 2015 01:18:37 -0600 Subject: [PATCH 122/349] minor grammer fix in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cda23c1..658d8c59 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Pixie now comes with a build tool called [dust](https://github.com/pixie-lang/du ### So this is written in Python? -It's actually written in the RPython, the same language PyPy is written in. `make build_with_jit` will compile Pixie using the PyPy toolchain. After some time, it will produce an executable called `pixie-vm`. This executable is a full blown native interpreter with a JIT, GC, etc. So yes, the guts are written in RPython, just like the guts of most lisp interpreters are written in C. At runtime the only thing that is interpreted is the Pixie bytecode, that is until the JIT kicks in... +It's actually written in RPython, the same language PyPy is written in. `make build_with_jit` will compile Pixie using the PyPy toolchain. After some time, it will produce an executable called `pixie-vm`. This executable is a full blown native interpreter with a JIT, GC, etc. So yes, the guts are written in RPython, just like the guts of most lisp interpreters are written in C. At runtime the only thing that is interpreted is the Pixie bytecode, that is until the JIT kicks in... ### What's this bit about "magical powers"? From b20575edc65d67c8195d226460ec376f72141eb0 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sat, 4 Apr 2015 21:47:14 +0200 Subject: [PATCH 123/349] Fix some docstrings being in the wrong position. --- pixie/stdlib.pxi | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 34cd0c52..7df603d9 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1598,21 +1598,23 @@ The new value is thus `(apply f current-value-of-atom args)`." (lazy-seq (step pred coll))))) ;; TODO: use a transient map in the future -(defn group-by [f coll] +(defn group-by {:doc "Groups the collection into a map keyed by the result of applying f on each element. The value at each key is a vector of elements in order of appearance." :examples [["(group-by even? [1 2 3 4 5])" nil {false [1 3 5] true [2 4]}] ["(group-by (partial apply +) [[1 2 3][2 4][1 2]]" nil {6 [[1 2 3] [2 4]] 3 [[1 2]]}]] :signatures [[f coll]] :added "0.1"} + [f coll] (reduce (fn [res elem] (update-in res [(f elem)] (fnil conj []) elem)) {} coll)) ;; TODO: use a transient map in the future -(defn frequencies [coll] +(defn frequencies {:doc "Returns a map with distinct elements as keys and the number of occurences as values" :added "0.1"} + [coll] (reduce (fn [res elem] (update-in res [elem] (fnil inc 0))) {} @@ -1634,17 +1636,18 @@ not enough elements were present." (lazy-seq (cons (take n s) (partition n step (drop step s))))))) -(defn partitionf [f coll] +(defn partitionf {:doc "A generalized version of partition. Instead of taking a constant number of elements, this function calls f with the remaining collection to determine how many elements to take." :examples [["(partitionf first [1 :a, 2 :a b, 3 :a :b :c])" nil ((1 :a) (2 :a :b) (3 :a :b :c))]]} + [f coll] (when-let [s (seq coll)] (lazy-seq (let [n (f s)] (cons (take n s) - (partitionf f (drop n coll))))))) + (partitionf f (drop n s))))))) (defn destructure [binding expr] (cond @@ -2293,7 +2296,7 @@ Expands to calls to `extend-type`." (mapcat walk (children node))))))] (walk root))) -(defn flatten [x] +(defn flatten ; TODO: laziness? {:doc "Takes any nested combination of ISeqable things, and return their contents as a single, flat sequence. @@ -2302,15 +2305,17 @@ Expands to calls to `extend-type`." value as its only element." :examples [["(flatten [[1 2 [3 4] [5 6]] 7])" nil [1 2 3 4 5 6 7]] ["(flatten :this)" nil [:this]]]} + [x] (if (not (satisfies? ISeqable x)) [x] (transduce (comp (map flatten) cat) conj [] (seq x)))) -(defn juxt [& fns] +(defn juxt {:doc "Returns a function that applies all fns to its arguments, and returns a vector of the results." :examples [["((juxt + - *) 2 3)" nil [5 -1 6]]]} + [& fns] (fn [& args] (mapv #(apply % args) fns))) @@ -2326,7 +2331,7 @@ Expands to calls to `extend-type`." ([f col] (transduce (map f) conj col))) -(defn macroexpand-1 [form] +(defn macroexpand-1 {:doc "If form is a macro call, returns the expanded form. Does nothing if not a macro call." @@ -2335,6 +2340,7 @@ Expands to calls to `extend-type`." nil `(if condition (do this and-this))] ["(macroexpand-1 ())" nil ()] ["(macroexpand-1 [1 2])" nil [1 2]]]} + [form] (if (or (not (list? form)) (= () form)) form From 1066bcaaa5df4a50f80ccf0bd03b7ec970cff2f4 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sat, 4 Apr 2015 21:54:09 +0200 Subject: [PATCH 124/349] Fix a few failing tests. --- pixie/stdlib.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 7df603d9..95809f9f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1601,7 +1601,7 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn group-by {:doc "Groups the collection into a map keyed by the result of applying f on each element. The value at each key is a vector of elements in order of appearance." :examples [["(group-by even? [1 2 3 4 5])" nil {false [1 3 5] true [2 4]}] - ["(group-by (partial apply +) [[1 2 3][2 4][1 2]]" nil {6 [[1 2 3] [2 4]] 3 [[1 2]]}]] + ["(group-by (partial apply +) [[1 2 3] [2 4] [1 2]])" nil {6 [[1 2 3] [2 4]] 3 [[1 2]]}]] :signatures [[f coll]] :added "0.1"} [f coll] @@ -1640,8 +1640,8 @@ not enough elements were present." {:doc "A generalized version of partition. Instead of taking a constant number of elements, this function calls f with the remaining collection to determine how many elements to take." - :examples [["(partitionf first [1 :a, 2 :a b, 3 :a :b :c])" - nil ((1 :a) (2 :a :b) (3 :a :b :c))]]} + :examples [["(partitionf first [2 :a, 3 :a :b, 4 :a :b :c])" + nil ((2 :a) (3 :a :b) (4 :a :b :c))]]} [f coll] (when-let [s (seq coll)] (lazy-seq @@ -2337,7 +2337,7 @@ Expands to calls to `extend-type`." Does nothing if not a macro call." :signatures [[form]] :examples [["(macroexpand-1 '(when condition this and-this))" - nil `(if condition (do this and-this))] + nil (if condition (do this and-this))] ["(macroexpand-1 ())" nil ()] ["(macroexpand-1 [1 2])" nil [1 2]]]} [form] From 073c9a30126de70bbb5581cd4dac0b79065f5dd3 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sat, 4 Apr 2015 22:09:50 +0200 Subject: [PATCH 125/349] Fix some docstring formatting issues. --- pixie/stdlib.pxi | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 95809f9f..5e66e8e2 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2206,11 +2206,11 @@ Expands to calls to `extend-type`." ;; TODO: implement :>> like in Clojure? (defmacro condp "Takes a binary predicate, an expression and a number of two-form clauses. - Calls the predicate on the first value of each clause and the expression. - If the result is truthy returns the second value of the clause. +Calls the predicate on the first value of each clause and the expression. +If the result is truthy returns the second value of the clause. - If the number of arguments is odd and no clause matches, the last argument is returned. - If the number of arguments is even and no clause matches, throws an exception." +If the number of arguments is odd and no clause matches, the last argument is returned. +If the number of arguments is even and no clause matches, throws an exception." [pred-form expr & clauses] (let [x (gensym 'expr), pred (gensym 'pred)] `(let [~x ~expr, ~pred ~pred-form] @@ -2224,13 +2224,13 @@ Expands to calls to `extend-type`." (defmacro case "Takes an expression and a number of two-form clauses. - Checks for each clause if the first part is equal to the expression. - If yes, returns the value of the second part. +Checks for each clause if the first part is equal to the expression. +If yes, returns the value of the second part. - The first part of each clause can also be a set. If that is the case, the clause matches when the result of the expression is in the set. +The first part of each clause can also be a set. If that is the case, the clause matches when the result of the expression is in the set. - If the number of arguments is odd and no clause matches, the last argument is returned. - If the number of arguments is even and no clause matches, throws an exception." +If the number of arguments is odd and no clause matches, the last argument is returned. +If the number of arguments is even and no clause matches, throws an exception." [expr & args] `(condp #(if (set? %1) (%1 %2) (= %1 %2)) ~expr ~@args)) @@ -2285,9 +2285,9 @@ Expands to calls to `extend-type`." (defn tree-seq "Returns a lazy sequence of the nodes in a tree via a depth-first walk. - branch? - fn of node that should true when node has children - children - fn of node that should return a sequence of children (called if branch? true) - root - root node of the tree" +branch? - fn of node that should true when node has children +children - fn of node that should return a sequence of children (called if branch? true) +root - root node of the tree" [branch? children root] (let [walk (fn walk [node] (lazy-seq @@ -2298,11 +2298,9 @@ Expands to calls to `extend-type`." (defn flatten ; TODO: laziness? - {:doc "Takes any nested combination of ISeqable things, and return their contents - as a single, flat sequence. + {:doc "Takes any nested combination of ISeqable things, and return their contents as a single, flat sequence. - Calling this function on something that is not ISeqable returns a seq with that - value as its only element." +Calling this function on something that is not ISeqable returns a seq with that value as its only element." :examples [["(flatten [[1 2 [3 4] [5 6]] 7])" nil [1 2 3 4 5 6 7]] ["(flatten :this)" nil [:this]]]} [x] @@ -2312,8 +2310,7 @@ Expands to calls to `extend-type`." (seq x)))) (defn juxt - {:doc "Returns a function that applies all fns to its arguments, - and returns a vector of the results." + {:doc "Returns a function that applies all fns to its arguments, and returns a vector of the results." :examples [["((juxt + - *) 2 3)" nil [5 -1 6]]]} [& fns] (fn [& args] @@ -2332,9 +2329,7 @@ Expands to calls to `extend-type`." (transduce (map f) conj col))) (defn macroexpand-1 - {:doc "If form is a macro call, returns the expanded form. - - Does nothing if not a macro call." + {:doc "If form is a macro call, returns the expanded form. Does nothing if not a macro call." :signatures [[form]] :examples [["(macroexpand-1 '(when condition this and-this))" nil (if condition (do this and-this))] From 8e9549e7e0f85b9d87a7096bb0beb3aafd4849de Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sat, 4 Apr 2015 23:13:23 +0200 Subject: [PATCH 126/349] ignore all pxics --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 43e35ec3..d2f96fde 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,5 @@ pixie-vm .idea lib include -pixie/*.pxic +*.pxic test.tmp From f97295e3324f32792b5a970bbb113e6ce5ed3f30 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Sat, 4 Apr 2015 23:41:45 +0200 Subject: [PATCH 127/349] Fix satisfies? and instance? using `and` and `or` before they are defined. --- pixie/stdlib.pxi | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 34cd0c52..0a1ea972 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -173,8 +173,9 @@ (if (-satisfies? ISeqable t) (let [ts (seq t)] (if (not ts) false - (or (-instance? (first ts) x) - (instance? (rest ts) x)))) + (if (-instance? (first ts) x) + true + (instance? (rest ts) x)))) (-instance? t x)))) (def satisfies? (fn ^{:doc "Checks if x satisfies the protocol p. @@ -186,8 +187,9 @@ (if (-satisfies? ISeqable p) (let [ps (seq p)] (if (not ps) true - (and (-satisfies? (first ps) x) - (satisfies? (rest ps) x)))) + (if (not (-satisfies? (first ps) x)) + false + (satisfies? (rest ps) x)))) (-satisfies? p x)))) (def into (fn ^{:doc "Add the elements of `from` to the collection `to`." From 0d95bb90756c4dbf8e866fc455801fe2e063feab Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Mon, 6 Apr 2015 17:34:13 +0200 Subject: [PATCH 128/349] install g++ in the Dockerfile it's a dependency for the FFI stuff. --- Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index ea969e9a..3da76a00 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ FROM debian:sid # install dependencies RUN apt-get update \ - && apt-get install -y gcc pkg-config make curl bzip2 python2.7 \ + && apt-get install -y gcc g++ pkg-config make curl bzip2 python2.7 \ && apt-get install -y libffi-dev libuv-dev libedit-dev ADD . /usr/src/pixie @@ -12,4 +12,4 @@ RUN cd /usr/src/pixie \ && make PYTHON=python2.7 build_with_jit \ && ln -s /usr/src/pixie/pixie-vm /usr/bin/pxi -ENTRYPOINT ["/usr/bin/pxi"] \ No newline at end of file +ENTRYPOINT ["/usr/bin/pxi"] From 3782dbacf49aac0bfc28c7fd31bfa914c4db39a2 Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Mon, 6 Apr 2015 17:58:32 +0200 Subject: [PATCH 129/349] install libboost-dev in the Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 3da76a00..76ca6849 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ FROM debian:sid # install dependencies RUN apt-get update \ - && apt-get install -y gcc g++ pkg-config make curl bzip2 python2.7 \ + && apt-get install -y gcc g++ libboost-dev pkg-config make curl bzip2 python2.7 \ && apt-get install -y libffi-dev libuv-dev libedit-dev ADD . /usr/src/pixie From 0c9e38b438c1de564aa051e926a492c5f603ab81 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 7 Apr 2015 20:11:58 +0100 Subject: [PATCH 130/349] remove iterators --- pixie/vm/iterator.py | 76 ---------------- pixie/vm/persistent_hash_map.py | 149 -------------------------------- pixie/vm/persistent_hash_set.py | 8 -- 3 files changed, 233 deletions(-) delete mode 100644 pixie/vm/iterator.py diff --git a/pixie/vm/iterator.py b/pixie/vm/iterator.py deleted file mode 100644 index 73327125..00000000 --- a/pixie/vm/iterator.py +++ /dev/null @@ -1,76 +0,0 @@ -from pixie.vm.object import Object, Type, runtime_error -from pixie.vm.code import extend -from pixie.vm.primitives import true, nil -import pixie.vm.stdlib as proto -import pixie.vm.rt as rt - - -class EmptyIterator(Object): - _type = Type(u"pixie.vm.Iterator") - - def type(self): - return EmptyIterator._type - - - def __init__(self): - pass - - def move_next(self): - runtime_error(u"Empty Iterator") - - def at_end(self): - return True - - -empty_iterator = EmptyIterator() - -@extend(proto._at_end_QMARK_, EmptyIterator) -def _at_end(_): - return true - - -class NativeIterator(Object): - _type = Type(u"pixie.vm.NativeIterator") - - def type(self): - return NativeIterator._type - - def __init__(self): - pass - -@extend(proto._at_end_QMARK_, NativeIterator) -def _at_end(self): - return rt.wrap(self.at_end()) - - -@extend(proto._move_next_BANG_, NativeIterator) -def _move_next(self): - return self.move_next() - - -@extend(proto._current, NativeIterator) -def _current(self): - return self.current() - - -class MapIterator(NativeIterator): - def __init__(self, fn, iter): - self._w_fn = fn - self._w_iter = iter - if not iter.at_end(): - self._w_current = self._w_fn.invoke([self._w_iter.current()]) - - def move_next(self): - self._w_iter.move_next() - - if not self._w_iter.at_end(): - self._w_current = self._w_fn.invoke([self._w_iter.current()]) - else: - self._w_current = nil - - def current(self): - return self._w_current - - def at_end(self): - return self._w_iter.at_end() - diff --git a/pixie/vm/persistent_hash_map.py b/pixie/vm/persistent_hash_map.py index b2dc1563..c36dbbdc 100644 --- a/pixie/vm/persistent_hash_map.py +++ b/pixie/vm/persistent_hash_map.py @@ -7,7 +7,6 @@ from rpython.rlib.rarithmetic import r_int, r_uint, intmask import rpython.rlib.jit as jit import pixie.vm.rt as rt -from pixie.vm.iterator import NativeIterator, empty_iterator MASK_32 = r_uint(0xFFFFFFFF) @@ -59,16 +58,6 @@ def without(self, key): return self return PersistentHashMap(self._cnt - 1, new_root, self._meta) - def iter(self): - if self._root is None: - return empty_iterator - else: - return self._root.iter() - - - - - class INode(object.Object): _type = object.Type(u"pixie.stdlib.INode") @@ -185,9 +174,6 @@ def reduce_inode(self, f, init): return init return init - def iter(self): - return BitmapIndexedNodeIterator(self._array) - def without_inode(self, shift, hash, key): bit = bitpos(hash, shift) if self._bitmap & bit == 0: @@ -216,59 +202,6 @@ def without_inode(self, shift, hash, key): BitmapIndexedNode_EMPTY = BitmapIndexedNode(None, r_uint(0), []) - -class BitmapIndexedNodeIterator(NativeIterator): - def __init__(self, array): - self._array_w = array - self._idx = 0 - self._child_iterator_w = None - self._at_end = False - self._current = nil - self.move_next() - - def move_next(self): - while True: - if self._child_iterator_w is None: - while True: - if self._idx == len(self._array_w): - self._current = nil - self._at_end = True - self._array_w = None - return self - key_or_none = self._array_w[self._idx] - val_or_node = self._array_w[self._idx + 1] - - if key_or_none is not None: - self._idx += 2 - self._current = rt.map_entry(key_or_none, val_or_node) - return self - - elif val_or_node is not None: - iter = val_or_node.iter() - if iter.at_end(): - self._idx += 1 - continue - self._child_iterator_w = iter - self._current = self._child_iterator_w.current() - return self - - self._idx += 2 - else: - self._child_iterator_w.move_next() - if self._child_iterator_w.at_end(): - continue - self._current = self._child_iterator_w.current() - return self - - def at_end(self): - return self._at_end - - def current(self): - return self._current - - - - class ArrayNode(INode): def __init__(self, edit, cnt, array): self._cnt = cnt @@ -345,54 +278,6 @@ def reduce_inode(self, f, init): return init - def iter(self): - return ArrayMapIterator(self._array) - -class ArrayMapIterator(NativeIterator): - def __init__(self, array): - self._array_w = array - self._idx = 0 - self._child_iterator_w = None - self._at_end = False - self._current = nil - self.move_next() - - def move_next(self): - while True: - if self._child_iterator_w is None: - while True: - if self._idx == len(self._array_w): - self._current = nil - self._at_end = True - self._array_w = None - return self - val = self._array_w[self._idx] - if val is not None: - iter = val.iter() - if iter.at_end(): - self._idx += 1 - continue - self._child_iterator_w = iter - self._current = self._child_iterator_w.current() - return self - - self._idx += 1 - else: - self._child_iterator_w.move_next() - if self._child_iterator_w.at_end(): - continue - self._current = self._child_iterator_w.current() - return self - - def at_end(self): - return self._at_end - - def current(self): - return self._current - - - - class HashCollisionNode(INode): def __init__(self, edit, hash, array): self._hash = hash @@ -437,9 +322,6 @@ def reduce_inode(self, f, init): return init return init - def iter(self): - return HashCollisionNodeIterator(self._array) - def find_index(self, key): i = r_int(0) while i < len(self._array): @@ -461,37 +343,6 @@ def without_inode(self, shift, hash, key): return HashCollisionNode(None, self._hash, remove_pair(self._array, r_uint(idx) / 2)) -class HashCollisionNodeIterator(NativeIterator): - def __init__(self, array): - self._w_array = array - self._w_idx = 0 - self._w_current = nil - self.move_next() - - def move_next(self): - while True: - if self._w_idx == len(self._w_array): - self._w_current = nil - self._w_array = None - return self - - key = self._w_array[self._w_idx] - val = self._w_array[self._w_idx + 1] - self._w_idx += 2 - if key is None: - continue - - self._w_current = rt.map_entry(key, val) - return - - def at_end(self): - return self._w_current is None - - def current(self): - return self._w_current - - - def create_node(shift, key1, val1, key2hash, key2, val2): key1hash = rt.hash(key1) & MASK_32 if key1hash == key2hash: diff --git a/pixie/vm/persistent_hash_set.py b/pixie/vm/persistent_hash_set.py index 2cebe830..9327ea42 100644 --- a/pixie/vm/persistent_hash_set.py +++ b/pixie/vm/persistent_hash_set.py @@ -5,7 +5,6 @@ import pixie.vm.stdlib as proto from pixie.vm.code import extend, as_var, intern_var import pixie.vm.rt as rt -from pixie.vm.iterator import MapIterator VAR_KEY = intern_var(u"pixie.stdlib", u"key") @@ -32,9 +31,6 @@ def meta(self): def with_meta(self, meta): return PersistentHashSet(meta, self._map) - def iter(self): - return MapIterator(VAR_KEY.deref(), self._map.iter()) - EMPTY = PersistentHashSet(nil, persistent_hash_map.EMPTY) @as_var("set") @@ -102,7 +98,3 @@ def _meta(self): def _with_meta(self, meta): assert isinstance(self, PersistentHashSet) return self.with_meta(meta) - -@extend(proto._iterator, PersistentHashSet) -def _iterator(self): - return self.iter() From 380340a80df3e4abf30e7528063d51c45fb493ac Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 8 Apr 2015 06:42:09 -0600 Subject: [PATCH 131/349] added basic parser support --- Makefile | 2 +- pixie/parser.pxi | 393 ++++++++++++++++++++++++++++++ pixie/stdlib.pxi | 7 + tests/pixie/tests/test-parser.pxi | 10 + 4 files changed, 411 insertions(+), 1 deletion(-) create mode 100644 pixie/parser.pxi create mode 100644 tests/pixie/tests/test-parser.pxi diff --git a/Makefile b/Makefile index c6a4850a..5cfac9aa 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,7 @@ build_preload_no_jit: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target_preload.py build: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) $(JIT_OPTS) $(TARGET_OPTS) + $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) $(JIT_OPTS) $(TARGET_OPTS) fetch_externals: $(EXTERNALS)/pypy ./lib diff --git a/pixie/parser.pxi b/pixie/parser.pxi new file mode 100644 index 00000000..d5b8e10c --- /dev/null +++ b/pixie/parser.pxi @@ -0,0 +1,393 @@ +(ns pixie.parser + (require pixie.stdlib :as s)) + + +;; This file contans a small framework for writing generic parsers in Pixie. Although the generated +;; code is probably not the fastest, it is fairly simple, and that simplicity should open the road for +;; future optimizations. The parsers allowed support multiple inheritance and multiple input data types. +;; Backtracking is supported by snapshots taken at key parts of the parsing process. For a string parser +;; these snapshots are simply a integer index into the string being parsed. + +;; Cursors + +(defprotocol ICursor + (next! [this] "Advance to the next element") + (current [this] "Return the current element") + (snapshot [this] "Return a snapshot of the cursor's mutable state") + (rewind! [this snapshot] "Rewind the cursor to a previous snapshot") + (at-end? [this] "Is there more to parse?")) + +(deftype StringCursor [idx s] + ICursor + (next! [this] + (set-field! this :idx (inc idx))) + (current [this] + (when (< idx (count s)) + (nth s idx))) + (snapshot [this] + idx) + (rewind! [this val] + (set-field! this :idx val)) + (at-end? [this] + (= idx (count s)))) + +;; Create a cursor from the given string +(defn string-cursor [s] + (->StringCursor 0 s)) + +;; Mechanics + +(deftype ParseFailure []) + +;; If a parser returns this value, parsing has failed +(def fail (->ParseFailure)) + +(defn failure? + "Returns true if return value from a parser is a parse failure" + [v] + (identical? v fail)) + +(defn parse-if + "Parse and return the current value of the cursor if this predicate succeeds against the cursor. Advances + the cursor to the next element." + [pred] + (fn [cursor] + (if (pred (current cursor)) + (let [value (current cursor)] + (next! cursor) + value) + fail))) + + +(defprotocol IParserGenerator + (to-parser [this] "Convert the current object to a parser")) + +(extend-protocol IParserGenerator + IFn + (to-parser [this] + this) + Character + (to-parser [this] + (parse-if #(= % this)))) + + + + +(defn or + "Defines a parser that succeeds if one of the provided parsers succeeds. Parsers are tried in-order." + ([a] a) + ([a b] + (let [a (to-parser a) + b (to-parser b) + m (atom #{})] + (fn [cursor] + (let [key [cursor (snapshot cursor)]] + (if-let [v (contains? @m key)] + (b cursor) + (let [_ (swap! m conj key) + state (snapshot cursor) + val (a cursor)] + (swap! m disj key) + (if (identical? val fail) + (do (rewind! cursor state) + (b cursor)) + val))))))) + ([a b & more] + (apply or (or a b) more))) + +(defn add-clauses [cursor-sym body [[sym goal] & more]] + (if sym + `(let [~sym (~sym ~cursor-sym)] + (if (identical? ~sym fail) + fail + ~(add-clauses cursor-sym body more))) + body)) + +(defn -parse-args + [args] + (loop [args args + rules [] + return nil] + (let [[arg & rest] args] + (assert (not (= '-> arg)) "invalid position for ->") + (if arg + (if (= '<- arg) + (let [return (first rest)] + (recur (next rest) + rules + return)) + (if (= (first rest) '->) + (let [binding (-> rest next first) + rest (-> rest next next)] + (recur rest + (conj rules [binding arg]) + return)) + (recur rest + (conj rules [(gensym "_") arg]) + return))) + [rules return])))) + +(defmacro and + "Defines a parser that succeeds only if all parsers succeed. Tried in order. Each parser clause can be followed + by a -> to give the parser's output a name. There may also be a single <- followed by any Pixie code that can be used + to post-process the parsed output." + [& args] + (let [[parsed body] (-parse-args args) + cursor-sym (gensym "cursor")] + `(let [~@(mapcat + (fn [[sym parser]] + [sym `(to-parser ~parser)]) + parsed)] + (fn [~cursor-sym] + (let [prev-pos# (snapshot ~cursor-sym) + result# ~(add-clauses cursor-sym body parsed)] + (if (identical? result# fail) + (do (rewind! ~cursor-sym prev-pos#) + fail) + result#)))))) + + +(defprotocol IDeliverable + (-deliver [this val])) + +(deftype PromiseFn [f name] + IDeliverable + (-deliver [this val] + (set-field! this :f val)) + IFn + (-invoke [this val] + (assert f (str "PromiseFN " name " has not been delivered")) + (f val))) + +(defn promise-fn + "Defines a promise that is callable." + [name] + (->PromiseFn nil name)) + +(defmacro parser + "(parser nm inherits & rules) + Defines a new parser named `nm` that inherits from zero or more other parsers defined ion `inherits`. Rules are pairs + of names and rules that will be assigned to those names. Names are inherited from parent parsers in the order they are + defined." + [inherits & rules] + (let [parted (apply merge + (conj (mapv (fn [sym] + (-> sym resolve deref ::forms)) inherits) + (apply hashmap rules))) + rules (apply concat parted) + syms (keys parted)] + `(let [~@(mapcat (fn [s] + `[~s (promise-fn (quote ~s))]) + syms)] + ~@(map (fn [[s goal]] + `(-deliver ~s ~goal)) + parted) + ~(assoc (zipmap (map (comp keyword name) syms) + syms) + ::forms (list 'quote (apply hashmap rules)))))) + +(defmacro defparser + "(defparser nm inherits rules) + Same as parser but assigns the resulting parser to a var with the name nm" + [nm inherits & rules] + `(def ~nm (parser ~inherits ~@rules))) + +;; Common parsers + +(defn char-range + "Defines a parser that parses a numerical range of characters" + [from to] + (parse-if (fn [v] + (when (char? v) + (<= (int from) (int v) (int to)))))) + +(defn one+ + "Defines a parser that succeeds if the given parser succeeds once or more. Will return a vector, but any + reducing function can be provided via rf as well." + ([g] + (one+ g conj)) + ([g rf] + (let [g (to-parser g)] + (fn [cursor] + (loop [acc (rf) + cnt 0] + (let [prev-pos (snapshot cursor) + v (g cursor)] + (if (identical? v fail) + (if (= 0 cnt) + (do (rewind! cursor prev-pos) + fail) + (rf acc)) + (recur (rf acc v) + (inc cnt))))))))) + +(def one+chars #(one+ % string-builder)) + +(defn zero+ + "Defines a parser that succeeds if a given parser succeeds zero or more times. Will return a vector, but + any reducing function can be provided via rf as well." + ([g] + (zero+ g conj)) + ([g rf] + (let [g (to-parser g)] + (fn [cursor] + (loop [acc (rf)] + (let [v (g cursor)] + (if (identical? v fail) + (rf acc) + (recur (rf acc v))))))))) + +(def zero+chars #(zero+ % string-builder)) + +(defn eat + "Eagerly parses as many values as possible until g fails. Discards the result, returns nil." + [g] + (fn [cursor] + (loop [] + (let [prev-pos (snapshot cursor) + v (g cursor)] + (if (identical? v fail) + (do (rewind! cursor prev-pos) + nil) + (recur)))))) + +(defn maybe + "Always succeeds, returns nil when the input did not match the parser." + ([g] + (maybe g nil)) + ([g default] + (let [g (to-parser g)] + (fn [cursor] + (let [v (g cursor)] + (if (failure? v) + default + v)))))) + +(defmacro sequence + [coll arrow body] + (assert (= '<- arrow) "Middle argument to sequence must be a return arrow") + `(and ~@coll ~'<- ~body)) + +(def end + "A parser that only succeeds if there is no more input left to process." + (fn [cursor] + (if (at-end? cursor) + nil + fail))) + +(defn one-of + "Deines a parser that succeeds if the value being parsed is found in v" + [v] + (parse-if (partial contains? v))) + +(def digits (parse-if (set "1234567890"))) + +(def whitespace (parse-if #{\newline \return \space \tab})) + +;; Basic numeric parser. Supports integers (1, 2, 43), decimals (0.1, 1.1, 1000.11) and exponents (1e42, 1E-2) +(defparser NumberParser [] + NUMBER (and (maybe \-) + -> sign + + (or (and + (parse-if (set "123456789")) -> first + (zero+chars digits) -> rest + <- (str first rest)) + (and \0)) + -> integer-digits + + (maybe (and \. + (one+chars digits) -> digits + <- digits)) + -> fraction-digits + + + (maybe (and (parse-if (set "eE")) + (maybe (parse-if (set "-+"))) -> exp-sign + (one+chars digits) -> exp-digits + <- [(s/or exp-sign "") exp-digits])) + -> exp-data + + <- (read-string (str (s/or sign "") + integer-digits + (if fraction-digits (str "." fraction-digits) "") + (if exp-data (apply str "E" exp-data) ""))))) + +(def valid-escape-chars + {\\ \\ + \" \" + \/ \/ + \b \backspace + \f \formfeed + \n \newline + \r \return + \t \tab}) + + +;; Defines a JSON escaped string parser. Supports all the normal \n \f \r stuff as well +;; as \uXXXX unicode characters +(defparser EscapedStringParser [] + CHAR (or (and \\ + (one-of valid-escape-chars) -> char + <- (valid-escape-chars char)) + + (and \\ + \u + digits -> d1 + digits -> d2 + digits -> d3 + digits -> d4 + <- (do + (println [d1 d2 d3 d4]) + (char (read-string (str "0x" d1 d2 d3 d4))))) + + (parse-if #(not= % \"))) + + STRING (and \" + (zero+chars CHAR) -> s + \" + <- s)) + +;; Basic JSON parser +(defparser JSONParser [NumberParser EscapedStringParser] + + NULL (sequence "null" <- nil) + TRUE (sequence "true" <- true) + FALSE (sequence "false" <- false) + ARRAY (and \[ + (eat whitespace) + (zero+ (and ENTRY -> e + (maybe \,) + <- e)) -> items + (eat whitespace) + (eat whitespace) + \] + <- items) + MAP-ENTRY (and (eat whitespace) + STRING -> key + (eat whitespace) + \: + ENTRY -> value + (maybe \,) + <- [key value]) + MAP (and \{ + (zero+ MAP-ENTRY) -> items + (eat whitespace) + \} + <- (apply hashmap (apply concat items))) + ENTRY (and + (eat whitespace) + (or NUMBER MAP STRING NULL TRUE FALSE ARRAY) -> val + (eat whitespace) + <- val) + ENTRY-AT-END (and ENTRY -> e + (eat whitespace) + end + <- e)) + +(defn read-json-string [s] + (let [c (string-cursor s) + result ((:ENTRY-AT-END JSONParser) c)] + (if (failure? result) + (println (current c) (snapshot c)) + result))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6276dd5d..c8a3e506 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -280,6 +280,7 @@ (extend -invoke Code -invoke) (extend -invoke NativeFn -invoke) (extend -invoke VariadicCode -invoke) +(extend -invoke MultiArityFn -invoke) (extend -invoke Closure -invoke) (extend -invoke Var -invoke) (extend -invoke PolymorphicFn -invoke) @@ -2340,3 +2341,9 @@ Expands to calls to `extend-type`." (def *e) (defn -set-*e [e] (def *e e)) + + +(def hash-map hashmap) + +(defn zipmap [a b] + (into {} (map vector a b))) diff --git a/tests/pixie/tests/test-parser.pxi b/tests/pixie/tests/test-parser.pxi new file mode 100644 index 00000000..54f1d580 --- /dev/null +++ b/tests/pixie/tests/test-parser.pxi @@ -0,0 +1,10 @@ +(ns pixie.tests.test-parser + (require pixie.test :refer :all) + (require pixie.parser :refer :all)) + +(deftest test-and + (let [p (parser [] + (and \a \b)) + c (string-cursor "abc")] + (assert= [\a \b] c) + (assert= (current c) \c))) From 6320356ed95ef38aa074d9a21d0f6b21e3f91049 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 8 Apr 2015 20:47:34 +0100 Subject: [PATCH 132/349] add another test to catch iteraters over maps --- tests/pixie/tests/test-stdlib.pxi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 3e9b50a4..1b80de5a 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -296,7 +296,9 @@ (t/assert= (seq (filter (fn [x] true) [])) nil) (t/assert= (seq (filter (fn [x] false) [])) nil) (t/assert= (seq (filter (fn [x] true) [1 2 3 4])) '(1 2 3 4)) - (t/assert= (seq (filter (fn [x] false) [1 2 3 4])) nil)) + (t/assert= (seq (filter (fn [x] false) [1 2 3 4])) nil) + (t/assert= (filter (fn [[_ v]] (odd? v)) {:a 1, :b 2, :c 3, :d 4}) + '(1 3))) (t/deftest test-distinct (t/assert= (seq (distinct [1 2 3 2 1])) '(1 2 3)) From 774cdfe7ccf591a146ec55f0032b06ed9a6bfb05 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 8 Apr 2015 22:11:27 +0100 Subject: [PATCH 133/349] remove iterators from stdlib --- pixie/stdlib.pxi | 175 ++++++++++-------------------- pixie/vm/stdlib.py | 19 ---- tests/pixie/tests/test-stdlib.pxi | 5 +- 3 files changed, 60 insertions(+), 139 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index d5cf4875..c3060254 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -415,7 +415,14 @@ nil (cons (nth self x) (lazy-seq* (fn [] (vector-seq self (+ x 1))))))))) - +(extend -seq String + (fn string-seq + ([self] + (string-seq self 0)) + ([self x] + (if (= x (count self)) + nil + (cons (nth self x) (lazy-seq* (fn [] (string-seq self (+ x 1))))))))) (def concat (fn ^{:doc "Concatenates its arguments." @@ -894,16 +901,6 @@ If further arguments are passed, invokes the method named by symbol, passing the nil [:me :me :me :me]]]} (fn [& _] x)) -(defn some - {:doc "Returns the first true value of the predicate for the elements of the collection." - :signatures [[pred coll]] - :added "0.1"} - [pred coll] - (if-let [coll (seq coll)] - (or (pred (first coll)) - (recur pred (next coll))) - false)) - (extend -count MapEntry (fn [self] 2)) (extend -nth MapEntry (fn map-entry-nth [self idx] (cond (= idx 0) (-key self) @@ -1421,21 +1418,6 @@ The new value is thus `(apply f current-value-of-atom args)`." (do ~@body (recur (inc ~b)))))))) -(extend -iterator PersistentVector - (fn [v] - (dotimes [x (count v)] - (yield (nth v x nil))))) - -(extend -iterator Array - (fn [v] - (dotimes [x (count v)] - (yield (nth v x nil))))) - -(extend -iterator String - (fn [v] - (dotimes [x (count v)] - (yield (nth v x nil))))) - (defmacro and {:doc "Check if the given expressions return truthy values, returning the last, or false." :examples [["(and true false)" nil false] @@ -1483,6 +1465,16 @@ The new value is thus `(apply f current-value-of-atom args)`." ~then) ~else))))) +(defn some + {:doc "Returns the first true value of the predicate for the elements of the collection." + :signatures [[pred coll]] + :added "0.1"} + [pred coll] + (if (seq coll) + (or (pred (first coll)) + (some pred (next coll))) + false)) + (defn nnext {:doc "Equivalent to (next (next coll))" :added "0.1"} @@ -1767,14 +1759,6 @@ For more information, see http://clojure.org/special_forms#binding-forms"} @acc (recur (+ i step) acc))) acc))) - IIterable - (-iterator [self] - (loop [i start] - (when (or (and (> step 0) (< i stop)) - (and (< step 0) (> i stop)) - (and (= step 0))) - (yield i) - (recur (+ i step))))) ICounted (-count [self] (if (or (and (< start stop) (< step 0)) @@ -1816,33 +1800,6 @@ For more information, see http://clojure.org/special_forms#binding-forms"} ([start stop] (->Range start stop 1)) ([start stop step] (->Range start stop step))) -(defn iterator - {:doc "Returns an iterator for the collection." - :added "0.1"} - [coll] - (-iterator coll)) - -(defn move-next! [i] - (-move-next! i) - i) - -(defn at-end? [i] - (-at-end? i)) - -(defn current [i] - (-current i)) - -(defn iterator-seq [i] - (if (at-end? i) - nil - (cons (current i) (lazy-seq (iterator-seq (move-next! i)))))) - -(extend -first IIterator -current) -(extend -iterator IIterator identity) - -(extend -seq IIterator iterator-seq) -(extend -seq IIterable (comp seq iterator)) - (extend -eq ISeqable -seq-eq) (deftype Unknown []) @@ -1863,36 +1820,25 @@ For more information, see http://clojure.org/special_forms#binding-forms"} true self)))) -(extend -reduce ShallowContinuation - (fn [k f init] - (loop [acc init] - (if (reduced? init) - @init - (if (-at-end? k) - acc - (let [acc (f acc (-current k))] - (-move-next! k) - (recur acc))))))) - (defn filter {:doc "Filter the collection for elements matching the predicate." :signatures [[pred] [pred coll]] :added "0.1"} - ([f] (fn [xf] - (fn - ([] (xf)) - ([acc] (xf acc)) - ([acc i] (if (f i) - (xf acc i) - acc))))) - ([f coll] - (let [iter (iterator coll)] - (loop [] - (when (not (at-end? iter)) - (if (f (current iter)) - (yield (current iter))) - (move-next! iter) - (recur)))))) + ([pred] + (fn [xf] + (fn + ([] (xf)) + ([acc] (xf acc)) + ([acc i] (if (pred i) + (xf acc i) + acc))))) + ([pred coll] + (lazy-seq + (when-let [s (seq coll)] + (let [[f & r] s] + (if (pred f) + (cons f (filter pred r)) + (filter pred r))))))) (defn distinct {:doc "Returns the distinct elements in the collection." @@ -1910,33 +1856,35 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (swap! seen conj i) (xf acc i)))))))) ([coll] - (let [iter (iterator coll)] - (loop [acc #{}] - (when (not (at-end? iter)) - (if (contains? acc (current iter)) - (do (move-next! iter) - (recur acc)) - (let [val (current iter)] - (yield val) - (move-next! iter) - (recur (conj acc val))))))))) - + (let [step (fn step [xs seen] + (lazy-seq + ((fn [f seen] + (when-let [s (seq f)] + (let [xs (first s)] + (if (contains? seen xs) + (step (rest s) seen) + (cons xs (step (rest s) (conj seen xs))))))) + xs seen)))] + (step coll #{})))) (defn keep ([f] - (fn [xf] - (fn - ([] (xf)) - ([acc] (xf acc)) - ([acc i] (let [result (f i)] - (if result - (xf acc result) - acc)))))) + (fn [xf] + (fn + ([] (xf)) + ([acc] (xf acc)) + ([acc i] (let [result (f i)] + (if result + (xf acc result) + acc)))))) ([f coll] - (iterate [x coll] - (let [result (f x)] - (if result - (yield result)))))) + (lazy-seq + (when-let [s (seq coll)] + (let [[first & rest] s + result (f first)] + (if result + (cons result (keep f rest)) + (keep f rest))))))) (defn refer {:doc "Refer to the specified vars from a namespace directly. @@ -1991,13 +1939,6 @@ user => (refer 'pixie.string :exclude '(substring))" -(extend -iterator ISeq (fn [s] - (loop [s s] - (when s - (yield (first s)) - (recur (next s)))))) -(extend -at-end? EmptyList (fn [_] true)) - (defn merge-with [f & maps] (cond diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 78eb48bd..1e581eb6 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -57,9 +57,6 @@ defprotocol("pixie.stdlib", "ITransientCollection", ["-conj!"]) defprotocol("pixie.stdlib", "ITransientStack", ["-push!", "-pop!"]) -defprotocol("pixie.stdlib", "IIterable", ["-iterator"]) -defprotocol("pixie.stdlib", "IIterator", ["-current", "-at-end?", "-move-next!"]) - defprotocol("pixie.stdlib", "IDisposable", ["-dispose!"]) @as_var("pixie.stdlib.internal", "-defprotocol") @@ -233,22 +230,6 @@ def __name(self): def __name(_): return nil -@extend(_current, ShallowContinuation) -def _current(self): - assert isinstance(self, ShallowContinuation) - return self._val - -@extend(_at_end_QMARK_, ShallowContinuation) -def _(self): - assert isinstance(self, ShallowContinuation) - return true if self.is_finished() else false - -@extend(_move_next_BANG_, ShallowContinuation) -def _(self): - assert isinstance(self, ShallowContinuation) - self.invoke([nil]) - return self - @returns(r_uint) @as_var("hash") def __hash(x): diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 1b80de5a..dab376dc 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -297,8 +297,8 @@ (t/assert= (seq (filter (fn [x] false) [])) nil) (t/assert= (seq (filter (fn [x] true) [1 2 3 4])) '(1 2 3 4)) (t/assert= (seq (filter (fn [x] false) [1 2 3 4])) nil) - (t/assert= (filter (fn [[_ v]] (odd? v)) {:a 1, :b 2, :c 3, :d 4}) - '(1 3))) + (t/assert= (into {} (filter (fn [[_ v]] (odd? v)) {:a 1, :b 2, :c 3, :d 4})) + {:a 1 :c 3})) (t/deftest test-distinct (t/assert= (seq (distinct [1 2 3 2 1])) '(1 2 3)) @@ -346,7 +346,6 @@ (t/deftest test-range (t/assert= (= (-seq (range 10)) - (-seq (-iterator (range 10))) '(0 1 2 3 4 5 6 7 8 9)) true)) From fe9bf9a98e65ed711c98dec973c4ba467b102092 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 8 Apr 2015 20:50:23 -0600 Subject: [PATCH 134/349] fixed a bunch of issues with error messages --- pixie/vm/compiler.py | 5 ++++- pixie/vm/libs/pxic/reader.py | 5 +++-- pixie/vm/libs/pxic/writer.py | 1 - pixie/vm/object.py | 21 +++++++++++++++++++++ pixie/vm/stdlib.py | 30 +++++++++++++++++++++++++----- 5 files changed, 53 insertions(+), 9 deletions(-) diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index c915214a..8165b486 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -78,7 +78,10 @@ def __init__(self, name, argc, parent_ctx): self._max_sp = 0 self.can_tail_call = False self.closed_overs = [] - self.name = name + if parent_ctx: + self.name = parent_ctx.name + u"_" + name + else: + self.name = name self.recur_points = [] self.debug_points = {} diff --git a/pixie/vm/libs/pxic/reader.py b/pixie/vm/libs/pxic/reader.py index b4ec9cbb..571cbddc 100644 --- a/pixie/vm/libs/pxic/reader.py +++ b/pixie/vm/libs/pxic/reader.py @@ -55,7 +55,8 @@ def read_raw_integer(rdr): return r_uint(ord(rdr.read()[0]) | (ord(rdr.read()[0]) << 8) | (ord(rdr.read()[0]) << 16) | (ord(rdr.read()[0]) << 24)) def read_raw_string(rdr): - return rdr.read_cached_string() + s = rdr.read_cached_string() + return s def read_code(rdr): sz = read_raw_integer(rdr) @@ -129,7 +130,6 @@ def read_interpreter_code_info(rdr): line_number = read_raw_integer(rdr) column_number = read_raw_integer(rdr) file = read_raw_string(rdr) - return InterpreterCodeInfo(line, intmask(line_number), intmask(column_number), file) def read_obj(rdr): @@ -151,6 +151,7 @@ def read_obj(rdr): return symbol(read_raw_string(rdr)) elif tag == LINE_PROMISE: lp = LinePromise() + lp._chrs = None lp._str = read_raw_string(rdr) return lp elif tag == MAP: diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index ecd8865d..8f1318ec 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -231,7 +231,6 @@ def write_namespace(o, wtr): def write_interpreter_code_info(obj, wtr): line, line_number, column_number, file = obj.interpreter_code_info_state() - write_tag(CODE_INFO, wtr) write_object(line, wtr) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 32bdd199..ad95b463 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -255,3 +255,24 @@ def trace_map(self): tm = {keyword(u"type") : keyword(u"pixie")} tm[keyword(u"name")] = String(self._name) return tm + +class ExtraCodeInfo(ErrorInfo): + def __init__(self, str): + self._str = str + + def __repr__(self): + return self._str + + def trace_map(self): + import pixie.vm.rt as rt + from pixie.vm.keyword import keyword + + tm = {keyword(u"type"): keyword(u"extra"), + keyword(u"data"): rt.wrap(self._str)} + return tm + + +def add_info(ex, data): + assert isinstance(ex, WrappedException) + ex._ex._trace.append(ExtraCodeInfo(data)) + return ex \ No newline at end of file diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 78eb48bd..f5702385 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ - runtime_error + runtime_error, add_info from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ list_copy, returns, intern_var import pixie.vm.code as code @@ -506,12 +506,32 @@ def load_reader(rdr): form = reader.read(rdr, False) if form is reader.eof: return nil - compiled = compiler.compile(form) - if pxic_writer is not None: - pxic_writer.write_object(compiled) + try: + compiled = compiler.compile(form) + + except WrappedException as ex: + meta = rt.meta(form) + if meta is not nil: + ci = rt.interpreter_code_info(meta) + add_info(ex, ci.__repr__()) + add_info(ex, u"Compiling: " + rt.name(rt.str(form))) + raise ex + + try: + if pxic_writer is not None: + pxic_writer.write_object(compiled) + + compiled.invoke([]) + + except WrappedException as ex: + meta = rt.meta(form) + if meta is not nil: + ci = rt.interpreter_code_info(meta) + add_info(ex, ci.__repr__()) + add_info(ex, u"Running: " + rt.name(rt.str(form))) + raise ex - compiled.invoke([]) if not we_are_translated(): print "done" From ce45c1c04d15c47dd492e69b880b0a7fc1580dac Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 9 Apr 2015 06:36:02 -0600 Subject: [PATCH 135/349] fixed up function names and added a few more debug helpers --- Makefile | 2 +- pixie/stdlib.pxi | 7 +++---- pixie/vm/compiler.py | 18 ++++++++++-------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index c6a4850a..a39ea229 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ build_no_jit: fetch_externals compile_basics: @echo -e "\n\n\n\nWARNING: Compiling core libs. If you want to modify one of these files delete the .pxic files first\n\n\n\n" - ./pixie-vm -c pixie/uv.pxi -c pixie/io.pxi -c pixie/stacklets.pxi -c pixie/stdlib.pxi + ./pixie-vm -c pixie/uv.pxi -c pixie/io.pxi -c pixie/stacklets.pxi -c pixie/stdlib.pxi -c pixie/repl.pxi build_preload_with_jit: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --opt=jit target_preload.py 2>&1 >/dev/null | grep -v 'WARNING' diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index d5cf4875..185ce1c3 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2034,9 +2034,8 @@ The following two forms are allowed: The params can be destructuring bindings, see `(doc let)` for details."} [& decls] - (let [name (if (symbol? (first decls)) (first decls) nil) + (let [name (if (symbol? (first decls)) [(first decls)] nil) decls (if name (next decls) decls) - name (or name '-fn) decls (cond (vector? (first decls)) (list decls) ;(satisfies? ISeqable (first decls)) decls @@ -2059,8 +2058,8 @@ The params can be destructuring bindings, see `(doc let)` for details."} ~@body))))) decls))] (if (= (count decls) 1) - `(fn* ~name ~(first (first decls)) ~@(next (first decls))) - `(fn* ~name ~@decls)))) + `(fn* ~@name ~(first (first decls)) ~@(next (first decls))) + `(fn* ~@name ~@decls)))) (deftype MultiMethod [dispatch-fn default-val methods] IFn diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index 8165b486..f314ac1c 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -78,8 +78,8 @@ def __init__(self, name, argc, parent_ctx): self._max_sp = 0 self.can_tail_call = False self.closed_overs = [] - if parent_ctx: - self.name = parent_ctx.name + u"_" + name + if name == default_fn_name and parent_ctx: + self.name = parent_ctx.name + u"_fn" else: self.name = name self.recur_points = [] @@ -459,7 +459,10 @@ def compile_platform_plus(form, ctx): def add_args(name, args, ctx): required_args = -1 local_idx = 0 - ctx.add_local(name, Self()) + + if name != default_fn_name: + ctx.add_local(name, Self()) + for x in range(rt.count(args)): arg = rt.nth(args, rt.wrap(x)) affirm(isinstance(arg, symbol.Symbol), u"Argument names must be symbols") @@ -471,6 +474,7 @@ def add_args(name, args, ctx): local_idx += 1 return required_args +default_fn_name = u"some_long_name_unlikely_to_be_used" def compile_fn(form, ctx): form = rt.next(form) @@ -478,7 +482,7 @@ def compile_fn(form, ctx): name = rt.first(form) form = rt.next(form) else: - name = symbol.symbol(u"-fn") + name = symbol.symbol(default_fn_name) @@ -511,9 +515,7 @@ def compile_fn_body(name, args, body, ctx): required_args = add_args(rt.name(name), args, new_ctx) bc = 0 - if name is not None: - affirm(isinstance(name, symbol.Symbol), u"Function names must be symbols") - #new_ctx.add_local(name._str, Self()) + affirm(isinstance(name, symbol.Symbol), u"Function names must be symbols") arg_syms = EMPTY for x in range(rt.count(args)): @@ -847,7 +849,7 @@ def compile_fn_call(form, ctx): def compile(form): - ctx = Context(u"main", 0, None) + ctx = Context(u"_toplevel_", 0, None) compile_form(form, ctx) ctx.bytecode.append(code.RETURN) return ctx.to_code() From 8f7368ab1da5598b3002dff2806380efba33612f Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Thu, 9 Apr 2015 20:59:05 +0100 Subject: [PATCH 136/349] Add a few extra uv functions --- pixie/uv.pxi | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 76417f47..210a63bd 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -27,9 +27,18 @@ (f/defcfn uv_update_time) (f/defcfn uv_walk) + (f/defccallback uv_alloc_cb) + (f/defcstruct uv_connect_t [:handle]) + (f/defcstruct uv_stream_t []) + + (f/defcfn uv_read_start) (f/defccallback uv_read_cb) + (f/defcfn uv_write) + (f/defcstruct uv_write_t []) + (f/defccallback uv_write_cb) + ;; Timer @@ -184,9 +193,11 @@ (f/defcfn uv_tcp_bind) (f/defcfn uv_listen) (f/defcfn uv_accept) - (f/defcfn uv_read_start) + (f/defcfn uv_tcp_connect) + (f/defcfn uv_tcp_keepalive) (f/defccallback uv_connection_cb) + (f/defccallback uv_connect_cb) ) From 3597a8191e4ef1399cfe85a9bdbee86096d3f626 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 9 Apr 2015 16:09:40 -0600 Subject: [PATCH 137/349] added tests and data support for add-exception-info --- pixie/vm/object.py | 9 +++++++-- pixie/vm/stdlib.py | 9 ++++++++- tests/pixie/tests/test-errors.pxi | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 tests/pixie/tests/test-errors.pxi diff --git a/pixie/vm/object.py b/pixie/vm/object.py index ad95b463..99123bd3 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -257,8 +257,9 @@ def trace_map(self): return tm class ExtraCodeInfo(ErrorInfo): - def __init__(self, str): + def __init__(self, str, data=None): self._str = str + self._data = data def __repr__(self): return self._str @@ -268,7 +269,11 @@ def trace_map(self): from pixie.vm.keyword import keyword tm = {keyword(u"type"): keyword(u"extra"), - keyword(u"data"): rt.wrap(self._str)} + keyword(u"msg"): rt.wrap(self._str)} + + if self._data: + tm[keyword(u"data")] = self._data + return tm diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 487d9c8c..cd9a283d 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ - runtime_error, add_info + runtime_error, add_info, ExtraCodeInfo from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ list_copy, returns, intern_var import pixie.vm.code as code @@ -865,3 +865,10 @@ def _set_current_var_frames(self, frames): Sets the current var frames. Frames should be a cons list of hashmaps containing mappings of vars to dynamic values. Setting this value to anything but this data format will cause undefined errors.""" code._dynamic_vars.set_current_frames(frames) + +@as_var("add-exception-info") +def _add_exception_info(ex, str, data): + affirm(isinstance(ex, RuntimeException), u"First argument must be an exception") + assert isinstance(ex, RuntimeException) + ex._trace.append(ExtraCodeInfo(rt.name(str), data)) + return ex diff --git a/tests/pixie/tests/test-errors.pxi b/tests/pixie/tests/test-errors.pxi new file mode 100644 index 00000000..1ef095b5 --- /dev/null +++ b/tests/pixie/tests/test-errors.pxi @@ -0,0 +1,15 @@ +(ns pixie.test.test-errors + (:require [pixie.test :refer :all])) + +(deftest test-add-exception-info + (try + (try + (+ 1 "foo") + (catch ex + (throw (add-exception-info ex "My Msg" :my-data)))) + (catch ex + (let [filter-fn (fn [mp] + (and (= (:type mp) :extra) + (= (:msg mp) "My Msg") + (= (:data mp) :my-data)))] + (assert= 1 (count (filter filter-fn ex))))))) From d388d1bd25d74dc6e58702a709ebcdc15ea3a883 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Fri, 10 Apr 2015 16:46:25 -0600 Subject: [PATCH 138/349] moved json code into its own namespace --- pixie/parsers/json.pxi | 111 ++++++++++++++++++++++++ pixie/stdlib.pxi | 38 ++++---- pixie/test.pxi | 7 ++ tests/pixie/tests/parsers/test-json.pxi | 11 +++ 4 files changed, 148 insertions(+), 19 deletions(-) create mode 100644 pixie/parsers/json.pxi create mode 100644 tests/pixie/tests/parsers/test-json.pxi diff --git a/pixie/parsers/json.pxi b/pixie/parsers/json.pxi new file mode 100644 index 00000000..c870a8c7 --- /dev/null +++ b/pixie/parsers/json.pxi @@ -0,0 +1,111 @@ +(ns pixie.parsers.json + (:require [pixie.parser :refer :all] + [pixie.stdlib :as std])) + + + +;; Basic numeric parser. Supports integers (1, 2, 43), decimals (0.1, 1.1, 1000.11) and exponents (1e42, 1E-2) +(defparser NumberParser [] + NUMBER (and (maybe \-) + -> sign + + (or (and + (parse-if (set "123456789")) -> first + (zero+chars digits) -> rest + <- (str first rest)) + (and \0)) + -> integer-digits + + (maybe (and \. + (one+chars digits) -> digits + <- digits)) + -> fraction-digits + + + (maybe (and (parse-if (set "eE")) + (maybe (parse-if (set "-+"))) -> exp-sign + (one+chars digits) -> exp-digits + <- [(std/or exp-sign "") exp-digits])) + -> exp-data + + <- (std/read-string (str (std/or sign "") + integer-digits + (if fraction-digits (str "." fraction-digits) "") + (if exp-data (apply str "E" exp-data) ""))))) + +(def valid-escape-chars + {\\ \\ + \" \" + \/ \/ + \b \backspace + \f \formfeed + \n \newline + \r \return + \t \tab}) + + +;; Defines a JSON escaped string parser. Supports all the normal \n \f \r stuff as well +;; as \uXXXX unicode characters +(defparser EscapedStringParser [] + CHAR (or (and \\ + (one-of valid-escape-chars) -> char + <- (valid-escape-chars char)) + + (and \\ + \u + digits -> d1 + digits -> d2 + digits -> d3 + digits -> d4 + <- (char (std/read-string (str "0x" d1 d2 d3 d4)))) + + (parse-if #(not= % \"))) + + STRING (and \" + (zero+chars CHAR) -> s + \" + <- s)) + +;; Basic JSON parser +(defparser JSONParser [NumberParser EscapedStringParser] + + NULL (sequence "null" <- nil) + TRUE (sequence "true" <- true) + FALSE (sequence "false" <- false) + ARRAY (and \[ + (eat whitespace) + (zero+ (and ENTRY -> e + (maybe \,) + <- e)) -> items + (eat whitespace) + (eat whitespace) + \] + <- items) + MAP-ENTRY (and (eat whitespace) + STRING -> key + (eat whitespace) + \: + ENTRY -> value + (maybe \,) + <- [key value]) + MAP (and \{ + (zero+ MAP-ENTRY) -> items + (eat whitespace) + \} + <- (apply hashmap (apply concat items))) + ENTRY (and + (eat whitespace) + (or NUMBER MAP STRING NULL TRUE FALSE ARRAY) -> val + (eat whitespace) + <- val) + ENTRY-AT-END (and ENTRY -> e + (eat whitespace) + end + <- e)) + +(defn read-string [s] + (let [c (string-cursor s) + result ((:ENTRY-AT-END JSONParser) c)] + (if (failure? result) + (println (current c) (snapshot c)) + result))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 5ca0ef2f..900bdbb3 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -310,7 +310,6 @@ (extend -reduce Nil (fn [self f init] init)) (extend -hash Nil (fn [self] 100000)) (extend -with-meta Nil (fn [self _] nil)) -(extend -at-end? Nil (fn [_] true)) (extend -deref Nil (fn [_] nil)) (extend -contains-key Nil (fn [_ _] false)) @@ -398,13 +397,6 @@ 1111111 3333333))) -(def stacklet->lazy-seq - (fn [k] - (if (-at-end? k) - nil - (cons (-current k) - (lazy-seq* (fn [] (stacklet->lazy-seq (-move-next! k)))))))) - (def = -eq) (extend -seq PersistentVector @@ -1393,17 +1385,6 @@ The new value is thus `(apply f current-value-of-atom args)`." nil ~(nth binding 1 nil))) -(defmacro iterate [binding & body] - (assert (= 2 (count binding)) "binding and collection required") - `(let [i# (iterator ~(second binding))] - (loop [] - (if (at-end? i#) - nil - (let [~(first binding) (current i#)] - ~@body - (move-next! i#) - (recur)))))) - (defmacro dotimes {:doc "Execute the expressions in the body n times." @@ -2314,3 +2295,22 @@ Calling this function on something that is not ISeqable returns a seq with that (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + + +(defn interleave + "Returns a seq of all the items in the input collections interleaved" + ([] ()) + ([c1] (seq c1)) + ([c1 c2] + (lazy-seq + (let [s1 (seq c1) + s2 (seq c2)] + (when (and s1 s2) + (cons (first s1) (cons (first s2) + (interleave (next s1) (next s2)))))))) + ([& colls] + (lazy-seq + (let [ss (map seq colls)] + (when (every? identity ss) + (concat (map first ss) + (apply interleave (map next ss)))))))) diff --git a/pixie/test.pxi b/pixie/test.pxi index 745efa00..2f622977 100644 --- a/pixie/test.pxi +++ b/pixie/test.pxi @@ -92,3 +92,10 @@ (if (= orig res) (pr-str orig) (str (pr-str orig) " = " (pr-str res))))) + + +(defmacro assert-table [pattern expr & vals] + (let [parted (partition (count pattern) vals)] + `(do ~@(for [fact parted] + `(let [~@(interleave pattern fact)] + ~expr))))) diff --git a/tests/pixie/tests/parsers/test-json.pxi b/tests/pixie/tests/parsers/test-json.pxi new file mode 100644 index 00000000..c1d8133d --- /dev/null +++ b/tests/pixie/tests/parsers/test-json.pxi @@ -0,0 +1,11 @@ +(ns pixie.tests.parsers.test-json + (:require [pixie.test :refer :all] + [pixie.parsers.json :as json])) + + + +(deftest test-json-numbers + (assert-table [x y] (assert= (json/read-string x) y) + "1" 1 + "1.0" 1.0 + "0.1" 0.1)) From a2bb0a1b90dffce6e1741dcd70f6fbefc2f34728 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Fri, 10 Apr 2015 23:48:21 +0100 Subject: [PATCH 139/349] Remove some lingering iterator stuff --- pixie/stdlib.pxi | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ee40a1b6..83bda7c0 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -309,7 +309,6 @@ (extend -reduce Nil (fn [self f init] init)) (extend -hash Nil (fn [self] 100000)) (extend -with-meta Nil (fn [self _] nil)) -(extend -at-end? Nil (fn [_] true)) (extend -deref Nil (fn [_] nil)) (extend -contains-key Nil (fn [_ _] false)) @@ -397,13 +396,6 @@ 1111111 3333333))) -(def stacklet->lazy-seq - (fn [k] - (if (-at-end? k) - nil - (cons (-current k) - (lazy-seq* (fn [] (stacklet->lazy-seq (-move-next! k)))))))) - (def = -eq) (extend -seq PersistentVector @@ -1392,18 +1384,6 @@ The new value is thus `(apply f current-value-of-atom args)`." nil ~(nth binding 1 nil))) -(defmacro iterate [binding & body] - (assert (= 2 (count binding)) "binding and collection required") - `(let [i# (iterator ~(second binding))] - (loop [] - (if (at-end? i#) - nil - (let [~(first binding) (current i#)] - ~@body - (move-next! i#) - (recur)))))) - - (defmacro dotimes {:doc "Execute the expressions in the body n times." :examples [["(dotimes [i 3] (println i))" "1\n2\n3\n"]] From 05ca6cc89b52ca07e55e4ac02a8a3d2c7a3fb6df Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Tue, 31 Mar 2015 20:31:55 +0100 Subject: [PATCH 140/349] Implement fs/size and fs/permissions --- pixie/fs.pxi | 60 ++++++++++++++++++++++++++--- tests/pixie/tests/fs/parent/foo.txt | 1 + tests/pixie/tests/test-fs.pxi | 18 +++++++++ 3 files changed, 73 insertions(+), 6 deletions(-) diff --git a/pixie/fs.pxi b/pixie/fs.pxi index 048e6f63..36bec55d 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -1,7 +1,19 @@ (ns pixie.fs (:require [pixie.path :as path] - [pixie.string :as string])) + [pixie.string :as string] + [pixie.ffi-infer :as f])) +(f/with-config {:library "c" + :cxx-flags ["-lc"] + :includes ["sys/stat.h"]} + (f/defc-raw-struct stat [:st_mode :st_size])) + +(def stat-struct stat) + +(f/with-config {:library "c" + :cxx-flags ["-lc"] + :includes ["sys/stat.h"]} + (f/defcfn stat)) (defprotocol IFSPath (path [this] @@ -19,15 +31,16 @@ (basename [this] "Returns the basename of the Filesystem Object") - ;; TODO (permissions [this] "Returns a string of the octal permissions") - (mounted? [this] - "Returns true if the directory is a mounted") - (size [this] - "Returns the size of the file/dir on disk")) + "Returns the size of the file/dir on disk") + + ;; TODO + + (mounted? [this] + "Returns true if the directory is a mounted")) (defprotocol IFile (extension [this] @@ -80,6 +93,29 @@ :else (apply str (interpose "/" (concat (repeat (count diff-b) "..") diff-a))))))) +(defn- assert-existence [f] + (assert (exists? f) (str "No file or directory at \"" (abs f) "\""))) + +(defn- read-stat-field [path field] + (assert-existence path) + (let [s (stat-struct) + _ (stat (abs path) s) + result (field s)] + (dispose! s) + result)) + +(defn- size-of-path [path] + (read-stat-field path :st_size)) + +(defn- permission-string [n] + (apply str + (for [shift [6 3 0]] + (let [mask (bit-shift-left 7 shift) + masked (bit-and mask n)] + (bit-shift-right masked shift))))) + +(defn- permissions-of-path [path] + (permission-string (read-stat-field path :st_mode))) ;; File and Dir are just wrappers around paths. (deftype File [pathz] @@ -99,6 +135,12 @@ (basename [this] (last (string/split (abs this) "/"))) + (size [this] + (size-of-path this)) + + (permissions [this] + (permissions-of-path this)) + IFile ;; TODO: Sort out regex or make strings partitionable. So we can split at ;; #".". @@ -141,6 +183,12 @@ (basename [this] (last (string/split (abs this) "/"))) + (size [this] + (size-of-path this)) + + (permissions [this] + (permissions-of-path pathz)) + IDir (list [this] (vec (map fspath (path/-list-dir pathz)))) diff --git a/tests/pixie/tests/fs/parent/foo.txt b/tests/pixie/tests/fs/parent/foo.txt index e69de29b..257cc564 100644 --- a/tests/pixie/tests/fs/parent/foo.txt +++ b/tests/pixie/tests/fs/parent/foo.txt @@ -0,0 +1 @@ +foo diff --git a/tests/pixie/tests/test-fs.pxi b/tests/pixie/tests/test-fs.pxi index 5a8ba3b2..c02d664a 100644 --- a/tests/pixie/tests/test-fs.pxi +++ b/tests/pixie/tests/test-fs.pxi @@ -105,3 +105,21 @@ (t/assert= (fs/exists? real-dir) true) (t/assert= (fs/exists? fake-dir) false) (t/assert= (fs/exists? fake-file) false))) + +(t/deftest test-size + (let [file-with-content (fs/file "tests/pixie/tests/fs/parent/foo.txt") + file-without-content (fs/file "tests/pixie/tests/fs/parent/bar.txt") + fake-file (fs/file "tests/pixie/tests/fs/parent/fake-file")] + (t/assert= (fs/size file-with-content) 4) + (t/assert= (fs/size file-without-content) 0) + (t/assert-throws? (fs/size fake-file)))) + +(t/deftest test-permissions + (let [file (fs/file "tests/pixie/tests/fs/parent/foo.txt") + fake-file (fs/file "tests/pixie/tests/fs/parent/fake-file")] + ; because Travis seems to change the permissions of some files... + (let [perms (fs/permissions file)] + (t/assert= (count perms) 3) + (t/assert (instance? String perms)) + (t/assert= (set (seq perms)) #{\6 \4})) + (t/assert-throws? (fs/permissions fake-file)))) From 35ac3a67e6761e3392a1f0a5810ab849f3974bdc Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Fri, 10 Apr 2015 22:48:43 +0100 Subject: [PATCH 141/349] Implement size and permissions using libuv --- pixie/fs.pxi | 29 +++++++---------------------- pixie/io.pxi | 26 ++++---------------------- pixie/uv.pxi | 28 ++++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 46 deletions(-) diff --git a/pixie/fs.pxi b/pixie/fs.pxi index 36bec55d..7a943857 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -1,19 +1,7 @@ (ns pixie.fs (:require [pixie.path :as path] [pixie.string :as string] - [pixie.ffi-infer :as f])) - -(f/with-config {:library "c" - :cxx-flags ["-lc"] - :includes ["sys/stat.h"]} - (f/defc-raw-struct stat [:st_mode :st_size])) - -(def stat-struct stat) - -(f/with-config {:library "c" - :cxx-flags ["-lc"] - :includes ["sys/stat.h"]} - (f/defcfn stat)) + [pixie.uv :as uv])) (defprotocol IFSPath (path [this] @@ -96,16 +84,12 @@ (defn- assert-existence [f] (assert (exists? f) (str "No file or directory at \"" (abs f) "\""))) -(defn- read-stat-field [path field] - (assert-existence path) - (let [s (stat-struct) - _ (stat (abs path) s) - result (field s)] - (dispose! s) - result)) +(uv/defuvfsfn fs-size pixie.uv/uv_fs_stat [file] :statbuf.st_size) +(uv/defuvfsfn fs-mode pixie.uv/uv_fs_stat [file] :statbuf.st_mode) (defn- size-of-path [path] - (read-stat-field path :st_size)) + (assert-existence path) + (fs-size (abs path))) (defn- permission-string [n] (apply str @@ -115,7 +99,8 @@ (bit-shift-right masked shift))))) (defn- permissions-of-path [path] - (permission-string (read-stat-field path :st_mode))) + (assert-existence path) + (permission-string (fs-mode (abs path)))) ;; File and Dir are just wrappers around paths. (deftype File [pathz] diff --git a/pixie/io.pxi b/pixie/io.pxi index aa868411..dabeac54 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -6,28 +6,10 @@ [pixie.ffi :as ffi] [pixie.ffi-infer :as ffi-infer])) -(defmacro defuvfsfn [nm args return] - `(defn ~nm ~args - (let [f (fn [k#] - (let [cb# (atom nil)] - (reset! cb# (ffi/ffi-prep-callback uv/uv_fs_cb - (fn [req#] - (try - (st/run-and-process k# (~return (pixie.ffi/cast req# uv/uv_fs_t))) - (uv/uv_fs_req_cleanup req#) - (-dispose! @cb#) - (catch e (println e)))))) - (~(symbol (str "pixie.uv/uv_" (name nm))) - (uv/uv_default_loop) - (uv/uv_fs_t) - ~@args - @cb#)))] - (st/call-cc f)))) - -(defuvfsfn fs_open [path flags mode] :result) -(defuvfsfn fs_read [file bufs nbufs offset] :result) -(defuvfsfn fs_write [file bufs nbufs offset] :result) -(defuvfsfn fs_close [file] :result) +(uv/defuvfsfn fs_open [path flags mode] :result) +(uv/defuvfsfn fs_read [file bufs nbufs offset] :result) +(uv/defuvfsfn fs_write [file bufs nbufs offset] :result) +(uv/defuvfsfn fs_close [file] :result) (def DEFAULT-BUFFER-SIZE 1024) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 210a63bd..792d81a4 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -1,5 +1,6 @@ (ns pixie.uv - (:require [pixie.ffi-infer :as f])) + (:require [pixie.ffi :as ffi] + [pixie.ffi-infer :as f])) (f/with-config {:library "uv" :includes ["uv.h"]} @@ -58,7 +59,9 @@ :fs_type :path :result - :ptr]) + :ptr + :statbuf.st_size + :statbuf.st_mode]) (f/defcstruct uv_timespec_t [:tv_sec :tv_nsec]) (f/defcstruct uv_stat_t [:st_dev @@ -214,3 +217,24 @@ (if (neg? result) (throw (str "UV Error: " (uv_err_name result))) result)) + +(defmacro defuvfsfn + ([nm args return] + (defuvfsfn nm (symbol (str "pixie.uv/uv_" (name nm))) args return)) + ([nm uv-fn args return] + `(defn ~nm ~args + (let [f (fn [k#] + (let [cb# (atom nil)] + (reset! cb# (ffi/ffi-prep-callback uv_fs_cb + (fn [req#] + (try + (pixie.stacklets/run-and-process k# (~return (pixie.ffi/cast req# uv_fs_t))) + (uv_fs_req_cleanup req#) + (-dispose! @cb#) + (catch e (println e)))))) + (~uv-fn + (uv_default_loop) + (uv_fs_t) + ~@args + @cb#)))] + (pixie.stacklets/call-cc f))))) From 8f251d03ad725dd7795adcda60bcbf387ae19dad Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Mon, 13 Apr 2015 19:23:02 +0100 Subject: [PATCH 142/349] Add a way to get the size of a CStructType --- pixie/vm/libs/ffi.py | 11 +++++++++++ tests/pixie/tests/test-ffi.pxi | 3 +++ 2 files changed, 14 insertions(+) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 0d346472..6fbc53a1 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -550,6 +550,9 @@ def get_type(self, nm): return tp + def get_size(self): + return self._size + def cast_to(self, frm): return CStruct(self, frm.raw_data()) @@ -768,6 +771,14 @@ def c_cast(frm, to): return to.cast_to(frm) +@as_var("pixie.ffi", "struct-size") +def struct_size(tp): + """(struct-size tp) + Gives the size of the given CStruct type tp, in bytes.""" + if not isinstance(tp, CStructType): + runtime_error(u"Expected a CStruct type to get the size of, got " + rt.name(rt.str(tp))) + + return rt.wrap(tp.get_size()) @extend(proto._val_at, CStructType.base_type) def val_at(self, k, not_found): diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index 8ea60649..beaaa079 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -55,3 +55,6 @@ (dotimes [x (dec MAX)] (t/assert (> (pixie.ffi/unpack buf x CUInt8) (pixie.ffi/unpack buf (inc x) CUInt8))))))) + +(t/deftest test-size + (t/assert= (pixie.ffi/struct-size (pixie.ffi/c-struct "struct" 1234 [])) 1234)) From 8025418a9416b49a563183a6d3cba77c80fdd938 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 13 Apr 2015 16:00:18 -0600 Subject: [PATCH 143/349] more tests for the json parser --- pixie/parsers/json.pxi | 2 +- tests/pixie/tests/parsers/test-json.pxi | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/pixie/parsers/json.pxi b/pixie/parsers/json.pxi index c870a8c7..56a21989 100644 --- a/pixie/parsers/json.pxi +++ b/pixie/parsers/json.pxi @@ -13,7 +13,7 @@ (parse-if (set "123456789")) -> first (zero+chars digits) -> rest <- (str first rest)) - (and \0)) + (and \0 <- "0")) -> integer-digits (maybe (and \. diff --git a/tests/pixie/tests/parsers/test-json.pxi b/tests/pixie/tests/parsers/test-json.pxi index c1d8133d..3d03979d 100644 --- a/tests/pixie/tests/parsers/test-json.pxi +++ b/tests/pixie/tests/parsers/test-json.pxi @@ -8,4 +8,26 @@ (assert-table [x y] (assert= (json/read-string x) y) "1" 1 "1.0" 1.0 - "0.1" 0.1)) + "0.1" 0.1 + "1.1" 1.1 + "1234.5678" 1234.5678 + + "-1" -1 + "-0.1" -0.1 + "-1.1" -1.1 + "-1234.5678" -1234.5678 + "1e1" 1e1)) + +(deftest test-vectors + (assert-table [x y] (assert= (json/read-string x) y) + "[]" [] + "[null]" [nil] + "[1, 2]" [1 2] + "[1, 1.0, null]" [1 1.0 nil] + "[\"foo\", 42]" ["foo" 42])) + +(deftest test-maps + (assert-table [x y] (assert= (json/read-string x) y) + "{\"foo\": 42}" {"foo", 42} + "{\"foo\": 42, \"bar\":null}" {"foo" 42 + "bar" nil})) From 57ea3d9235aa5548fc166ab8e857490f40f0f569 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 13 Apr 2015 20:48:08 -0600 Subject: [PATCH 144/349] start of tcp support --- pixie/io/tcp.pxi | 41 +++++++++++++++++++++++++++++++ pixie/stacklets.pxi | 13 ++++++++++ tests/pixie/tests/io/test-tcp.pxi | 6 +++++ 3 files changed, 60 insertions(+) create mode 100644 pixie/io/tcp.pxi create mode 100644 tests/pixie/tests/io/test-tcp.pxi diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi new file mode 100644 index 00000000..c32c9d62 --- /dev/null +++ b/pixie/io/tcp.pxi @@ -0,0 +1,41 @@ +(ns pixie.io.tcp + (:require [pixie.stacklets :as st] + [pixie.uv :as uv] + [pixie.ffi :as ffi])) + +(defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb]) + +(defrecord TCPStream [uv-client]) + +(defn launch-tcp-client-from-server [svr] + (assert (instance? TCPServer svr) "Requires a TCPServer as the first argument") + (let [client (uv/uv_tcp_t)] + (uv/uv_tcp_init (uv/uv_default_loop) client) + (if (= 0 (uv/uv_accept (:uv-server svr) client)) + (do (st/spawn-from-non-stacklet #((:on-connect svr) + (->TCPStream client))) + svr) + (do (uv/uv_close client nil) + svr)))) + + + +(defn tcp-server [ip port on-connection] + (assert (string? ip) "Ip should be a string") + (assert (integer? port) "Port should be a int") + + (let [server (uv/uv_tcp_t) + bind-addr (uv/sockaddr_in) + _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) + on-new-connetion (atom nil) + tcp-server (->TCPServer ip port on-connection server bind-addr on-new-connetion)] + (reset! on-new-connetion + (ffi/ffi-prep-callback + uv/uv_connection_cb + (fn [server status] + (launch-tcp-client-from-server tcp-server)))) + (uv/uv_tcp_init (uv/uv_default_loop) server) + (uv/uv_tcp_bind server bind-addr 0) + (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) + (st/yield-control) + tcp-server)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index c3d2b236..378c46cf 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -93,6 +93,19 @@ (println e))))))) +(defn spawn-from-non-stacklet [f] + (let [s (new-stacklet (fn [h _] + (try + (reset! stacklet-loop-h h) + (swap! running-threads inc) + (f) + (swap! running-threads dec) + (call-cc (fn [_] nil)) + (catch e + (println e)))))] + (-run-later + (fn [] + (run-and-process s))))) (defn -with-stacklets [fn] diff --git a/tests/pixie/tests/io/test-tcp.pxi b/tests/pixie/tests/io/test-tcp.pxi new file mode 100644 index 00000000..84a9848d --- /dev/null +++ b/tests/pixie/tests/io/test-tcp.pxi @@ -0,0 +1,6 @@ +(ns pixie.test.io.test-tcp + (:require [pixie.io.tcp :refer :all] + [pixie.async :as async])) + + +(tcp-server "0.0.0.0" 4242 #(println "FOOOOO " %)) From 61bea2f9b49028620881ccefa0e40c700818b656 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 14 Apr 2015 05:57:58 -0600 Subject: [PATCH 145/349] make everything inherit from Object --- pixie/vm/object.py | 13 +++++++++---- tests/pixie/tests/test-object.pxi | 9 +++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 99123bd3..e986bbbe 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -67,14 +67,18 @@ def get_type_by_name(nm): return _type_registry.get_by_name(nm) class Type(Object): - def __init__(self, name, parent = None): + def __init__(self, name, parent=None, object_inited=True): assert isinstance(name, unicode), u"Type names must be unicode" _type_registry.register_type(name, self) self._name = name - self._parent = parent - if parent is not None: + + if object_inited: + if parent is None: + parent = Object._type + parent.add_subclass(self) + self._parent = parent self._subclasses = [] def name(self): @@ -89,7 +93,8 @@ def add_subclass(self, tp): def subclasses(self): return self._subclasses -Type._type = Type(u"Type") +Object._type = Type(u"pixie.stdlib.Object", None, False) +Type._type = Type(u"pixie.stdlib.Type") @jit.elidable_promote() def istypeinstance(obj, t): diff --git a/tests/pixie/tests/test-object.pxi b/tests/pixie/tests/test-object.pxi index 810470b0..3a805042 100644 --- a/tests/pixie/tests/test-object.pxi +++ b/tests/pixie/tests/test-object.pxi @@ -4,3 +4,12 @@ (t/deftest test-hash (t/assert= (hash (var foo)) (hash (var foo))) (t/assert (not= (hash (var foo)) (hash (var bar))))) + + +(deftype FooType []) + +(t/deftest test-everything-is-an-object + (t/assert (instance? Object 42)) + (t/assert (instance? Object [])) + (t/assert (instance? Object "Foo")) + (t/assert (instance? Object FooType))) From 64f7cbc1da3521791c29b0dde10e41d6e71d85ff Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 14 Apr 2015 06:20:56 -0600 Subject: [PATCH 146/349] removed some duplicate code, moved parsers.* namespaces to parser.* --- pixie/parser.pxi | 109 +---------------------- pixie/parsers/json.pxi | 111 ------------------------ tests/pixie/tests/parsers/test-json.pxi | 33 ------- 3 files changed, 2 insertions(+), 251 deletions(-) delete mode 100644 pixie/parsers/json.pxi delete mode 100644 tests/pixie/tests/parsers/test-json.pxi diff --git a/pixie/parser.pxi b/pixie/parser.pxi index 7718bd27..e1b12a26 100644 --- a/pixie/parser.pxi +++ b/pixie/parser.pxi @@ -198,7 +198,8 @@ [inherits & rules] (let [parted (apply merge (conj (mapv (fn [sym] - (-> sym resolve deref ::forms)) inherits) + (::forms (deref (resolve-in *ns* sym)))) + inherits) (-parse-parser-args rules))) rules (apply concat parted) syms (keys parted)] @@ -309,109 +310,3 @@ (def digits (parse-if (set "1234567890"))) (def whitespace (parse-if #{\newline \return \space \tab})) - -;; Basic numeric parser. Supports integers (1, 2, 43), decimals (0.1, 1.1, 1000.11) and exponents (1e42, 1E-2) -(defparser NumberParser [] - NUMBER (and (maybe \-) - -> sign - - (or (and - (parse-if (set "123456789")) -> first - (zero+chars digits) -> rest - <- (str first rest)) - (and \0)) - -> integer-digits - - (maybe (and \. - (one+chars digits) -> digits - <- digits)) - -> fraction-digits - - - (maybe (and (parse-if (set "eE")) - (maybe (parse-if (set "-+"))) -> exp-sign - (one+chars digits) -> exp-digits - <- [(s/or exp-sign "") exp-digits])) - -> exp-data - - <- (read-string (str (s/or sign "") - integer-digits - (if fraction-digits (str "." fraction-digits) "") - (if exp-data (apply str "E" exp-data) ""))))) - -(def valid-escape-chars - {\\ \\ - \" \" - \/ \/ - \b \backspace - \f \formfeed - \n \newline - \r \return - \t \tab}) - - -;; Defines a JSON escaped string parser. Supports all the normal \n \f \r stuff as well -;; as \uXXXX unicode characters -(defparser EscapedStringParser [] - CHAR (or (and \\ - (one-of valid-escape-chars) -> char - <- (valid-escape-chars char)) - - (and \\ - \u - digits -> d1 - digits -> d2 - digits -> d3 - digits -> d4 - <- (char (read-string (str "0x" d1 d2 d3 d4)))) - - (parse-if #(not= % \"))) - - STRING (and \" - (zero+chars CHAR) -> s - \" - <- s)) - -;; Basic JSON parser -(defparser JSONParser [NumberParser EscapedStringParser] - - NULL (sequence "null" <- nil) - TRUE (sequence "true" <- true) - FALSE (sequence "false" <- false) - ARRAY (and \[ - (eat whitespace) - (zero+ (and ENTRY -> e - (maybe \,) - <- e)) -> items - (eat whitespace) - (eat whitespace) - \] - <- items) - MAP-ENTRY (and (eat whitespace) - STRING -> key - (eat whitespace) - \: - ENTRY -> value - (maybe \,) - <- [key value]) - MAP (and \{ - (zero+ MAP-ENTRY) -> items - (eat whitespace) - \} - <- (apply hashmap (apply concat items))) - ENTRY (and - (eat whitespace) - (or NUMBER MAP STRING NULL TRUE FALSE ARRAY) -> val - (eat whitespace) - <- val) - ENTRY-AT-END (and ENTRY -> e - (eat whitespace) - end - <- e)) - -(defn read-json-string [s] - (let [c (string-cursor s) - result ((:ENTRY-AT-END JSONParser) c)] - (if (failure? result) - (println (current c) (snapshot c)) - result))) diff --git a/pixie/parsers/json.pxi b/pixie/parsers/json.pxi deleted file mode 100644 index 56a21989..00000000 --- a/pixie/parsers/json.pxi +++ /dev/null @@ -1,111 +0,0 @@ -(ns pixie.parsers.json - (:require [pixie.parser :refer :all] - [pixie.stdlib :as std])) - - - -;; Basic numeric parser. Supports integers (1, 2, 43), decimals (0.1, 1.1, 1000.11) and exponents (1e42, 1E-2) -(defparser NumberParser [] - NUMBER (and (maybe \-) - -> sign - - (or (and - (parse-if (set "123456789")) -> first - (zero+chars digits) -> rest - <- (str first rest)) - (and \0 <- "0")) - -> integer-digits - - (maybe (and \. - (one+chars digits) -> digits - <- digits)) - -> fraction-digits - - - (maybe (and (parse-if (set "eE")) - (maybe (parse-if (set "-+"))) -> exp-sign - (one+chars digits) -> exp-digits - <- [(std/or exp-sign "") exp-digits])) - -> exp-data - - <- (std/read-string (str (std/or sign "") - integer-digits - (if fraction-digits (str "." fraction-digits) "") - (if exp-data (apply str "E" exp-data) ""))))) - -(def valid-escape-chars - {\\ \\ - \" \" - \/ \/ - \b \backspace - \f \formfeed - \n \newline - \r \return - \t \tab}) - - -;; Defines a JSON escaped string parser. Supports all the normal \n \f \r stuff as well -;; as \uXXXX unicode characters -(defparser EscapedStringParser [] - CHAR (or (and \\ - (one-of valid-escape-chars) -> char - <- (valid-escape-chars char)) - - (and \\ - \u - digits -> d1 - digits -> d2 - digits -> d3 - digits -> d4 - <- (char (std/read-string (str "0x" d1 d2 d3 d4)))) - - (parse-if #(not= % \"))) - - STRING (and \" - (zero+chars CHAR) -> s - \" - <- s)) - -;; Basic JSON parser -(defparser JSONParser [NumberParser EscapedStringParser] - - NULL (sequence "null" <- nil) - TRUE (sequence "true" <- true) - FALSE (sequence "false" <- false) - ARRAY (and \[ - (eat whitespace) - (zero+ (and ENTRY -> e - (maybe \,) - <- e)) -> items - (eat whitespace) - (eat whitespace) - \] - <- items) - MAP-ENTRY (and (eat whitespace) - STRING -> key - (eat whitespace) - \: - ENTRY -> value - (maybe \,) - <- [key value]) - MAP (and \{ - (zero+ MAP-ENTRY) -> items - (eat whitespace) - \} - <- (apply hashmap (apply concat items))) - ENTRY (and - (eat whitespace) - (or NUMBER MAP STRING NULL TRUE FALSE ARRAY) -> val - (eat whitespace) - <- val) - ENTRY-AT-END (and ENTRY -> e - (eat whitespace) - end - <- e)) - -(defn read-string [s] - (let [c (string-cursor s) - result ((:ENTRY-AT-END JSONParser) c)] - (if (failure? result) - (println (current c) (snapshot c)) - result))) diff --git a/tests/pixie/tests/parsers/test-json.pxi b/tests/pixie/tests/parsers/test-json.pxi deleted file mode 100644 index 3d03979d..00000000 --- a/tests/pixie/tests/parsers/test-json.pxi +++ /dev/null @@ -1,33 +0,0 @@ -(ns pixie.tests.parsers.test-json - (:require [pixie.test :refer :all] - [pixie.parsers.json :as json])) - - - -(deftest test-json-numbers - (assert-table [x y] (assert= (json/read-string x) y) - "1" 1 - "1.0" 1.0 - "0.1" 0.1 - "1.1" 1.1 - "1234.5678" 1234.5678 - - "-1" -1 - "-0.1" -0.1 - "-1.1" -1.1 - "-1234.5678" -1234.5678 - "1e1" 1e1)) - -(deftest test-vectors - (assert-table [x y] (assert= (json/read-string x) y) - "[]" [] - "[null]" [nil] - "[1, 2]" [1 2] - "[1, 1.0, null]" [1 1.0 nil] - "[\"foo\", 42]" ["foo" 42])) - -(deftest test-maps - (assert-table [x y] (assert= (json/read-string x) y) - "{\"foo\": 42}" {"foo", 42} - "{\"foo\": 42, \"bar\":null}" {"foo" 42 - "bar" nil})) From e976478213aab3ed3e5a6672e6cea6fb948434b4 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 14 Apr 2015 22:12:23 -0600 Subject: [PATCH 147/349] tcp server works, needs quite a bit of cleanup --- pixie/io/tcp.pxi | 59 +++++++++++++++++++++++++++++-- pixie/stdlib.pxi | 41 +++++++++++++++++++-- pixie/uv.pxi | 5 ++- tests/pixie/tests/io/test-tcp.pxi | 11 +++++- 4 files changed, 110 insertions(+), 6 deletions(-) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index c32c9d62..081aa480 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -1,11 +1,66 @@ (ns pixie.io.tcp (:require [pixie.stacklets :as st] + [pixie.streams :refer [IInputStream read IOutputStream write]] [pixie.uv :as uv] [pixie.ffi :as ffi])) (defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb]) -(defrecord TCPStream [uv-client]) +(defn -prep-uv-buffer-fn [buf read-bytes] + (ffi/ffi-prep-callback + uv/uv_alloc_cb + (fn [handle suggested-size uv-buf] + (try + (let [casted (ffi/cast uv-buf uv/uv_buf_t)] + (println "Alloc " handle suggested-size buf read-bytes) + (ffi/set! casted :base buf) + (ffi/set! casted :len (min suggested-size + (buffer-capacity buf) + read-bytes))) + (catch ex (println ex)))))) + +(deftype TCPStream [uv-client uv-write-buf] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [alloc-cb (-prep-uv-buffer-fn buffer len) + read-cb (atom nil)] + (st/call-cc (fn [k] + (reset! read-cb (ffi/ffi-prep-callback + uv/uv_read_cb + (fn [stream nread uv-buf] + (println "-<<< nread <-- " nread) + (set-buffer-count! buffer nread) + (try + (dispose! alloc-cb) + (dispose! @read-cb) + ;(dispose! uv-buf) + (uv/uv_read_stop stream) + (st/run-and-process k nread) + (catch ex + (println ex)))))) + (uv/uv_read_start uv-client alloc-cb @read-cb))))) + IOutputStream + (write [this buffer] + (let [write-cb (atom nil) + uv_write (uv/uv_write_t)] + (println "writing " (count buffer)) + (ffi/set! uv-write-buf :base buffer) + (ffi/set! uv-write-buf :len (count buffer)) + (st/call-cc + (fn [k] + (reset! write-cb (ffi/ffi-prep-callback + uv/uv_write_cb + (fn [req status] + (println status "<<-- status") + (try + (dispose! @write-cb) + ;(uv/uv_close uv_write st/close_cb) + (st/run-and-process k status) + (catch ex + (println ex)))))) + (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb)))))) (defn launch-tcp-client-from-server [svr] (assert (instance? TCPServer svr) "Requires a TCPServer as the first argument") @@ -13,7 +68,7 @@ (uv/uv_tcp_init (uv/uv_default_loop) client) (if (= 0 (uv/uv_accept (:uv-server svr) client)) (do (st/spawn-from-non-stacklet #((:on-connect svr) - (->TCPStream client))) + (->TCPStream client (uv/uv_buf_t)))) svr) (do (uv/uv_close client nil) svr)))) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 83bda7c0..ef4683f2 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -282,6 +282,7 @@ (extend -invoke Code -invoke) (extend -invoke NativeFn -invoke) (extend -invoke VariadicCode -invoke) +(extend -invoke MultiArityFn -invoke) (extend -invoke Closure -invoke) (extend -invoke Var -invoke) (extend -invoke PolymorphicFn -invoke) @@ -1804,7 +1805,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} {:doc "Filter the collection for elements matching the predicate." :signatures [[pred] [pred coll]] :added "0.1"} - ([pred] + ([pred] (fn [xf] (fn ([] (xf)) @@ -1858,7 +1859,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (xf acc result) acc)))))) ([f coll] - (lazy-seq + (lazy-seq (when-let [s (seq coll)] (let [[first & rest] s result (f first)] @@ -2279,6 +2280,11 @@ Calling this function on something that is not ISeqable returns a seq with that (defn -set-*e [e] (def *e e)) +(def hash-map hashmap) + +(defn zipmap [a b] + (into {} (map vector a b))) + (extend -str Environment (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] @@ -2288,3 +2294,34 @@ Calling this function on something that is not ISeqable returns a seq with that (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + +(defn interleave + "Returns a seq of all the items in the input collections interleaved" + ([] ()) + ([c1] (seq c1)) + ([c1 c2] + (lazy-seq + (let [s1 (seq c1) + s2 (seq c2)] + (when (and s1 s2) + (cons (first s1) (cons (first s2) + (interleave (next s1) (next s2)))))))) + ([& colls] + (lazy-seq + (let [ss (map seq colls)] + (when (every? identity ss) + (concat (map first ss) + (apply interleave (map next ss)))))))) + + +(defn min + "Returns the smallest of all the arguments to this function. Assumes arguments are numeric" + ([x] x) + ([x y] (if (< x y) x y)) + ([x y & zs] (apply min (min x y) zs))) + +(defn max + "Returns the largest of all the arguments to this function. Assumes arguments are numeric" + ([x] x) + ([x y] (if (> x y) x y)) + ([x y & zs] (apply min (min x y) zs))) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 792d81a4..474901bb 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -198,11 +198,14 @@ (f/defcfn uv_accept) (f/defcfn uv_tcp_connect) (f/defcfn uv_tcp_keepalive) + (f/defcfn uv_read_start) + (f/defcfn uv_read_stop) (f/defccallback uv_connection_cb) (f/defccallback uv_connect_cb) - ) + (f/defccallback uv_alloc_cb) + (f/defccallback uv_read_cb)) (defn new-fs-buf [size] diff --git a/tests/pixie/tests/io/test-tcp.pxi b/tests/pixie/tests/io/test-tcp.pxi index 84a9848d..fadb3f64 100644 --- a/tests/pixie/tests/io/test-tcp.pxi +++ b/tests/pixie/tests/io/test-tcp.pxi @@ -1,6 +1,15 @@ (ns pixie.test.io.test-tcp (:require [pixie.io.tcp :refer :all] + [pixie.io :refer [read write]] + [pixie.stacklets :as st] [pixie.async :as async])) +(defn on-client [conn] + (let [b (buffer 1024)] + (read conn b 1024) + (write conn b) + (dotimes [x 1000] + (st/yield-control)) + (println "Done Writing.."))) -(tcp-server "0.0.0.0" 4242 #(println "FOOOOO " %)) +(tcp-server "0.0.0.0" 4242 on-client) From 0cccf33e7dda91adedff80df03d8e7af50c1d142 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 16 Apr 2015 15:43:32 -0600 Subject: [PATCH 148/349] implemented a basic tcp server and tests --- pixie/io.pxi | 43 ++++++++++++----------------- pixie/io/tcp.pxi | 45 ++++++++++++++++++++++++++----- pixie/stacklets.pxi | 11 +++++++- pixie/stdlib.pxi | 2 +- pixie/streams.pxi | 3 +++ pixie/uv.pxi | 2 ++ tests/pixie/tests/io/test-tcp.pxi | 45 ++++++++++++++++++++++++------- 7 files changed, 106 insertions(+), 45 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index dabeac54..20dd2d64 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -111,6 +111,11 @@ IDisposable (-dispose! [this] (set-buffer-count! buffer idx) + (write downstream buffer)) + IFlushableStream + (flush [this] + (set-buffer-count! buffer idx) + (set-field! this :idx 0) (write downstream buffer))) (deftype BufferedInputStream [upstream idx buffer] @@ -124,16 +129,21 @@ val)) IDisposable (-dispose! [this] - (dispose! upstream) (dispose! buffer))) -(defn buffered-output-stream [downstream size] - (->BufferedOutputStream downstream 0 (buffer size))) +(defn buffered-output-stream + ([downstream] + (buffered-output-stream downstream DEFAULT-BUFFER-SIZE)) + ([downstream size] + (->BufferedOutputStream downstream 0 (buffer size)))) -(defn buffered-input-stream [upstream size] - (let [b (buffer size)] - (set-buffer-count! b size) - (->BufferedInputStream upstream size b))) +(defn buffered-input-stream + ([upstream] + (buffered-input-stream upstream DEFAULT-BUFFER-SIZE)) + ([upstream size] + (let [b (buffer size)] + (set-buffer-count! b size) + (->BufferedInputStream upstream size b)))) (defn throw-on-error [result] (when (neg? result) @@ -180,25 +190,6 @@ (defn run-command [command] (st/apply-blocking io-blocking/run-command command)) -(comment - - (defn tcp-server [ip port on-connection] - (assert (string? ip) "Ip should be a string") - (assert (integer? port) "Port should be a int") - (let [server (uv/uv_tcp_t) - bind-addr (uv/sockaddr_in) - _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) - on-new-connetion (atom nil)] - (reset! on-new-connetion - (ffi/ffi-prep-callback - uv/uv_connection_cb - (fn [server status] - (when (not (= status -1)) - (println "Got Client!!!!!!!"))))) - (uv/uv_tcp_init (uv/uv_default_loop) server) - (uv/uv_tcp_bind server bind-addr 0) - (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) - (st/yield-control)))) (comment (st/apply-blocking println "FROM OTHER THREAD <---!!!!!") diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 081aa480..95614f7e 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -4,7 +4,12 @@ [pixie.uv :as uv] [pixie.ffi :as ffi])) -(defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb]) +(defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb] + IDisposable + (-dispose! [this] + (uv/uv_close uv-server st/close_cb) + (dispose! @on-connection-cb) + (dispose! bind-addr))) (defn -prep-uv-buffer-fn [buf read-bytes] (ffi/ffi-prep-callback @@ -12,7 +17,6 @@ (fn [handle suggested-size uv-buf] (try (let [casted (ffi/cast uv-buf uv/uv_buf_t)] - (println "Alloc " handle suggested-size buf read-bytes) (ffi/set! casted :base buf) (ffi/set! casted :len (min suggested-size (buffer-capacity buf) @@ -30,14 +34,15 @@ (reset! read-cb (ffi/ffi-prep-callback uv/uv_read_cb (fn [stream nread uv-buf] - (println "-<<< nread <-- " nread) (set-buffer-count! buffer nread) (try (dispose! alloc-cb) (dispose! @read-cb) ;(dispose! uv-buf) (uv/uv_read_stop stream) - (st/run-and-process k nread) + (st/run-and-process k (or + (st/exception-on-uv-error nread) + nread)) (catch ex (println ex)))))) (uv/uv_read_start uv-client alloc-cb @read-cb))))) @@ -45,7 +50,6 @@ (write [this buffer] (let [write-cb (atom nil) uv_write (uv/uv_write_t)] - (println "writing " (count buffer)) (ffi/set! uv-write-buf :base buffer) (ffi/set! uv-write-buf :len (count buffer)) (st/call-cc @@ -53,14 +57,17 @@ (reset! write-cb (ffi/ffi-prep-callback uv/uv_write_cb (fn [req status] - (println status "<<-- status") (try (dispose! @write-cb) ;(uv/uv_close uv_write st/close_cb) (st/run-and-process k status) (catch ex (println ex)))))) - (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb)))))) + (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) + IDisposable + (-dispose! [this] + (dispose! uv-write-buf) + (uv/uv_close uv-client st/close_cb))) (defn launch-tcp-client-from-server [svr] (assert (instance? TCPServer svr) "Requires a TCPServer as the first argument") @@ -94,3 +101,27 @@ (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) (st/yield-control) tcp-server)) + + +(defn tcp-client [ip port] + (let [client-addr (uv/sockaddr_in) + uv-connect (uv/uv_connect_t) + client (uv/uv_tcp_t) + cb (atom nil)] + (uv/throw-on-error (uv/uv_ip4_addr ip port client-addr)) + (uv/uv_tcp_init (uv/uv_default_loop) client) + (st/call-cc (fn [k] + (reset! cb (ffi/ffi-prep-callback + uv/uv_connect_cb + (fn [_ status] + (try + (dispose! @cb) + (dispose! uv-connect) + (dispose! client-addr) + (st/run-and-process k (or (st/exception-on-uv-error status) + (->TCPStream client (uv/uv_buf_t)))) + (catch ex + (println ex)))))) + (uv/uv_tcp_connect uv-connect client client-addr @cb))) + + )) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 378c46cf..30e0ada3 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -16,6 +16,8 @@ ;; Yield +(defrecord ThrowException [ex]) + (defn run-and-process ([k] (run-and-process k nil)) @@ -23,12 +25,19 @@ (let [[h f] (k val)] (f h)))) +(defn exception-on-uv-error [result] + (when (neg? result) + (->ThrowException (str "UV Error: " (uv/uv_err_name result))))) + + (defn call-cc [f] (let [frames (-get-current-var-frames nil) [h val] (@stacklet-loop-h f)] (reset! stacklet-loop-h h) (-set-current-var-frames nil frames) - val)) + (if (instance? ThrowException val) + (throw (:ex val)) + val))) (defn -run-later [f] (let [a (uv/uv_async_t) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ef4683f2..3478b185 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2324,4 +2324,4 @@ Calling this function on something that is not ISeqable returns a seq with that "Returns the largest of all the arguments to this function. Assumes arguments are numeric" ([x] x) ([x y] (if (> x y) x y)) - ([x y & zs] (apply min (min x y) zs))) + ([x y & zs] (apply max (max x y) zs))) diff --git a/pixie/streams.pxi b/pixie/streams.pxi index b39fa4f3..1bdf358f 100644 --- a/pixie/streams.pxi +++ b/pixie/streams.pxi @@ -1,5 +1,8 @@ (ns pixie.streams) +(defprotocol IFlushableStream + (flush [this] "Flushes all buffers in this stream and applies writes to any parent streams")) + (defprotocol IInputStream (read [this buffer len] "Reads multiple bytes into a buffer, returns the number of bytes read")) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 474901bb..67f93cdd 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -124,6 +124,8 @@ (f/defconst UV_DIRENT_CHAR) (f/defconst UV_DIRENT_BLOCK) + (f/defconst UV_EOF) + (f/defcstruct uv_dirent_t [:name :type]) diff --git a/tests/pixie/tests/io/test-tcp.pxi b/tests/pixie/tests/io/test-tcp.pxi index fadb3f64..a86439a2 100644 --- a/tests/pixie/tests/io/test-tcp.pxi +++ b/tests/pixie/tests/io/test-tcp.pxi @@ -1,15 +1,40 @@ (ns pixie.test.io.test-tcp (:require [pixie.io.tcp :refer :all] - [pixie.io :refer [read write]] + [pixie.io :refer [buffered-input-stream buffered-output-stream read-byte write-byte]] + [pixie.streams :refer :all] [pixie.stacklets :as st] - [pixie.async :as async])) + [pixie.async :as async] + [pixie.uv :as uv] + [pixie.test :refer :all])) -(defn on-client [conn] - (let [b (buffer 1024)] - (read conn b 1024) - (write conn b) - (dotimes [x 1000] - (st/yield-control)) - (println "Done Writing.."))) +(deftest test-echo-server + (let [client-done (async/promise) + on-client (fn on-client [conn] + (let [in (buffered-input-stream conn) + out (buffered-output-stream conn)] + (try + (loop [] + (let [val (read-byte in)] + (write-byte out val) + (flush out) + (recur))) + (catch ex + (dispose! in) + (dispose! out) -(tcp-server "0.0.0.0" 4242 on-client) + (dispose! conn) + (client-done true))))) + + server (tcp-server "0.0.0.0" 4242 on-client)] + + (let [client-stream (tcp-client "127.0.0.1" 4242) + in (buffered-input-stream client-stream) + out (buffered-output-stream client-stream)] + + (dotimes [x 255] + (write-byte out x) + (flush out) + (assert= x (read-byte in))) + (dispose! client-stream) + (assert @client-done) + (dispose! server)))) From fb414d9c20877247cec29499dc635c232d052aa0 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 16 Apr 2015 15:44:02 -0600 Subject: [PATCH 149/349] move json parser, don't delete it --- pixie/parser/json.pxi | 111 +++++++++++++++++++++++++ tests/pixie/tests/parser/test-json.pxi | 33 ++++++++ 2 files changed, 144 insertions(+) create mode 100644 pixie/parser/json.pxi create mode 100644 tests/pixie/tests/parser/test-json.pxi diff --git a/pixie/parser/json.pxi b/pixie/parser/json.pxi new file mode 100644 index 00000000..321d71c1 --- /dev/null +++ b/pixie/parser/json.pxi @@ -0,0 +1,111 @@ +(ns pixie.parser.json + (:require [pixie.parser :refer :all] + [pixie.stdlib :as std])) + + + +;; Basic numeric parser. Supports integers (1, 2, 43), decimals (0.1, 1.1, 1000.11) and exponents (1e42, 1E-2) +(defparser NumberParser [] + NUMBER (and (maybe \-) + -> sign + + (or (and + (parse-if (set "123456789")) -> first + (zero+chars digits) -> rest + <- (str first rest)) + (and \0 <- "0")) + -> integer-digits + + (maybe (and \. + (one+chars digits) -> digits + <- digits)) + -> fraction-digits + + + (maybe (and (parse-if (set "eE")) + (maybe (parse-if (set "-+"))) -> exp-sign + (one+chars digits) -> exp-digits + <- [(std/or exp-sign "") exp-digits])) + -> exp-data + + <- (std/read-string (str (std/or sign "") + integer-digits + (if fraction-digits (str "." fraction-digits) "") + (if exp-data (apply str "E" exp-data) ""))))) + +(def valid-escape-chars + {\\ \\ + \" \" + \/ \/ + \b \backspace + \f \formfeed + \n \newline + \r \return + \t \tab}) + + +;; Defines a JSON escaped string parser. Supports all the normal \n \f \r stuff as well +;; as \uXXXX unicode characters +(defparser EscapedStringParser [] + CHAR (or (and \\ + (one-of valid-escape-chars) -> char + <- (valid-escape-chars char)) + + (and \\ + \u + digits -> d1 + digits -> d2 + digits -> d3 + digits -> d4 + <- (char (std/read-string (str "0x" d1 d2 d3 d4)))) + + (parse-if #(not= % \"))) + + STRING (and \" + (zero+chars CHAR) -> s + \" + <- s)) + +;; Basic JSON parser +(defparser JSONParser [NumberParser EscapedStringParser] + + NULL (sequence "null" <- nil) + TRUE (sequence "true" <- true) + FALSE (sequence "false" <- false) + ARRAY (and \[ + (eat whitespace) + (zero+ (and ENTRY -> e + (maybe \,) + <- e)) -> items + (eat whitespace) + (eat whitespace) + \] + <- items) + MAP-ENTRY (and (eat whitespace) + STRING -> key + (eat whitespace) + \: + ENTRY -> value + (maybe \,) + <- [key value]) + MAP (and \{ + (zero+ MAP-ENTRY) -> items + (eat whitespace) + \} + <- (apply hashmap (apply concat items))) + ENTRY (and + (eat whitespace) + (or NUMBER MAP STRING NULL TRUE FALSE ARRAY) -> val + (eat whitespace) + <- val) + ENTRY-AT-END (and ENTRY -> e + (eat whitespace) + end + <- e)) + +(defn read-string [s] + (let [c (string-cursor s) + result ((:ENTRY-AT-END JSONParser) c)] + (if (failure? result) + (println (current c) (snapshot c)) + result))) diff --git a/tests/pixie/tests/parser/test-json.pxi b/tests/pixie/tests/parser/test-json.pxi new file mode 100644 index 00000000..e79ef6cd --- /dev/null +++ b/tests/pixie/tests/parser/test-json.pxi @@ -0,0 +1,33 @@ +(ns pixie.tests.parser.test-json + (:require [pixie.test :refer :all] + [pixie.parser.json :as json])) + + + +(deftest test-json-numbers + (assert-table [x y] (assert= (json/read-string x) y) + "1" 1 + "1.0" 1.0 + "0.1" 0.1 + "1.1" 1.1 + "1234.5678" 1234.5678 + + "-1" -1 + "-0.1" -0.1 + "-1.1" -1.1 + "-1234.5678" -1234.5678 + "1e1" 1e1)) + +(deftest test-vectors + (assert-table [x y] (assert= (json/read-string x) y) + "[]" [] + "[null]" [nil] + "[1, 2]" [1 2] + "[1, 1.0, null]" [1 1.0 nil] + "[\"foo\", 42]" ["foo" 42])) + +(deftest test-maps + (assert-table [x y] (assert= (json/read-string x) y) + "{\"foo\": 42}" {"foo", 42} + "{\"foo\": 42, \"bar\":null}" {"foo" 42 + "bar" nil})) From 5905f573cdfd2d6356473604e2b5e2b01a5ce582 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 16 Apr 2015 16:27:04 -0600 Subject: [PATCH 150/349] added a few comments in tcp.pxi --- pixie/io/tcp.pxi | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 95614f7e..45ab1d3a 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -82,7 +82,10 @@ -(defn tcp-server [ip port on-connection] +(defn tcp-server + "Creates a TCP server on the given ip (as a string) and port (as an integer). Returns a TCPServer that can be + shutdown with dispose!. on-connection is a function that will be passed a TCPStream for each connecting client." + [ip port on-connection] (assert (string? ip) "Ip should be a string") (assert (integer? port) "Port should be a int") @@ -103,7 +106,9 @@ tcp-server)) -(defn tcp-client [ip port] +(defn tcp-client + "Creates a TCP connection to the given ip (as a string) and port (an integer). Will return a TCPStream" + [ip port] (let [client-addr (uv/sockaddr_in) uv-connect (uv/uv_connect_t) client (uv/uv_tcp_t) @@ -122,6 +127,4 @@ (->TCPStream client (uv/uv_buf_t)))) (catch ex (println ex)))))) - (uv/uv_tcp_connect uv-connect client client-addr @cb))) - - )) + (uv/uv_tcp_connect uv-connect client client-addr @cb))))) From bfe04685f9351b251b0e22ffac93affe73495efa Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 17 Apr 2015 08:46:36 +0100 Subject: [PATCH 151/349] Fix typo --- pixie/io/tcp.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 45ab1d3a..fb136bb1 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -92,16 +92,16 @@ (let [server (uv/uv_tcp_t) bind-addr (uv/sockaddr_in) _ (uv/throw-on-error (uv/uv_ip4_addr ip port bind-addr)) - on-new-connetion (atom nil) - tcp-server (->TCPServer ip port on-connection server bind-addr on-new-connetion)] - (reset! on-new-connetion + on-new-connection (atom nil) + tcp-server (->TCPServer ip port on-connection server bind-addr on-new-connection)] + (reset! on-new-connection (ffi/ffi-prep-callback uv/uv_connection_cb (fn [server status] (launch-tcp-client-from-server tcp-server)))) (uv/uv_tcp_init (uv/uv_default_loop) server) (uv/uv_tcp_bind server bind-addr 0) - (uv/throw-on-error (uv/uv_listen server 128 @on-new-connetion)) + (uv/throw-on-error (uv/uv_listen server 128 @on-new-connection)) (st/yield-control) tcp-server)) From d7470199b94406b9492181f238fb2004359d89c4 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 17 Apr 2015 13:58:32 +0100 Subject: [PATCH 152/349] basic tty io support --- examples/tty-io-test.pxi | 12 +++++++ pixie/io.pxi | 16 ++++++++- pixie/io/tcp.pxi | 14 +------- pixie/io/tty.pxi | 73 ++++++++++++++++++++++++++++++++++++++++ pixie/system.pxi | 13 +++++++ pixie/uv.pxi | 20 +++++++++++ 6 files changed, 134 insertions(+), 14 deletions(-) create mode 100644 examples/tty-io-test.pxi create mode 100644 pixie/io/tty.pxi create mode 100644 pixie/system.pxi diff --git a/examples/tty-io-test.pxi b/examples/tty-io-test.pxi new file mode 100644 index 00000000..ec8fe209 --- /dev/null +++ b/examples/tty-io-test.pxi @@ -0,0 +1,12 @@ +(ns io-test + (:require [pixie.io :as io] + [pixie.system :as sys] + [pixie.io.tty :as tty])) + +(io/write-stream tty/stdout "This is on STDOUT\n") +(io/write-stream tty/stderr "This is on STDERR\n") + +(loop [] + (let [input (io/read-line tty/stdin)] + (io/write-stream tty/stdout (str "You typed: " input "\n")) + (recur))) diff --git a/pixie/io.pxi b/pixie/io.pxi index 20dd2d64..afe0e733 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -151,7 +151,7 @@ result) (defn open-write - {:doc "Open a file for reading, returning a IInputStream" + {:doc "Open a file for writing, returning a IOutputStream" :added "0.1"} [filename] (assert (string? filename) "Filename must be a string") @@ -172,6 +172,20 @@ (write-byte fp chr) nil)))) +(defn stream-output-rf [output-stream] + (let [fp (buffered-output-stream output-stream + DEFAULT-BUFFER-SIZE)] + (fn ([] 0) + ([_] (dispose! fp)) + ([_ chr] + (assert (integer? chr)) + (write-byte fp chr) + nil)))) + +(defn write-stream [output-stream val] + (transduce (map int) + (stream-output-rf output-stream) + (str val))) (defn spit [filename val] (transduce (map int) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index fb136bb1..2ca440f4 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -11,24 +11,12 @@ (dispose! @on-connection-cb) (dispose! bind-addr))) -(defn -prep-uv-buffer-fn [buf read-bytes] - (ffi/ffi-prep-callback - uv/uv_alloc_cb - (fn [handle suggested-size uv-buf] - (try - (let [casted (ffi/cast uv-buf uv/uv_buf_t)] - (ffi/set! casted :base buf) - (ffi/set! casted :len (min suggested-size - (buffer-capacity buf) - read-bytes))) - (catch ex (println ex)))))) - (deftype TCPStream [uv-client uv-write-buf] IInputStream (read [this buffer len] (assert (<= (buffer-capacity buffer) len) "Not enough capacity in the buffer") - (let [alloc-cb (-prep-uv-buffer-fn buffer len) + (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) read-cb (atom nil)] (st/call-cc (fn [k] (reset! read-cb (ffi/ffi-prep-callback diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi new file mode 100644 index 00000000..f84d10d0 --- /dev/null +++ b/pixie/io/tty.pxi @@ -0,0 +1,73 @@ +(ns pixie.io.tty + (:require [pixie.stacklets :as st] + [pixie.streams :refer [IInputStream read IOutputStream write]] + [pixie.uv :as uv] + [pixie.io :as io] + [pixie.system :as sys] + [pixie.ffi :as ffi])) + +(deftype TTYInputStream [uv-client uv-write-buf] + IInputStream + (read [this buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) + read-cb (atom nil)] + (st/call-cc (fn [k] + (reset! read-cb (ffi/ffi-prep-callback + uv/uv_read_cb + (fn [stream nread uv-buf] + (set-buffer-count! buffer nread) + (try + (dispose! alloc-cb) + (dispose! @read-cb) + ;(dispose! uv-buf) + (uv/uv_read_stop stream) + (st/run-and-process k (or + (st/exception-on-uv-error nread) + nread)) + (catch ex + (println ex)))))) + (uv/uv_read_start uv-client alloc-cb @read-cb)))))) + +(deftype TTYOutputStream [uv-client uv-write-buf] + IOutputStream + (write [this buffer] + (let [write-cb (atom nil) + uv_write (uv/uv_write_t)] + (ffi/set! uv-write-buf :base buffer) + (ffi/set! uv-write-buf :len (count buffer)) + (st/call-cc + (fn [k] + (reset! write-cb (ffi/ffi-prep-callback + uv/uv_write_cb + (fn [req status] + (try + (dispose! @write-cb) + (st/run-and-process k status) + (catch ex + (println ex)))))) + (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) + + IDisposable + (-dispose! [this] + (dispose! uv-write-buf) + (uv/uv_close uv-client st/close_cb))) + +(defn tty-output-stream [fd] + ;(assert (= uv/UV_TTY (uv/uv_guess_handle fd)) "fd is not a TTY") + (let [buf (uv/uv_buf_t) + tty (uv/uv_tty_t)] + (uv/uv_tty_init (uv/uv_default_loop) tty fd 0) + (->TTYOutputStream tty buf))) + +(defn tty-input-stream [fd] + ;(assert (= uv/UV_TTY (uv/uv_guess_handle fd)) "fd is not a TTY") + (let [buf (uv/uv_buf_t) + tty (uv/uv_tty_t)] + (uv/uv_tty_init (uv/uv_default_loop) tty fd 0) + (->TTYInputStream tty buf))) + +(def stdin (tty-input-stream sys/stdin)) +(def stdout (tty-output-stream sys/stdout)) +(def stderr (tty-output-stream sys/stderr)) diff --git a/pixie/system.pxi b/pixie/system.pxi new file mode 100644 index 00000000..21306122 --- /dev/null +++ b/pixie/system.pxi @@ -0,0 +1,13 @@ +(ns pixie.system + (:require [pixie.ffi-infer :as i])) + +(i/with-config {:library "c" :imports ["stdio.h"]} + (i/defconst STDIN_FILENO) + (i/defconst STDOUT_FILENO) + (i/defconst STDERR_FILENO)) + +(def fdopen (ffi-fn libc "fdopen" [CInt CCharP] CVoidP)) + +(def stdin STDIN_FILENO) +(def stderr STDOUT_FILENO) +(def stdout STDERR_FILENO) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 67f93cdd..d49da8f7 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -189,6 +189,14 @@ (f/defcfn uv_async_init) (f/defcfn uv_async_send) + ; TTY + (f/defcfn uv_tty_init) + (f/defconst UV_TTY_MODE_NORMAL) + (f/defcfn uv_guess_handle) + ;(f/defcfn uv_tty_set_mode) + (f/defcstruct uv_tty_t []) + (f/defconst UV_TTY) + ; TCP Networking (f/defcstruct uv_tcp_t []) @@ -243,3 +251,15 @@ ~@args @cb#)))] (pixie.stacklets/call-cc f))))) + +(defn -prep-uv-buffer-fn [buf read-bytes] + (ffi/ffi-prep-callback + uv_alloc_cb + (fn [handle suggested-size uv-buf] + (try + (let [casted (ffi/cast uv-buf uv_buf_t)] + (ffi/set! casted :base buf) + (ffi/set! casted :len (min suggested-size + (buffer-capacity buf) + read-bytes))) + (catch ex (println ex)))))) From 4c3093fe3709c6bd1c8c0eee3964385e697a242d Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 19 Apr 2015 13:00:20 +0100 Subject: [PATCH 153/349] make slurp/spit accept filenames or streams. * Use utf8 streams for slurp and spit. * Also make the tty example a bit cooler. Note: EOF file errors occur when slurping in IInputStreams but seems to nearly work --- examples/tty-io-test.pxi | 27 ++++++++++++--- pixie/io.pxi | 72 +++++++++++++++++++--------------------- pixie/io/tty.pxi | 30 ++++++++++++++--- pixie/streams/utf8.pxi | 9 +++++ 4 files changed, 90 insertions(+), 48 deletions(-) diff --git a/examples/tty-io-test.pxi b/examples/tty-io-test.pxi index ec8fe209..0fadfa3a 100644 --- a/examples/tty-io-test.pxi +++ b/examples/tty-io-test.pxi @@ -3,10 +3,27 @@ [pixie.system :as sys] [pixie.io.tty :as tty])) -(io/write-stream tty/stdout "This is on STDOUT\n") -(io/write-stream tty/stderr "This is on STDERR\n") +(def history (atom [])) +(defn depth [d] + (apply str (take d (repeat " ")))) + +(defn nested-trace + "Prints a stack trace with each level indented slightly" + [e] + (loop [d 0 traces (trace e)] + (io/spit tty/stdout (str (depth d) (pr-str (first traces)) "\n")) + (if (seq traces) + (recur (inc d) (rest traces))))) + +(io/spit tty/stdout "TTY Demo REPL\n") (loop [] - (let [input (io/read-line tty/stdin)] - (io/write-stream tty/stdout (str "You typed: " input "\n")) - (recur))) + (let [command-number (count @history)] + (io/spit tty/stdout (str "[ " command-number " ] < " )) + (let [input (io/read-line tty/stdin) + res (try (eval (read-string input)) + (catch e + (nested-trace e)))] + (io/spit tty/stdout (str "[ " command-number " ] > " res "\n")) + (swap! history conj input) + (recur)))) diff --git a/pixie/io.pxi b/pixie/io.pxi index afe0e733..9929018e 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,5 +1,6 @@ (ns pixie.io (:require [pixie.streams :as st :refer :all] + [pixie.streams.utf8 :as utf8] [pixie.io-blocking :as io-blocking] [pixie.uv :as uv] [pixie.stacklets :as st] @@ -161,45 +162,40 @@ 0 (uv/uv_buf_t))) - -(defn file-output-rf [filename] - (let [fp (buffered-output-stream (open-write filename) - DEFAULT-BUFFER-SIZE)] - (fn ([] 0) - ([_] (dispose! fp)) - ([_ chr] - (assert (integer? chr)) - (write-byte fp chr) - nil)))) - -(defn stream-output-rf [output-stream] - (let [fp (buffered-output-stream output-stream - DEFAULT-BUFFER-SIZE)] - (fn ([] 0) - ([_] (dispose! fp)) - ([_ chr] - (assert (integer? chr)) - (write-byte fp chr) - nil)))) - -(defn write-stream [output-stream val] - (transduce (map int) - (stream-output-rf output-stream) - (str val))) - -(defn spit [filename val] - (transduce (map int) - (file-output-rf filename) - (str val))) - -(defn slurp [filename] - (let [c (open-read filename) +(defn spit + "Writes the content to output. Output must be a file or an IOutputStream." + [output content] + (cond + (string? output) + (transduce (map identity) + (-> output + open-write + buffered-output-stream + utf8/utf8-output-stream-rf) + (str content)) + + (satisfies? IOutputStream output) + (transduce (map identity) + (-> output + buffered-output-stream + utf8/utf8-output-stream-rf) + (str content)) + + :else (throw "Expected a string or IOutputStream"))) + +(defn slurp + "Reads in the contents of input. Input must be a filename or an IInputStream" + [input] + (let [stream (cond + (string? input) (open-read input) + (satisfies? IInputStream input) input + :else (throw "Expected a string or an IInputStream")) result (transduce - (map char) - string-builder - c)] - (dispose! c) - result)) + (map char) + string-builder + stream)] + (dispose! stream) + result)) (defn run-command [command] (st/apply-blocking io-blocking/run-command command)) diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index f84d10d0..24a909cd 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -6,18 +6,20 @@ [pixie.system :as sys] [pixie.ffi :as ffi])) +(def DEFAULT-BUFFER-SIZE 1024) + (deftype TTYInputStream [uv-client uv-write-buf] IInputStream - (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) + (read [this buf len] + (assert (<= (buffer-capacity buf) len) "Not enough capacity in the buffer") - (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) + (let [alloc-cb (uv/-prep-uv-buffer-fn buf len) read-cb (atom nil)] (st/call-cc (fn [k] (reset! read-cb (ffi/ffi-prep-callback uv/uv_read_cb (fn [stream nread uv-buf] - (set-buffer-count! buffer nread) + (set-buffer-count! buf nread) (try (dispose! alloc-cb) (dispose! @read-cb) @@ -28,7 +30,25 @@ nread)) (catch ex (println ex)))))) - (uv/uv_read_start uv-client alloc-cb @read-cb)))))) + (uv/uv_read_start uv-client alloc-cb @read-cb))))) + + IDisposable + (-dispose! [this] + (dispose! uvbuf) + (fs_close fp)) + + IReduce + (-reduce [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc)))))) (deftype TTYOutputStream [uv-client uv-write-buf] IOutputStream diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi index 055733df..bc9b4044 100644 --- a/pixie/streams/utf8.pxi +++ b/pixie/streams/utf8.pxi @@ -67,3 +67,12 @@ "Creates a UTF8 encoder that writes characters to the given IByteOutputStream." [o] (->UTF8OutputStream o)) + +(defn utf8-output-stream-rf [output-stream] + (let [fp (utf8-output-stream output-stream)] + (fn ([] 0) + ([_] (dispose! fp)) + ([_ chr] + (assert (char? chr)) + (write-char fp chr) + nil)))) From c1a23c8660300264f279caef75c58bd0e1fe5e49 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 19 Apr 2015 15:55:42 -0400 Subject: [PATCH 154/349] 3 arity into --- pixie/fs.pxi | 2 +- pixie/stdlib.pxi | 13 ++++++++----- tests/pixie/tests/test-stdlib.pxi | 4 ++++ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/pixie/fs.pxi b/pixie/fs.pxi index 7a943857..f3e73960 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -52,7 +52,7 @@ "Recursively returns all files and directories below") (walk-files [this] - "Recursivelt returns all files underneath") + "Recursively returns all files underneath") (walk-dirs [this] "Recursivley returns all directories underneath")) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 48110302..a2770d6c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -195,11 +195,14 @@ (def into (fn ^{:doc "Add the elements of `from` to the collection `to`." :signatures [[to from]] :added "0.1"} - into - [to from] - (if (satisfies? IToTransient to) - (persistent! (reduce conj! (transient to) from)) - (reduce conj to from)))) + ([to from] + (if (satisfies? IToTransient to) + (persistent! (reduce conj! (transient to) from)) + (reduce conj to from))) + ([to xform from] + (if (satisfies? IToTransient to) + (transduce xform conj! (transient to) from) + (transduce xform conj to from))))) (def interpose (fn ^{:doc "Returns a transducer that inserts `val` in between elements of a collection." diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 49bec527..6e35566b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -338,6 +338,10 @@ [2 :a] [2 :b] [2 :c] [3 :a] [3 :b] [3 :c]])) +(t/deftest test-into + (t/assert= [1 3] (into [] (comp (map inc) (filter odd?)) (range 3))) + (t/assert= {:a 1 :b 2} (into {} [[:a 1] [:b 2]]))) + (t/deftest test-ex-msg (try (throw "This is an exception") From 77db40c29b985dcaa514fc2820a5cbe0d89c87c5 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 19 Apr 2015 21:17:43 -0400 Subject: [PATCH 155/349] string representations for Range --- pixie/stdlib.pxi | 7 +++++++ tests/pixie/tests/test-stdlib.pxi | 6 ++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 48110302..215b5527 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1768,6 +1768,13 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (and (< step 0) (> start stop))) (cons start (lazy-seq* #(range (+ start step) stop step)))))) +(extend -str Range + (fn [v] + (-str (seq v)))) +(extend -repr Range + (fn [v] + (-repr (seq v)))) + (defn range {:doc "Returns a range of numbers." :examples [["(seq (range 3))" nil (0 1 2)] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 49bec527..b1ab65da 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -36,7 +36,8 @@ (t/assert= (str {:a 1}) "{:a 1}") (t/assert= (str (type 3)) "") (t/assert= (str [1 {:a 1} "hey"]) "[1 {:a 1} hey]") - (t/assert= (seq (map identity "iterable")) '(\i \t \e \r \a \b \l \e))) + (t/assert= (seq (map identity "iterable")) '(\i \t \e \r \a \b \l \e)) + (t/assert= (str (range 3)) "(0 1 2)")) (t/deftest test-repr (t/assert= (-repr nil) "nil") @@ -58,7 +59,8 @@ (t/assert= (-repr {:a 1}) "{:a 1}") (t/assert= (-repr (type 3)) "pixie.stdlib.Integer") - (t/assert= (-repr [1 {:a 1} "hey"]) "[1 {:a 1} \"hey\"]")) + (t/assert= (-repr [1 {:a 1} "hey"]) "[1 {:a 1} \"hey\"]") + (t/assert= (-repr (range 3)) "(0 1 2)")) (t/deftest test-nth ;; works if the index is found From ba08757e2eeb395b4af64db298c15a852c462961 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 20 Apr 2015 06:53:11 -0600 Subject: [PATCH 156/349] Require that exceptions support filterable data, and update catch to allow filtering on these exceptions --- pixie/stdlib.pxi | 107 ++++++++++++++++++++---------- pixie/vm/code.py | 6 +- pixie/vm/custom_types.py | 6 +- pixie/vm/interpreter.py | 6 +- pixie/vm/libs/ffi.py | 3 +- pixie/vm/object.py | 19 ++++-- pixie/vm/persistent_vector.py | 3 +- pixie/vm/reader.py | 5 +- pixie/vm/stdlib.py | 27 +++++++- tests/pixie/tests/test-stdlib.pxi | 34 ++++++++-- 10 files changed, 158 insertions(+), 58 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a2770d6c..d8783a10 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1,6 +1,5 @@ (in-ns :pixie.stdlib) - (def libc (ffi-library pixie.platform/lib-c-name)) @@ -795,19 +794,37 @@ there's a value associated with the key. Use `some` for checking for values." (let [head (first form)] (cond (= head 'catch) (if catch - (throw "Can only have one catch clause per try") + (throw [:pixie.stdlib/SyntaxException + "Can only have one catch clause per try"]) (recur (next (next form)) (first (next form)) body-items finally (next body))) (= head 'finally) (if finally - (throw "Can only have one finally clause per try") + (throw [:pixie.stdlib/SyntaxException + "Can only have one finally clause per try"]) (recur catch catch-sym body-items (next form) (next body))) :else (recur catch catch-sym (conj body-items form) finally (next body))))) - `(-try-catch - (fn [] ~@body-items) - ~(if catch - `(fn [~catch-sym] ~@catch) - `(fn [] nil)) - - (fn [] ~@finally)))))) + (let [catch-data (cond + (keyword? catch-sym) (let [sym (first catch)] + (assert (symbol? sym) (str "Invalid catch binding form" + catch)) + [`[(if (= ~catch-sym (ex-data ~sym)) + (do ~@(next catch)) + (throw ~sym))] + sym]) + (seq? catch-sym) (let [sym (first catch)] + (assert (symbol? sym) (str "Invalid catch binding form" + catch)) + [`[(if ~catch-sym + (do ~@(next catch)) + (throw ~sym))] + sym]) + :else [catch catch-sym])] + `(-try-catch + (fn [] ~@body-items) + ~(if catch + `(fn [~(nth catch-data 1)] ~@(nth catch-data 0)) + `(fn [] nil)) + + (fn [] ~@finally))))))) (defn . {:doc "Access the field named by the symbol. @@ -846,7 +863,9 @@ If further arguments are passed, invokes the method named by symbol, passing the [x] (cond (number? x) (+ x 0.0) - :else (throw (str "Can't convert a value of type " (type x) " to a Float")))) + :else (throw + [:pixie.stdlib/ConversionException + (str "Can't convert a value of type " (type x) " to a Float")]))) (defn int {:doc "Converts a number to an integer." @@ -857,7 +876,9 @@ If further arguments are passed, invokes the method named by symbol, passing the (float? x) (lround (floor x)) (ratio? x) (int (/ (float (numerator x)) (float (denominator x)))) (char? x) (+ x 0) - :else (throw (str "Can't convert a value of type " (type x) " to an Integer")))) + :else (throw + [:pixie.stdlib/ConversionException + (throw (str "Can't convert a value of type " (type x) " to an Integer"))]))) (defn last {:doc "Returns the last element of the collection, or nil if none." @@ -883,13 +904,12 @@ If further arguments are passed, invokes the method named by symbol, passing the {:doc "Given a function, return a new function which takes the same arguments but returns the opposite truth value"} [f] - (if (not (fn? f)) - (throw "Complement must be passed a function") - (fn - ([] (not (f))) - ([x] (not (f x))) - ([x y] (not (f x y))) - ([x y & more] (not (apply f x y more)))))) + (assert (fn? f) "Complement must be passed a function") + (fn + ([] (not (f))) + ([x] (not (f x))) + ([x y] (not (f x y))) + ([x y & more] (not (apply f x y more))))) (defn constantly [x] {:doc "Return a function that always returns x, no matter what it is called with." @@ -983,13 +1003,17 @@ If further arguments are passed, invokes the method named by symbol, passing the (instance? PersistentVector x) (if (= (count x) 2) (assoc coll (nth x 0 nil) (nth x 1 nil)) - (throw "Vector arg to map conj must be a pair")) + (throw + [:pixie.stdlib/InvalidArgumentException + "Vector arg to map conj must be a pair"])) (satisfies? ISeqable x) (reduce conj coll (-seq x)) :else - (throw (str (type x) " cannot be conjed to a map"))))) + (throw + [:pixie.stdlib/InvalidArgumentException + (str (type x) " cannot be conjed to a map")])))) (extend -conj Cons (fn [coll x] @@ -1075,11 +1099,13 @@ Creates new maps if the keys are not present." ([test] `(if ~test nil - (throw "Assert failed"))) + (throw [:pixie.stdlib/AssertionException + "Assert failed"]))) ([test msg] `(if ~test nil - (throw (str "Assert failed: " ~msg))))) + (throw [:pixie.stdlib/AssertionException + (str "Assert failed: " ~msg)])))) (defmacro resolve {:doc "Resolve the var associated with the symbol in the current namespace." @@ -1172,7 +1198,9 @@ Creates new maps if the keys are not present." (protocol? @(resolve-in *ns* body)) [@(resolve-in *ns* body) (second res) (conj (third res) body)] - :else (throw (str "can only extend protocols or Object, not " body " of type " (type body)))) + :else (throw + [:pixie.stdlib/AssertionException + (str "can only extend protocols or Object, not " body " of type " (type body))])) (seq? body) (let [proto (first res) tbs (second res) pbs (third res)] (if (protocol? proto) [proto tbs (conj pbs body)] @@ -1222,7 +1250,8 @@ and implements IAssociative, ILookup and IObject." `(-contains-key [self k] (contains? ~(set fields) k)) `(-dissoc [self k] - (throw "dissoc is not supported on defrecords")) + (throw [:pixie.stdlib/NotImplementedException + "dissoc is not supported on defrecords"])) 'ILookup `(-val-at [self k not-found] (if (contains? ~(set fields) k) @@ -1237,7 +1266,7 @@ and implements IAssociative, ILookup and IObject." `(= (. self ~field) (. other ~field))) fields))) `(-hash [self] - (throw "not implemented"))] + (throw [:pixie.stdlib/NotImplementedException "not implemented"]))] deftype-decl `(deftype ~nm ~fields ~@default-bodies ~@body)] `(do ~type-from-map ~deftype-decl))) @@ -1636,7 +1665,8 @@ not enough elements were present." (map? binding) (let [name (gensym "map__")] (reduce conj [name expr] (destructure-map binding name))) - :else (throw (str "unsupported binding form: " binding)))) + :else (throw [:pixie.stdlib/AssertionException + (str "unsupported binding form: " binding)]))) (defn destructure-vector [binding-vector expr] (loop [bindings (seq binding-vector) @@ -1711,12 +1741,15 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (extend -nth ISeq (fn [s n] (when (empty? s) - (throw "Index out of Range")) + (throw + [:pixie.stdlib/OutOfRangeException + "Index out of Range"])) (if (and (pos? n) s) (recur (next s) (dec n)) (if (zero? n) (first s) - (throw "Index out of Range"))))) + (throw [:pixie.stdlib/OutOfRangeException + "Index out of Range"]))))) (extend -nth-not-found ISeq (fn [s n not-found] (if (and (pos? n) s) (recur (next s) (dec n) not-found) @@ -1753,12 +1786,12 @@ For more information, see http://clojure.org/special_forms#binding-forms"} IIndexed (-nth [self idx] (when (or (= start stop 0) (neg? idx)) - (throw "Index out of Range")) + (throw [:pixie.stdlib/OutOfRangeException "Index out of Range"])) (let [cmp (if (< start stop) < >) val (+ start (* idx step))] (if (cmp val stop) val - (throw "Index out of Range")))) + (throw [:pixie.stdlib/OutOfRangeException "Index out of Range"])))) (-nth-not-found [self idx not-found] (let [cmp (if (< start stop) < >) val (+ start (* idx step))] @@ -1887,7 +1920,8 @@ user => (refer 'pixie.string :rename '{index-of find}) user => (refer 'pixie.string :exclude '(substring))" :added "0.1"} [ns-sym & filters] - (let [ns (or (the-ns ns-sym) (throw (str "No such namespace: " ns-sym))) + (let [ns (or (the-ns ns-sym) (throw [:pixie.stdlib/NamespaceNotFoundException + (str "No such namespace: " ns-sym)])) filters (apply hashmap filters) nsmap (ns-map ns) rename (or (:rename filters) {}) @@ -1896,7 +1930,8 @@ user => (refer 'pixie.string :exclude '(substring))" (keys nsmap) (or (:refer filters) (:only filters)))] (when (and refers (not (satisfies? ISeqable refers))) - (throw ":only/:refer must be a collection of symbols")) + (throw [:pixie.stdlib/InvalidArgumentException + ":only/:refer must be a collection of symbols"])) (when-let [as (:as filters)] (refer-ns *ns* ns-sym as)) (loop [syms (seq refers)] @@ -1907,7 +1942,8 @@ user => (refer 'pixie.string :exclude '(substring))" (when-not (exclude sym) (let [v (nsmap sym)] (when-not v - (throw (str sym "does not exist"))) + (throw [:pixie.stdlib/SymbolNotFoundException + (str sym "does not exist")])) (refer-symbol *ns* (or (rename sym) sym) v)))) (recur (next syms))))) nil)) @@ -2146,7 +2182,8 @@ If the number of arguments is even and no clause matches, throws an exception." `((~pred ~a ~x) ~b) `(:else ~a))) (partition 2 clauses)) - :else (throw "No matching clause!"))))) + :else (throw [:pixie.stdlib/MissingClauseException + "No matching clause!"]))))) (defmacro case "Takes an expression and a number of two-form clauses. diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 548cb48a..b1ac4caa 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -179,7 +179,8 @@ def get_fn(self, arity): if self._rest_fn: acc.append(unicode(str(self._rest_fn.required_arity())) + u"+") - runtime_error(u"Wrong number of arguments " + unicode(str(arity)) + u" for function '" + unicode(self._name) + u"'. Expected " + join_last(acc, u"or")) + runtime_error(u"Wrong number of arguments " + unicode(str(arity)) + u" for function '" + unicode(self._name) + u"'. Expected " + join_last(acc, u"or"), + u"pixie.stdlib/InvalidArityException") def get_arities(self): return self._arities.keys() @@ -241,7 +242,8 @@ def invoke(self, args): else: runtime_error(u"Invalid number of arguments " + unicode(str(len(args))) + u" for function '" + unicode(str(self._name)) + u"'. Expected " - + unicode(str(self.get_arity()))) + + unicode(str(self.get_arity())), + u":pixie.stdlib/InvalidArityException") def invoke_with(self, args, this_fn): try: diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 0d6d126b..081e57fc 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -49,7 +49,8 @@ def type(self): def set_field(self, name, val): idx = self._custom_type.get_slot_idx(name) if idx == -1: - runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type())), + u"pixie.stdlib/InvalidFieldException") old_val = self._fields[idx] if isinstance(old_val, AbstractMutableCell): @@ -71,7 +72,8 @@ def get_field_immutable(self, idx): def get_field(self, name): idx = self._custom_type.get_slot_idx(name) if idx == -1: - runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type()))) + runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type())), + u"pixie.stdlib/InvalidFieldException") if self._custom_type.is_mutable(name): value = self._fields[idx] diff --git a/pixie/vm/interpreter.py b/pixie/vm/interpreter.py index bbc96324..83e873df 100644 --- a/pixie/vm/interpreter.py +++ b/pixie/vm/interpreter.py @@ -81,7 +81,8 @@ def pop(self): self.sp -= 1 if not 0 <= self.sp < len(self.stack): - runtime_error(u"Stack out of range: " + unicode(str(self.sp))) + runtime_error(u"Stack out of range: " + unicode(str(self.sp)), + u"pixie.vm.interpreter/InterpreterError") v = self.stack[self.sp] self.stack[self.sp] = None @@ -91,7 +92,8 @@ def pop(self): def nth(self, delta): affirm(delta >= 0, u"Invalid nth value, (compiler error)") if not self.sp - 1 >= delta: - runtime_error(u"Interpreter nth out of range: " + unicode(str(self.sp - 1)) + u", " + unicode(str(delta))) + runtime_error(u"Interpreter nth out of range: " + unicode(str(self.sp - 1)) + u", " + unicode(str(delta)), + u"pixie.vm.interpreter/InterpreterError") return self.stack[self.sp - delta - 1] def push_nth(self, delta): diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 6fbc53a1..b8b92512 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -68,7 +68,8 @@ def load_lib(self): self._dyn_lib = dynload.dlopen(s) self._is_inited = True except dynload.DLOpenError as ex: - raise object.WrappedException(object.RuntimeException(rt.wrap(u"Couldn't Load Library: " + self._name))) + raise object.runtime_error(u"Couldn't Load Library: " + self._name, + u"pixie.stdlib/LibraryNotFoundException") finally: rffi.free_charp(s) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index e986bbbe..4c39f162 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -114,7 +114,10 @@ def istypeinstance(obj, t): class RuntimeException(Object): _type = Type(u"pixie.stdlib.RuntimeException") - def __init__(self, data): + def __init__(self, msg, data): + assert data is not None + assert msg is not None + self._msg = msg self._data = data self._trace = [] @@ -129,8 +132,8 @@ def __repr__(self): for x in trace: s.append(x.__repr__()) s.append(u"\n") - - s.extend([u"RuntimeException: " + rt.name(rt.str(self._data)) + u"\n"]) + s.extend([u"RuntimeException: " + rt.name(rt.str(self._data)) + u" " + + rt.name(rt.str(self._msg)) + u"\n"]) return u"".join(s) @@ -150,11 +153,15 @@ def affirm(val, msg): assert isinstance(msg, unicode) if not val: import pixie.vm.rt as rt - raise WrappedException(RuntimeException(rt.wrap(msg))) + from pixie.vm.keyword import keyword + raise WrappedException(RuntimeException(rt.wrap(msg), keyword(u"pixie.stdlib/AssertionException"))) -def runtime_error(msg): +def runtime_error(msg, data=None): import pixie.vm.rt as rt - raise WrappedException(RuntimeException(rt.wrap(msg))) + from pixie.vm.keyword import keyword + if data is None: + data = u"pixie.stdlib/AssertionException" + raise WrappedException(RuntimeException(rt.wrap(msg), keyword(data))) def safe_invoke(f, args): try: diff --git a/pixie/vm/persistent_vector.py b/pixie/vm/persistent_vector.py index 65aaacfb..a0e1ae55 100644 --- a/pixie/vm/persistent_vector.py +++ b/pixie/vm/persistent_vector.py @@ -182,7 +182,8 @@ def assoc_at(self, idx, val): if idx == self._cnt: return self.conj(val) else: - object.runtime_error(u"index out of range") + object.runtime_error(u"index out of range", + u"pixie.stdlib/OutOfRangeException") def do_assoc(lvl, node, idx, val): diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 0e150600..6173859b 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -787,7 +787,7 @@ def throw_syntax_error_with_data(rdr, txt): meta = nil data = rt.interpreter_code_info(meta) - err = object.RuntimeException(rt.wrap(txt)) + err = object.runtime_error(txt) err._trace.append(data) raise object.WrappedException(err) @@ -797,7 +797,8 @@ def read_inner(rdr, error_on_eof, always_return_form=True): eat_whitespace(rdr) except EOFError as ex: if error_on_eof: - runtime_error(u"Unexpected EOF while reading") + runtime_error(u"Unexpected EOF while reading", + u"pixie.stdlib/EOFWhileReadingException") return eof diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index cd9a283d..05c309c3 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -659,6 +659,7 @@ def namespace(s): @as_var("-try-catch") def _try_catch(main_fn, catch_fn, final): + from pixie.vm.keyword import keyword try: return main_fn.invoke([]) except Exception as ex: @@ -668,9 +669,9 @@ def _try_catch(main_fn, catch_fn, final): if not we_are_translated(): print "Python Error Info: ", ex.__dict__, ex raise - ex = RuntimeException(rt.wrap(u"Some error: " + unicode(str(ex)))) + ex = RuntimeException(rt.wrap(u"Internal error: " + unicode(str(ex))), keyword(u"pixie.stdlib/InternalError")) else: - ex = RuntimeException(nil) + ex = RuntimeException(u"No available message", keyword(u"pixie.stdlib/UnknownInternalError")) return catch_fn.invoke([ex]) else: return catch_fn.invoke([ex._ex]) @@ -680,9 +681,19 @@ def _try_catch(main_fn, catch_fn, final): @as_var("throw") def _throw(ex): + from pixie.vm.keyword import keyword if isinstance(ex, RuntimeException): raise WrappedException(ex) - raise WrappedException(RuntimeException(ex)) + if rt._satisfies_QMARK_(IVector, ex): + data = rt.nth(ex, rt.wrap(0)) + msg = rt.nth(ex, rt.wrap(1)) + elif rt._satisfies_QMARK_(ILookup, ex): + data = rt._val_at(ex, keyword(u"data"), nil) + msg = rt._val_at(ex, keyword(u"msg"), nil) + else: + affirm(False, u"Can only throw vectors, maps and exceptions") + return nil + raise WrappedException(RuntimeException(msg, data)) @as_var("resolve-in") def _var(ns, nm): @@ -791,6 +802,7 @@ def _seq(self): trace = vector.EMPTY trace_element = rt.hashmap(keyword(u"type"), keyword(u"runtime")) trace_element = rt.assoc(trace_element, keyword(u"data"), rt.wrap(self._data)) + trace_element = rt.assoc(trace_element, keyword(u"msg"), rt.wrap(self._msg)) trace = rt.conj(trace, trace_element) for x in self._trace: tmap = x.trace_map() @@ -806,9 +818,18 @@ def _seq(self): @as_var("ex-msg") def ex_msg(e): """Returns the message contained in an exception""" + affirm(isinstance(e, RuntimeException), u"Argument must be a RuntimeException") + assert isinstance(e, RuntimeException) + return e._msg + +@as_var("ex-data") +def ex_data(e): + """Returns the data contained in an exception""" + affirm(isinstance(e, RuntimeException), u"Argument must be a RuntimeException") assert isinstance(e, RuntimeException) return e._data + @extend(_doc, code.NativeFn._type) def _doc(self): assert isinstance(self, code.NativeFn) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 6e35566b..37f038ee 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -344,9 +344,33 @@ (t/deftest test-ex-msg (try - (throw "This is an exception") - (catch e - (t/assert= (ex-msg e) "This is an exception")))) + (throw [::something "This is an exception"]) + (catch e + (t/assert= (ex-msg e) "This is an exception") + (t/assert= (ex-data e) ::something)))) + +(t/deftest test-ex-filtering + (let [f (fn [val] + (try + (try + (throw [val "Some failure"]) + (catch ::catch-this ex + :found)) + (catch ex + :not-found)))] + (t/assert= (f ::catch-this) :found) + (t/assert= (f :something-else) :not-found)) + + (let [f (fn [val] + (try + (try + (throw [val "Some failure"]) + (catch (= ::catch-this (ex-data ex)) ex + :found)) + (catch ex + :not-found)))] + (t/assert= (f ::catch-this) :found) + (t/assert= (f :something-else) :not-found))) (t/deftest test-range (t/assert= (= (-seq (range 10)) @@ -397,7 +421,9 @@ (try (/ 0 0) (catch e - (t/assert= (first (trace e)) {:type :runtime :data "Divide by zero"}) + (t/assert= (first (trace e)) {:type :runtime + :data :pixie.stdlib/AssertionException + :msg "Divide by zero"}) (t/assert= (second (trace e)) {:type :native :name "_div"} )))) (t/deftest test-tree-seq From abe9791453b42879ec43d39499405cd8d512915f Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Mon, 20 Apr 2015 10:29:18 -0400 Subject: [PATCH 157/349] Make remainder return Integer if both arguments are integers Only extend the rem operation to use math.fmod if one or both of the two arguments is not an integer. --- pixie/vm/numbers.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index fe06eafd..6f1d029e 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -135,7 +135,8 @@ def define_num_ops(): continue extend_num_op(op, c1, c2, conv1, sym, conv2) extend_num_op("_quot", c1, c2, conv1, "/", conv2, wrap_start = "rt.wrap(math.floor(", wrap_end = "))") - extend_num_op("_rem", c1, c2, conv1, ",", conv2, wrap_start = "rt.wrap(math.fmod(", wrap_end = "))") + if c1 != Integer or c2 != Integer: + extend_num_op("_rem", c1, c2, conv1, ",", conv2, wrap_start = "rt.wrap(math.fmod(", wrap_end = "))") for (op, sym) in [("_num_eq", "=="), ("_lt", "<"), ("_gt", ">"), ("_lte", "<="), ("_gte", ">=")]: extend_num_op(op, c1, c2, conv1, sym, conv2, wrap_start = "true if ", wrap_end = " else false") From e53412cf1b7c957ee1d896be5c15f4a7d96fce9a Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Mon, 20 Apr 2015 10:39:26 -0400 Subject: [PATCH 158/349] Add note for Mac OS X building --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 658d8c59..69a01bf9 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ Some planned and implemented features: make build_with_jit ./pixie-vm +Note: Mac OS X does not come with the build tools required by default. Install the XCode Command Line tools ([Apple Developer Site](http://developer.apple.com)) or install them independently. + ## Running the tests From a07f9e310552658cc2dcfd9df624aa3c2b5e6f74 Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Mon, 20 Apr 2015 17:35:38 -0400 Subject: [PATCH 159/349] Wrap _quot in a check whether its arguments are not both ints --- pixie/vm/numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index 6f1d029e..ed54bd53 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -134,9 +134,9 @@ def define_num_ops(): if op == "_div" and c1 == Integer and c2 == Integer: continue extend_num_op(op, c1, c2, conv1, sym, conv2) - extend_num_op("_quot", c1, c2, conv1, "/", conv2, wrap_start = "rt.wrap(math.floor(", wrap_end = "))") if c1 != Integer or c2 != Integer: extend_num_op("_rem", c1, c2, conv1, ",", conv2, wrap_start = "rt.wrap(math.fmod(", wrap_end = "))") + extend_num_op("_quot", c1, c2, conv1, "/", conv2, wrap_start = "rt.wrap(math.floor(", wrap_end = "))") for (op, sym) in [("_num_eq", "=="), ("_lt", "<"), ("_gt", ">"), ("_lte", "<="), ("_gte", ">=")]: extend_num_op(op, c1, c2, conv1, sym, conv2, wrap_start = "true if ", wrap_end = " else false") From 74231847156eed08d9cfa0b54b6ee3dacfd32554 Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Mon, 20 Apr 2015 21:57:17 -0400 Subject: [PATCH 160/349] Added tests to confirm changes --- tests/pixie/tests/test-numbers.pxi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 1d88d9d0..092aff5d 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -49,3 +49,16 @@ (t/deftest test-float (doseq [[x f] [[1 1.0] [3 3.0] [3.333 3.333] [3/2 1.5] [1/7 (/ 1.0 7.0)]]] (t/assert= (float x) f))) + +(t/deftest rem-types + (t/assert= "" (str (type (rem 5 3)))) + (t/assert= "" (str (type (rem 5.0 3)))) + (t/assert= "" (str (type (rem 7/2 3)))) + (t/assert= "" (str (type (rem 7/2 3.0))))) + +(t/deftest quot-types + (t/assert= "" (str (type (quot 5 3)))) + (t/assert= "" (str (type (quot 5.0 3)))) + (t/assert= "" (str (type (quot 7/2 3/7)))) + (t/assert= "" (str (type (quot 7/2 3.0))))) + From 8871f30356d2668f2fe96a501a5195d8459c15ea Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Tue, 21 Apr 2015 12:05:55 -0400 Subject: [PATCH 161/349] Change test to remove stringification --- tests/pixie/tests/test-numbers.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 092aff5d..efe36e2a 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -57,8 +57,8 @@ (t/assert= "" (str (type (rem 7/2 3.0))))) (t/deftest quot-types - (t/assert= "" (str (type (quot 5 3)))) - (t/assert= "" (str (type (quot 5.0 3)))) - (t/assert= "" (str (type (quot 7/2 3/7)))) - (t/assert= "" (str (type (quot 7/2 3.0))))) + (t/assert= Integer (type (quot 5 3))) + (t/assert= Float (type (quot 5.0 3))) + (t/assert= Integer (type (quot 7/2 3/7))) + (t/assert= Float (type (quot 7/2 3.0)))) From 103d36732fa54af0d6f6965d1fd75249daa6a5fd Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Tue, 21 Apr 2015 23:26:00 -0400 Subject: [PATCH 162/349] Fix to not use stringification for rem tests --- tests/pixie/tests/test-numbers.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index efe36e2a..3b5f0aeb 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -51,10 +51,10 @@ (t/assert= (float x) f))) (t/deftest rem-types - (t/assert= "" (str (type (rem 5 3)))) - (t/assert= "" (str (type (rem 5.0 3)))) - (t/assert= "" (str (type (rem 7/2 3)))) - (t/assert= "" (str (type (rem 7/2 3.0))))) + (t/assert= Integer (type (rem 5 3))) + (t/assert= Float (type (rem 5.0 3))) + (t/assert= Ratio (type (rem 7/2 3))) + (t/assert= Float (type (rem 7/2 3.0)))) (t/deftest quot-types (t/assert= Integer (type (quot 5 3))) From 0c367748fc8737a23140d82c476ca3102150602c Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 22 Apr 2015 20:06:56 +0100 Subject: [PATCH 163/349] add if-not macro --- pixie/stdlib.pxi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index aa648128..4114ed8f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1467,6 +1467,11 @@ The new value is thus `(apply f current-value-of-atom args)`." (let [~bind tmp#] ~@body))))) +(defmacro if-not + ([test then] `(if-not ~test ~then nil)) + ([test then else] + `(if (not ~test) ~then ~else))) + (defmacro if-let ([binding then] `(if-let ~binding ~then nil)) ([binding then else] From 85a9d7b6b85ba9507d7475d3edf12548db70a8ce Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Wed, 22 Apr 2015 21:45:21 +0200 Subject: [PATCH 164/349] exit the repl when the form is just `:exit` It does *not* exit when `:exit` is the result of evaluating an expression, e.g. `(do :exit)` and `(or nil false :exit)` both don't exit, but just `:exit` does. A similar feature was present in the old repl, but hadn't made it into the current one. --- pixie/repl.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/repl.pxi b/pixie/repl.pxi index e8432cba..639035db 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -19,7 +19,7 @@ ""))))] (loop [] (try (let [form (read rdr false)] - (if (= form eof) + (if (or (= form eof) (= form :exit)) (exit 0) (let [x (eval form)] (pixie.stdlib/-push-history x) From 6fcadacb5e58df752d34e269805672b980d289c7 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 22 Apr 2015 22:14:55 +0100 Subject: [PATCH 165/349] add a time macro --- pixie/time.pxi | 9 +++++++++ pixie/uv.pxi | 3 +++ 2 files changed, 12 insertions(+) create mode 100644 pixie/time.pxi diff --git a/pixie/time.pxi b/pixie/time.pxi new file mode 100644 index 00000000..f392646d --- /dev/null +++ b/pixie/time.pxi @@ -0,0 +1,9 @@ +(ns pixie.time + (:require [pixie.uv :as uv])) + +(defmacro time + [body] + `(let [start# (uv/uv_hrtime) + return# ~body] + (prn (str "Elapsed time: " (/ (- (uv/uv_hrtime) start#) 1000.0) "ms")) + return#)) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index d49da8f7..199942f4 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -52,6 +52,9 @@ (f/defcfn uv_timer_set_repeat) (f/defcfn uv_timer_get_repeat) + ;; Time + (f/defcfn uv_hrtime) + ;; Filesystem From fbbd9c2598fb1fd1eafff7e382b852bef423a5a4 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 23 Apr 2015 12:16:16 +0100 Subject: [PATCH 166/349] fix --- pixie/time.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/time.pxi b/pixie/time.pxi index f392646d..38f8a46b 100644 --- a/pixie/time.pxi +++ b/pixie/time.pxi @@ -5,5 +5,5 @@ [body] `(let [start# (uv/uv_hrtime) return# ~body] - (prn (str "Elapsed time: " (/ (- (uv/uv_hrtime) start#) 1000.0) "ms")) + (prn (str "Elapsed time: " (/ (- (uv/uv_hrtime) start#) 1000000.0) "ms")) return#)) From eb8278ea9cc44cf7eda30eafc059d8fadf5e2a50 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Thu, 23 Apr 2015 13:48:52 -0400 Subject: [PATCH 167/349] loop destructure --- pixie/stdlib.pxi | 98 ++++++++++++++++++++++--------- pixie/vm/compiler.py | 6 +- tests/pixie/tests/test-stdlib.pxi | 8 +++ 3 files changed, 81 insertions(+), 31 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4114ed8f..9842dc1f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -37,6 +37,10 @@ (cons 'let* args))) (set-macro! let) +(def loop (fn* [& args] + (cons 'loop* args))) +(set-macro! loop) + (def identity (fn ^{:doc "The identity function. Returns its argument." :added "0.1"} @@ -132,6 +136,15 @@ result (-reduce coll f init)] (f result))))) +(defn every? + {:doc "Check if every element of the collection satisfies the predicate." + :added "0.1"} + [pred coll] + (cond + (nil? (seq coll)) true + (pred (first coll)) (recur pred (next coll)) + :else false)) + (def map (fn ^{:doc "map - creates a transducer that applies f to every input element" :signatures [[f] [f coll]] :added "0.1"} @@ -1322,6 +1335,24 @@ and implements IAssociative, ILookup and IObject." ([f] (lazy-seq (cons (f) (repeatedly f)))) ([n f] (take n (repeatedly f)))) +(defn interleave + "Returns a seq of all the items in the input collections interleaved" + ([] ()) + ([c1] (seq c1)) + ([c1 c2] + (lazy-seq + (let [s1 (seq c1) + s2 (seq c2)] + (when (and s1 s2) + (cons (first s1) (cons (first s2) + (interleave (next s1) (next s2)))))))) + ([& colls] + (lazy-seq + (let [ss (map seq colls)] + (when (every? identity ss) + (concat (map first ss) + (apply interleave (map next ss)))))))) + (defmacro doseq {:doc "Evaluates all elements of the seq, presumably for side effects. Returns nil." :added "0.1"} @@ -1710,7 +1741,7 @@ not enough elements were present." res)) (defmacro let - {:doc "Makes the bindings availlable in the body. + {:doc "Makes the bindings available in the body. The bindings must be a vector of binding-expr pairs. The binding can be a destructuring binding, as below. @@ -1744,6 +1775,44 @@ For more information, see http://clojure.org/special_forms#binding-forms"} `(let* ~destructured-bindings ~@body))) +(defn take-nth + "Returns a lazy seq of every nth item in coll. Returns a stateful + transducer when no collection is provided." + ([n] + (fn [rf] + (let [ia (atom -1)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (let [i (swap! ia inc)] + (if (zero? (rem i n)) + (rf result input) + result))))))) + ([n coll] + (lazy-seq + (when-let [s (seq coll)] + (cons (first s) (take-nth n (drop n s))))))) + +(defmacro loop + [bindings & body] + (let [vals (take-nth 2 (drop 1 bindings)) + bindings (take-nth 2 bindings) + binding-syms (map (fn [b] (if (symbol? b) b (gensym))) bindings) + binding-forms (transduce + (map (fn [bind] + (let [[b v s] bind] + (if (symbol? b) + [b v] + [s v b s])))) + concat + [] + (map vector bindings vals binding-syms))] + `(let ~(vec binding-forms) + (loop* ~(vec (interleave binding-syms binding-syms)) + (let ~(vec (interleave bindings binding-syms)) + ~@body))))) + (extend -nth ISeq (fn [s n] (when (empty? s) (throw @@ -1986,15 +2055,6 @@ user => (refer 'pixie.string :exclude '(substring))" m2))] (reduce merge2 (first maps) (next maps))))) -(defn every? - {:doc "Check if every element of the collection satisfies the predicate." - :added "0.1"} - [pred coll] - (cond - (nil? (seq coll)) true - (pred (first coll)) (recur pred (next coll)) - :else false)) - ; If you want a fn that uses destructuring in its parameter list, place ; it after this definition. If you don't, you will get compile failures ; in unrelated files. @@ -2347,24 +2407,6 @@ Calling this function on something that is not ISeqable returns a seq with that (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) -(defn interleave - "Returns a seq of all the items in the input collections interleaved" - ([] ()) - ([c1] (seq c1)) - ([c1 c2] - (lazy-seq - (let [s1 (seq c1) - s2 (seq c2)] - (when (and s1 s2) - (cons (first s1) (cons (first s2) - (interleave (next s1) (next s2)))))))) - ([& colls] - (lazy-seq - (let [ss (map seq colls)] - (when (every? identity ss) - (concat (map first ss) - (apply interleave (map next ss)))))))) - (defn min "Returns the smallest of all the arguments to this function. Assumes arguments are numeric" ([x] x) diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index f314ac1c..76ca7fae 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -508,7 +508,7 @@ def compile_fn(form, ctx): if rt.meta(name) is not nil: compile_meta(rt.meta(name), ctx) -LOOP = symbol.symbol(u"loop") +LOOP = symbol.symbol(u"loop*") def compile_fn_body(name, args, body, ctx): new_ctx = Context(rt.name(name), rt.count(args), ctx) @@ -698,7 +698,7 @@ def compile_loop(form, ctx): for i in range(0, rt.count(bindings), 2): binding_count += 1 name = rt.nth(bindings, rt.wrap(i)) - affirm(isinstance(name, symbol.Symbol), u"Loop must bindings must be symbols") + affirm(isinstance(name, symbol.Symbol), u"Loop bindings must be symbols") bind = rt.nth(bindings, rt.wrap(i + 1)) compile_form(bind, ctx) @@ -787,7 +787,7 @@ def compile_local_macro(form, ctx): u"quote": compile_quote, u"recur": compile_recur, u"let*": compile_let, - u"loop": compile_loop, + u"loop*": compile_loop, u"comment": compile_comment, u"var": compile_var, u"catch": compile_catch, diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index b5dd3741..1e938a1b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -405,6 +405,14 @@ (swap! cnt inc))) @cnt))) +(t/deftest test-loop-destructure + (t/assert= + [3 -3] + (loop [[a b :as vs] [0 0]] + (if (> a 2) + vs + (recur [(inc a) (dec b)]))))) + (t/deftest test-take-while (t/assert= (take-while pos? [1 2 3 -1]) [1 2 3]) (t/assert= (take-while pos? [-1 2]) ()) From e63ba1614351231a65f528995a8d007119806d28 Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Fri, 24 Apr 2015 11:51:54 -0400 Subject: [PATCH 168/349] From #176 Add 2-argument reduce with function identity --- pixie/stdlib.pxi | 7 +++++-- tests/pixie/tests/test-stdlib.pxi | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4114ed8f..3af57b15 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -160,8 +160,11 @@ nil)))))] (map (fn [args] (apply f args)) (step colls)))))) -(def reduce (fn [rf init col] - (-reduce col rf init))) +(def reduce (fn + ([rf col] + (reduce rf (rf) col)) + ([rf init col] + (-reduce col rf init)))) (def instance? (fn ^{:doc "Checks if x is an instance of t. diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index b5dd3741..551cbd8b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -508,3 +508,8 @@ (t/assert-throws? RuntimeException "proto must be a Protocol" (satisfies? [IIndexed :also-not-a-proto] [1 2]))) + +(t/deftest test-reduce + (t/assert= 5050 (reduce + (range 101))) + (t/assert= 3628800 (reduce * (range 1 11))) + (t/assert= 5051 (reduce + 1 (range 101)))) From a6afbfb90b73bd6565c90f1c8cfe784494b5692a Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 26 Apr 2015 14:23:05 -0400 Subject: [PATCH 169/349] additional tests, reorder loop macro in stdlib --- pixie/stdlib.pxi | 134 +++++++++++++++--------------- tests/pixie/tests/test-stdlib.pxi | 10 ++- 2 files changed, 75 insertions(+), 69 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 4f87065c..6f260ade 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -38,7 +38,7 @@ (set-macro! let) (def loop (fn* [& args] - (cons 'loop* args))) + (cons 'loop* args))) (set-macro! loop) (def identity @@ -136,15 +136,6 @@ result (-reduce coll f init)] (f result))))) -(defn every? - {:doc "Check if every element of the collection satisfies the predicate." - :added "0.1"} - [pred coll] - (cond - (nil? (seq coll)) true - (pred (first coll)) (recur pred (next coll)) - :else false)) - (def map (fn ^{:doc "map - creates a transducer that applies f to every input element" :signatures [[f] [f coll]] :added "0.1"} @@ -1338,24 +1329,6 @@ and implements IAssociative, ILookup and IObject." ([f] (lazy-seq (cons (f) (repeatedly f)))) ([n f] (take n (repeatedly f)))) -(defn interleave - "Returns a seq of all the items in the input collections interleaved" - ([] ()) - ([c1] (seq c1)) - ([c1 c2] - (lazy-seq - (let [s1 (seq c1) - s2 (seq c2)] - (when (and s1 s2) - (cons (first s1) (cons (first s2) - (interleave (next s1) (next s2)))))))) - ([& colls] - (lazy-seq - (let [ss (map seq colls)] - (when (every? identity ss) - (concat (map first ss) - (apply interleave (map next ss)))))))) - (defmacro doseq {:doc "Evaluates all elements of the seq, presumably for side effects. Returns nil." :added "0.1"} @@ -1744,7 +1717,7 @@ not enough elements were present." res)) (defmacro let - {:doc "Makes the bindings available in the body. + {:doc "Makes the bindings availlable in the body. The bindings must be a vector of binding-expr pairs. The binding can be a destructuring binding, as below. @@ -1778,44 +1751,6 @@ For more information, see http://clojure.org/special_forms#binding-forms"} `(let* ~destructured-bindings ~@body))) -(defn take-nth - "Returns a lazy seq of every nth item in coll. Returns a stateful - transducer when no collection is provided." - ([n] - (fn [rf] - (let [ia (atom -1)] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] - (let [i (swap! ia inc)] - (if (zero? (rem i n)) - (rf result input) - result))))))) - ([n coll] - (lazy-seq - (when-let [s (seq coll)] - (cons (first s) (take-nth n (drop n s))))))) - -(defmacro loop - [bindings & body] - (let [vals (take-nth 2 (drop 1 bindings)) - bindings (take-nth 2 bindings) - binding-syms (map (fn [b] (if (symbol? b) b (gensym))) bindings) - binding-forms (transduce - (map (fn [bind] - (let [[b v s] bind] - (if (symbol? b) - [b v] - [s v b s])))) - concat - [] - (map vector bindings vals binding-syms))] - `(let ~(vec binding-forms) - (loop* ~(vec (interleave binding-syms binding-syms)) - (let ~(vec (interleave bindings binding-syms)) - ~@body))))) - (extend -nth ISeq (fn [s n] (when (empty? s) (throw @@ -2058,6 +1993,15 @@ user => (refer 'pixie.string :exclude '(substring))" m2))] (reduce merge2 (first maps) (next maps))))) +(defn every? + {:doc "Check if every element of the collection satisfies the predicate." + :added "0.1"} + [pred coll] + (cond + (nil? (seq coll)) true + (pred (first coll)) (recur pred (next coll)) + :else false)) + ; If you want a fn that uses destructuring in its parameter list, place ; it after this definition. If you don't, you will get compile failures ; in unrelated files. @@ -2410,6 +2354,24 @@ Calling this function on something that is not ISeqable returns a seq with that (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) +(defn interleave + "Returns a seq of all the items in the input collections interleaved" + ([] ()) + ([c1] (seq c1)) + ([c1 c2] + (lazy-seq + (let [s1 (seq c1) + s2 (seq c2)] + (when (and s1 s2) + (cons (first s1) (cons (first s2) + (interleave (next s1) (next s2)))))))) + ([& colls] + (lazy-seq + (let [ss (map seq colls)] + (when (every? identity ss) + (concat (map first ss) + (apply interleave (map next ss)))))))) + (defn min "Returns the smallest of all the arguments to this function. Assumes arguments are numeric" ([x] x) @@ -2421,3 +2383,41 @@ Calling this function on something that is not ISeqable returns a seq with that ([x] x) ([x y] (if (> x y) x y)) ([x y & zs] (apply max (max x y) zs))) + +(defn take-nth + "Returns a lazy seq of every nth item in coll. Returns a stateful + transducer when no collection is provided." + ([n] + (fn [rf] + (let [ia (atom -1)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (let [i (swap! ia inc)] + (if (zero? (rem i n)) + (rf result input) + result))))))) + ([n coll] + (lazy-seq + (when-let [s (seq coll)] + (cons (first s) (take-nth n (drop n s))))))) + +(defmacro loop + [bindings & body] + (let [vals (take-nth 2 (drop 1 bindings)) + bindings (take-nth 2 bindings) + binding-syms (map (fn [b] (if (symbol? b) b (gensym))) bindings) + binding-forms (transduce + (map (fn [bind] + (let [[b v s] bind] + (if (symbol? b) + [b v] + [s v b s])))) + concat + [] + (map vector bindings vals binding-syms))] + `(let ~(vec binding-forms) + (loop* ~(vec (interleave binding-syms binding-syms)) + (let ~(vec (interleave bindings binding-syms)) + ~@body))))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index c40dc7ca..c4816b44 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -405,13 +405,19 @@ (swap! cnt inc))) @cnt))) -(t/deftest test-loop-destructure +(t/deftest test-loop (t/assert= [3 -3] (loop [[a b :as vs] [0 0]] (if (> a 2) vs - (recur [(inc a) (dec b)]))))) + (recur [(inc a) (dec b)])))) + (t/assert= + 3 + (loop [a 1] + (if (> a 2) + a + (recur (inc a)))))) (t/deftest test-take-while (t/assert= (take-while pos? [1 2 3 -1]) [1 2 3]) From 34e129a41ccbd244e44934e81f3668af4e847837 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Sun, 26 Apr 2015 10:16:41 +0100 Subject: [PATCH 170/349] Add comment reader macro --- pixie/vm/reader.py | 10 ++++++++-- tests/pixie/tests/test-readeval.pxi | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 6173859b..d3872d12 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -627,9 +627,15 @@ def invoke(self, rdr, ch): if itm != rdr: acc = acc.conj(itm) +class CommentReader(ReaderHandler): + def invoke(self, rdr, ch): + read_inner(rdr, True, always_return_form=True) + return rdr + dispatch_handlers = { - u"{": SetReader(), - u"(": FnReader() + u"{": SetReader(), + u"(": FnReader(), + u"_": CommentReader() } class DispatchReader(ReaderHandler): diff --git a/tests/pixie/tests/test-readeval.pxi b/tests/pixie/tests/test-readeval.pxi index 4344bff6..636dca23 100644 --- a/tests/pixie/tests/test-readeval.pxi +++ b/tests/pixie/tests/test-readeval.pxi @@ -63,3 +63,11 @@ (t/assert= (read-string "{:foo :bar ; a comment\n }") '{:foo :bar}) (t/assert= (read-string "#{:foo ; a comment\n }") '#{:foo}) (t/assert= (read-string "{:foo ; a comment\n :bar }") '{:foo :bar})) + +(t/deftest test-comment-reader-macro + (t/assert= (read-string "(foo #_bar baz)") '(foo baz)) + (t/assert= (read-string "(foo #_ bar baz)") '(foo baz)) + (t/assert= (read-string "(foo #_ #_ bar baz)") '(foo)) + (t/assert= (read-string "(foo #_(bar goo) baz)") '(foo baz)) + (t/assert= (read-string "(foo bar #_baz)") '(foo bar)) + (t/assert= (read-string "(foo bar #_ ; comment \n baz)") '(foo bar))) From d954d72f7752634570be21acc162639dea1ad99c Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Mon, 4 May 2015 06:33:38 -0600 Subject: [PATCH 171/349] optimized performance and memory usage of custom types --- pixie/vm/custom_types.py | 104 ++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 13 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 081e57fc..b1aa73c9 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -6,6 +6,9 @@ from pixie.vm.keyword import Keyword import pixie.vm.rt as rt +MAX_FIELDS = 32 + + class CustomType(Type): _immutable_fields_ = ["_slots", "_rev?"] def __init__(self, name, slots): @@ -38,10 +41,9 @@ def get_num_slots(self): class CustomTypeInstance(Object): _immutable_fields_ = ["_type"] - def __init__(self, type, fields): + def __init__(self, type): affirm(isinstance(type, CustomType), u"Can't create a instance of a non custom type") self._custom_type = type - self._fields = fields def type(self): return self._custom_type @@ -52,17 +54,17 @@ def set_field(self, name, val): runtime_error(u"Invalid field named " + rt.name(rt.str(name)) + u" on type " + rt.name(rt.str(self.type())), u"pixie.stdlib/InvalidFieldException") - old_val = self._fields[idx] + old_val = self.get_field_by_idx(idx) if isinstance(old_val, AbstractMutableCell): - old_val.set_mutable_cell_value(self._custom_type, self._fields, name, idx, val) + old_val.set_mutable_cell_value(self._custom_type, self, name, idx, val) else: self._custom_type.set_mutable(name) - self._fields[idx] = val + self.set_field_by_idx(idx, val) return self @jit.elidable_promote() def _get_field_immutable(self, idx, rev): - return self._fields[idx] + return self.get_field_by_idx(idx) def get_field_immutable(self, idx): tp = self._custom_type @@ -76,7 +78,7 @@ def get_field(self, name): u"pixie.stdlib/InvalidFieldException") if self._custom_type.is_mutable(name): - value = self._fields[idx] + value = self.get_field_by_idx(idx) else: value = self.get_field_immutable(idx) @@ -86,11 +88,86 @@ def get_field(self, name): return value +create_type_prefix = """ +def new_inst(tp, fields): + l = len(fields) + if l >= {max_c}: + runtime_error(u"Too many fields for type", u"pixie.stdlib/TooManyFields") +""" + +clause_template = """ + elif l == {c}: + return CustomType{c}(tp, fields) +""" + +def gen_ct_code(): + acc = create_type_prefix.format(max_c=MAX_FIELDS + 1) + for x in range(MAX_FIELDS + 1): + acc += clause_template.format(c=x) + + #print acc + return acc + +exec gen_ct_code() + + +type_template = """ +class CustomType{c}(CustomTypeInstance): + def __init__(self, tp, fields): + CustomTypeInstance.__init__(self, tp) + {self_fields_list} = fields + + def get_field_by_idx(self, idx): + if idx >= {max}: + return None +""" + +get_field_by_idx_template = """ + elif idx == {c}: + return self._custom_field{c} +""" + +set_field_prefix_template = """ + def set_field_by_idx(self, idx, val): + if idx >= {max}: + return +""" + +set_field_by_idx_template = """ + elif idx == {c}: + self._custom_field{c} = val +""" + +def gen_ct_class_code(): + acc = "" + for x in range(MAX_FIELDS + 1): + if x == 0: + self_fields_list = "_null_" + elif x == 1: + self_fields_list = "self._custom_field0," + else: + self_fields_list = ",".join(map(lambda x: "self._custom_field" + str(x), range(x))) + acc += type_template.format(c=x, self_fields_list=self_fields_list, max=x) + for y in range(x): + acc += get_field_by_idx_template.format(c=y) + + acc += set_field_prefix_template.format(max=x) + + for y in range(x): + acc += set_field_by_idx_template.format(c=y) + + + + #print acc + return acc + +exec gen_ct_class_code() + + @as_var("create-type") def create_type(type_name, fields): affirm(isinstance(type_name, Keyword), u"Type name must be a keyword") - field_count = rt.count(fields) acc = {} for i in range(rt.count(fields)): val = rt.nth(fields, rt.wrap(i)) @@ -101,6 +178,7 @@ def create_type(type_name, fields): return CustomType(rt.name(type_name), acc) @as_var("new") +@jit.unroll_safe def _new__args(args): affirm(len(args) >= 1, u"new takes at least one parameter") tp = args[0] @@ -116,7 +194,7 @@ def _new__args(args): val = FloatMutableCell(val.float_val()) arr[x] = val - return CustomTypeInstance(tp, arr) + return new_inst(tp, arr) @as_var("set-field!") def set_field(inst, field, val): @@ -152,9 +230,9 @@ def set_mutable_cell_value(self, ct, fields, nm, idx, value): if not isinstance(value, Integer): ct.set_mutable(nm) if isinstance(value, Float): - fields[idx] = FloatMutableCell(value.float_val()) + fields.set_field_by_idx(idx, FloatMutableCell(value.float_val())) else: - fields[idx] = value + fields.set_field_by_idx(idx, value) else: self._mutable_integer_val = value.int_val() @@ -169,9 +247,9 @@ def set_mutable_cell_value(self, ct, fields, nm, idx, value): if not isinstance(value, Float): ct.set_mutable(nm) if isinstance(value, Integer): - fields[idx] = IntegerMutableCell(value.int_val()) + fields.set_field_by_idx(idx, IntegerMutableCell(value.int_val())) else: - fields[idx] = value + fields.set_field_by_idx(idx, value) else: self._mutable_float_val = value.float_val() From 765b20c7685df980a0ab1fd231958deab2b90c44 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 4 May 2015 16:58:22 +0100 Subject: [PATCH 172/349] fix formatting of time --- pixie/time.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/time.pxi b/pixie/time.pxi index 38f8a46b..a045b14f 100644 --- a/pixie/time.pxi +++ b/pixie/time.pxi @@ -5,5 +5,5 @@ [body] `(let [start# (uv/uv_hrtime) return# ~body] - (prn (str "Elapsed time: " (/ (- (uv/uv_hrtime) start#) 1000000.0) "ms")) + (prn (str "Elapsed time: " (/ (- (uv/uv_hrtime) start#) 1000000.0) " ms")) return#)) From 6efa5cf6e86ed510e2b3154a273f9ecda2f44acb Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 12 May 2015 17:10:20 +0100 Subject: [PATCH 173/349] add remove function --- pixie/stdlib.pxi | 9 +++++++++ tests/pixie/tests/test-stdlib.pxi | 3 +++ 2 files changed, 12 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6f260ade..6f14c9db 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1876,6 +1876,15 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (cons f (filter pred r)) (filter pred r))))))) +(defn remove + {:doc "Removes any element from the collection which matches the predicate. The complement of filter." + :signatures [[pred] [pred coll]] + :added "0.1"} + ([pred] + (filter (complement pred))) + ([pred coll] + (filter (complement pred) coll))) + (defn distinct {:doc "Returns the distinct elements in the collection." :signatures [[] [coll]] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index c4816b44..25643160 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -302,6 +302,9 @@ (t/assert= (into {} (filter (fn [[_ v]] (odd? v)) {:a 1, :b 2, :c 3, :d 4})) {:a 1 :c 3})) +(t/deftest test-remove + (t/assert= (remove even? [1 2 3 4 5]) '(1 3 5))) + (t/deftest test-distinct (t/assert= (seq (distinct [1 2 3 2 1])) '(1 2 3)) (t/assert= (vec (distinct) [1 1 2 2 3 3]) [1 2 3]) From 3c62749795970a4b2ca6c3b1c7a8816ec36518c0 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 15 May 2015 12:10:57 +0100 Subject: [PATCH 174/349] tcp streams satisfy IReduce * refactor out common io functionality to io/common --- pixie/io-blocking.pxi | 22 +++------------- pixie/io.pxi | 18 +++----------- pixie/io/common.pxi | 58 +++++++++++++++++++++++++++++++++++++++++++ pixie/io/tcp.pxi | 8 +++++- pixie/io/tty.pxi | 11 +------- 5 files changed, 73 insertions(+), 44 deletions(-) create mode 100644 pixie/io/common.pxi diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 9b4f3943..2d359d5b 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -1,5 +1,6 @@ (ns pixie.io-blocking - (:require [pixie.streams :as st :refer :all])) + (:require [pixie.streams :as st :refer :all] + [pixie.io.common :as common])) (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) @@ -15,21 +16,6 @@ (def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) - -(def DEFAULT-BUFFER-SIZE 1024) - -(defn default-stream-reducer [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc))))) - (deftype FileStream [fp] IInputStream (read [this buffer len] @@ -50,7 +36,7 @@ (fclose fp)) IReduce (-reduce [this f init] - (default-stream-reducer this f init))) + (common/stream-reducer this f init))) (defn open-read {:doc "Open a file for reading, returning a IInputStream" @@ -144,7 +130,7 @@ (pclose fp)) IReduce (-reduce [this f init] - (default-stream-reducer this f init))) + (common/stream-reducer this f init))) (defn popen-read diff --git a/pixie/io.pxi b/pixie/io.pxi index 9929018e..b5092ddc 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -12,9 +12,6 @@ (uv/defuvfsfn fs_write [file bufs nbufs offset] :result) (uv/defuvfsfn fs_close [file] :result) - -(def DEFAULT-BUFFER-SIZE 1024) - (deftype FileStream [fp offset uvbuf] IInputStream (read [this buffer len] @@ -40,16 +37,7 @@ (fs_close fp)) IReduce (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) + (common/stream-reducer this f init))) (defn open-read @@ -134,13 +122,13 @@ (defn buffered-output-stream ([downstream] - (buffered-output-stream downstream DEFAULT-BUFFER-SIZE)) + (buffered-output-stream downstream common/DEFAULT-BUFFER-SIZE)) ([downstream size] (->BufferedOutputStream downstream 0 (buffer size)))) (defn buffered-input-stream ([upstream] - (buffered-input-stream upstream DEFAULT-BUFFER-SIZE)) + (buffered-input-stream upstream common/DEFAULT-BUFFER-SIZE)) ([upstream size] (let [b (buffer size)] (set-buffer-count! b size) diff --git a/pixie/io/common.pxi b/pixie/io/common.pxi new file mode 100644 index 00000000..9f4737c5 --- /dev/null +++ b/pixie/io/common.pxi @@ -0,0 +1,58 @@ +(ns pixie.io.common + "Common functionality for handling IO" + (:require [pixie.streams :refer :all])) + +(def DEFAULT-BUFFER-SIZE 1024) + +(defn stream-reducer [this f init] + (let [buf (buffer DEFAULT-BUFFER-SIZE) + rrf (preserving-reduced f)] + (loop [acc init] + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] + (if (> read-count 0) + (let [result (reduce rrf acc buf)] + (if (not (reduced? result)) + (recur result) + @result)) + acc))))) + +(defn stream-reader [this buf len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) + read-cb (atom nil)] + (st/call-cc (fn [k] + (reset! read-cb (ffi/ffi-prep-callback + uv/uv_read_cb + (fn [stream nread uv-buf] + (set-buffer-count! buffer nread) + (try + (dispose! alloc-cb) + (dispose! @read-cb) + ;(dispose! uv-buf) + (uv/uv_read_stop stream) + (st/run-and-process k (or + (st/exception-on-uv-error nread) + nread)) + (catch ex + (println ex)))))) + (uv/uv_read_start uv-client alloc-cb @read-cb))))) + +(defn stream-writer + [this buf] + (let [write-cb (atom nil) + uv_write (uv/uv_write_t)] + (ffi/set! uv-write-buf :base buffer) + (ffi/set! uv-write-buf :len (count buffer)) + (st/call-cc + (fn [k] + (reset! write-cb (ffi/ffi-prep-callback + uv/uv_write_cb + (fn [req status] + (try + (dispose! @write-cb) + ;(uv/uv_close uv_write st/close_cb) + (st/run-and-process k status) + (catch ex + (println ex)))))) + (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 2ca440f4..5e22dda9 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -1,9 +1,12 @@ (ns pixie.io.tcp (:require [pixie.stacklets :as st] [pixie.streams :refer [IInputStream read IOutputStream write]] + [pixie.io.common :as common] [pixie.uv :as uv] [pixie.ffi :as ffi])) +(def DEFAULT-BUFFER-SIZE 1024) + (defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb] IDisposable (-dispose! [this] @@ -55,7 +58,10 @@ IDisposable (-dispose! [this] (dispose! uv-write-buf) - (uv/uv_close uv-client st/close_cb))) + (uv/uv_close uv-client st/close_cb)) + IReduce + (-reduce [this f init] + (common/default-stream-reducer this f init))) (defn launch-tcp-client-from-server [svr] (assert (instance? TCPServer svr) "Requires a TCPServer as the first argument") diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index 24a909cd..060c5f0d 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -39,16 +39,7 @@ IReduce (-reduce [this f init] - (let [buf (buffer DEFAULT-BUFFER-SIZE) - rrf (preserving-reduced f)] - (loop [acc init] - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] - (if (> read-count 0) - (let [result (reduce rrf acc buf)] - (if (not (reduced? result)) - (recur result) - @result)) - acc)))))) + (common/default-stream-reducer this f init))) (deftype TTYOutputStream [uv-client uv-write-buf] IOutputStream From 41203fe7c6ad152b5374055ea91f1f36348fb92b Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 15 May 2015 12:19:18 +0100 Subject: [PATCH 175/349] refactor tcp and tty --- pixie/io.pxi | 1 + pixie/io/common.pxi | 11 +++++++---- pixie/io/tcp.pxi | 44 +++----------------------------------------- pixie/io/tty.pxi | 45 ++++----------------------------------------- 4 files changed, 15 insertions(+), 86 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index b5092ddc..f90ec346 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -2,6 +2,7 @@ (:require [pixie.streams :as st :refer :all] [pixie.streams.utf8 :as utf8] [pixie.io-blocking :as io-blocking] + [pixie.io.common :as common] [pixie.uv :as uv] [pixie.stacklets :as st] [pixie.ffi :as ffi] diff --git a/pixie/io/common.pxi b/pixie/io/common.pxi index 9f4737c5..ee23bdef 100644 --- a/pixie/io/common.pxi +++ b/pixie/io/common.pxi @@ -1,6 +1,9 @@ (ns pixie.io.common "Common functionality for handling IO" - (:require [pixie.streams :refer :all])) + (:require [pixie.streams :refer :all] + [pixie.uv :as uv] + [pixie.stacklets :as st] + [pixie.ffi :as ffi])) (def DEFAULT-BUFFER-SIZE 1024) @@ -16,7 +19,7 @@ @result)) acc))))) -(defn stream-reader [this buf len] +(defn cb-stream-reader [uv-client buffer len] (assert (<= (buffer-capacity buffer) len) "Not enough capacity in the buffer") (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) @@ -38,8 +41,8 @@ (println ex)))))) (uv/uv_read_start uv-client alloc-cb @read-cb))))) -(defn stream-writer - [this buf] +(defn cb-stream-writer + [uv-client uv-write-buf buffer] (let [write-cb (atom nil) uv_write (uv/uv_write_t)] (ffi/set! uv-write-buf :base buffer) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 5e22dda9..b3945782 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -5,8 +5,6 @@ [pixie.uv :as uv] [pixie.ffi :as ffi])) -(def DEFAULT-BUFFER-SIZE 1024) - (defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb] IDisposable (-dispose! [this] @@ -17,51 +15,17 @@ (deftype TCPStream [uv-client uv-write-buf] IInputStream (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) - "Not enough capacity in the buffer") - (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) - read-cb (atom nil)] - (st/call-cc (fn [k] - (reset! read-cb (ffi/ffi-prep-callback - uv/uv_read_cb - (fn [stream nread uv-buf] - (set-buffer-count! buffer nread) - (try - (dispose! alloc-cb) - (dispose! @read-cb) - ;(dispose! uv-buf) - (uv/uv_read_stop stream) - (st/run-and-process k (or - (st/exception-on-uv-error nread) - nread)) - (catch ex - (println ex)))))) - (uv/uv_read_start uv-client alloc-cb @read-cb))))) + (common/cb-stream-reader uv-client buffer len)) IOutputStream (write [this buffer] - (let [write-cb (atom nil) - uv_write (uv/uv_write_t)] - (ffi/set! uv-write-buf :base buffer) - (ffi/set! uv-write-buf :len (count buffer)) - (st/call-cc - (fn [k] - (reset! write-cb (ffi/ffi-prep-callback - uv/uv_write_cb - (fn [req status] - (try - (dispose! @write-cb) - ;(uv/uv_close uv_write st/close_cb) - (st/run-and-process k status) - (catch ex - (println ex)))))) - (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) + (common/cb-stream-writer uv-client uv-write-buf buffer)) IDisposable (-dispose! [this] (dispose! uv-write-buf) (uv/uv_close uv-client st/close_cb)) IReduce (-reduce [this f init] - (common/default-stream-reducer this f init))) + (common/stream-reducer this f init))) (defn launch-tcp-client-from-server [svr] (assert (instance? TCPServer svr) "Requires a TCPServer as the first argument") @@ -74,8 +38,6 @@ (do (uv/uv_close client nil) svr)))) - - (defn tcp-server "Creates a TCP server on the given ip (as a string) and port (as an integer). Returns a TCPServer that can be shutdown with dispose!. on-connection is a function that will be passed a TCPStream for each connecting client." diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index 060c5f0d..0acedfe8 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -3,63 +3,26 @@ [pixie.streams :refer [IInputStream read IOutputStream write]] [pixie.uv :as uv] [pixie.io :as io] + [pixie.io.common :as common] [pixie.system :as sys] [pixie.ffi :as ffi])) -(def DEFAULT-BUFFER-SIZE 1024) - (deftype TTYInputStream [uv-client uv-write-buf] IInputStream (read [this buf len] - (assert (<= (buffer-capacity buf) len) - "Not enough capacity in the buffer") - (let [alloc-cb (uv/-prep-uv-buffer-fn buf len) - read-cb (atom nil)] - (st/call-cc (fn [k] - (reset! read-cb (ffi/ffi-prep-callback - uv/uv_read_cb - (fn [stream nread uv-buf] - (set-buffer-count! buf nread) - (try - (dispose! alloc-cb) - (dispose! @read-cb) - ;(dispose! uv-buf) - (uv/uv_read_stop stream) - (st/run-and-process k (or - (st/exception-on-uv-error nread) - nread)) - (catch ex - (println ex)))))) - (uv/uv_read_start uv-client alloc-cb @read-cb))))) - + (common/cb-stream-reader uv-client buf len)) IDisposable (-dispose! [this] (dispose! uvbuf) (fs_close fp)) - IReduce (-reduce [this f init] - (common/default-stream-reducer this f init))) + (common/stream-reducer this f init))) (deftype TTYOutputStream [uv-client uv-write-buf] IOutputStream (write [this buffer] - (let [write-cb (atom nil) - uv_write (uv/uv_write_t)] - (ffi/set! uv-write-buf :base buffer) - (ffi/set! uv-write-buf :len (count buffer)) - (st/call-cc - (fn [k] - (reset! write-cb (ffi/ffi-prep-callback - uv/uv_write_cb - (fn [req status] - (try - (dispose! @write-cb) - (st/run-and-process k status) - (catch ex - (println ex)))))) - (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) - + (common/cb-stream-writer uv-client uv-write-buf buffer)) IDisposable (-dispose! [this] (dispose! uv-write-buf) From ce47508849b9cd52c6d60845c0921a877e61149a Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 15 May 2015 12:53:14 +0100 Subject: [PATCH 176/349] remove unused requires --- pixie/io-blocking.pxi | 3 --- pixie/io.pxi | 1 - pixie/io/tty.pxi | 4 +--- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 2d359d5b..ecfbd5ee 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -91,7 +91,6 @@ (reduced cnt) (+ cnt written))))))) - (defn spit [filename val] (transduce (map int) (file-output-rf filename) @@ -132,7 +131,6 @@ (-reduce [this f init] (common/stream-reducer this f init))) - (defn popen-read {:doc "Open a file for reading, returning a IInputStream" :added "0.1"} @@ -140,7 +138,6 @@ (assert (string? command) "Command must be a string") (->ProcessInputStream (popen command "r"))) - (defn run-command [command] (let [c (->ProcessInputStream (popen command "r")) result (transduce diff --git a/pixie/io.pxi b/pixie/io.pxi index f90ec346..e589b34b 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -40,7 +40,6 @@ (-reduce [this f init] (common/stream-reducer this f init))) - (defn open-read {:doc "Open a file for reading, returning a IInputStream" :added "0.1"} diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index 0acedfe8..cc75ad2b 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -2,10 +2,8 @@ (:require [pixie.stacklets :as st] [pixie.streams :refer [IInputStream read IOutputStream write]] [pixie.uv :as uv] - [pixie.io :as io] [pixie.io.common :as common] - [pixie.system :as sys] - [pixie.ffi :as ffi])) + [pixie.system :as sys])) (deftype TTYInputStream [uv-client uv-write-buf] IInputStream From eff528b20be407916713f1ddadb0f3a32a54d6b0 Mon Sep 17 00:00:00 2001 From: Julius Ring Date: Tue, 19 May 2015 20:24:35 +0200 Subject: [PATCH 177/349] Make comp work when the number of arguments is divisible by 4. --- pixie/stdlib.pxi | 1 + tests/pixie/tests/test-stdlib.pxi | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6f14c9db..f9754580 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -767,6 +767,7 @@ there's a value associated with the key. Use `some` for checking for values." :examples [["((comp inc first) [41 2 3])" nil 42]] :signatures [[f] [f & fs]] :added "0.1"} + ([] identity) ([f] f) ([f1 f2] (fn [& args] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 25643160..7b98f74a 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -530,3 +530,7 @@ (t/assert= 5050 (reduce + (range 101))) (t/assert= 3628800 (reduce * (range 1 11))) (t/assert= 5051 (reduce + 1 (range 101)))) + +(t/deftest test-comp + (t/assert= 5 ((comp inc inc inc inc) 1)) + (t/assert= :xyz ((comp) :xyz))) From d261289bf299c4fb57021428fecf35978a7e5ff4 Mon Sep 17 00:00:00 2001 From: Justin Jaffray Date: Tue, 19 May 2015 14:43:35 -0400 Subject: [PATCH 178/349] exchange_result_libffi -> exchange_result In current pypy (as of https://bitbucket.org/pypy/pypy/commits/749bf9a13d9ccf18ed9be89ac3f3ec4dd6b11a76), exchange_result_libffi has been removed. This means that anyone installing Pixie now and pulling down the latest pypy will be unable to build (as in #318). A lot of the logic for dealing with endianness has been pushed into rpython, meaning pixie/pypy don't need to deal with it. --- pixie/vm/libs/ffi.py | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index b8b92512..a733464d 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -119,7 +119,7 @@ def prep_exb(self, args): return exb, tokens def get_ret_val_from_buffer(self, exb): - offset_p = rffi.ptradd(exb, jit.promote(self._cd.exchange_result_libffi)) + offset_p = rffi.ptradd(exb, jit.promote(self._cd.exchange_result)) ret_val = self._ret_type.ffi_get_value(offset_p) return ret_val @@ -804,7 +804,6 @@ def prep_ffi_call__args(args): import sys -BIG_ENDIAN = sys.byteorder == 'big' USE_C_LIBFFI_MSVC = getattr(clibffi, 'USE_C_LIBFFI_MSVC', False) @@ -869,16 +868,6 @@ def fb_build_exchange(self, cif_descr): exchange_offset = rffi.sizeof(rffi.VOIDP) * nargs exchange_offset = self.align_arg(exchange_offset) cif_descr.exchange_result = exchange_offset - cif_descr.exchange_result_libffi = exchange_offset - - if BIG_ENDIAN and self.fresult.is_primitive_integer: - # For results of precisely these types, libffi has a - # strange rule that they will be returned as a whole - # 'ffi_arg' if they are smaller. The difference - # only matters on big-endian. - if self.fresult.size < SIZE_OF_FFI_ARG: - diff = SIZE_OF_FFI_ARG - self.fresult.size - cif_descr.exchange_result += diff # then enough room for the result, rounded up to sizeof(ffi_arg) exchange_offset += max(rffi.getintfield(self.rtype, 'c_size'), From 01c8776a2f9b9e3f87f78c6c70ab8bedd828b8d1 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 20 May 2015 12:54:08 +0100 Subject: [PATCH 179/349] keywords can now be fully qualified as in clojure --- pixie/vm/code.py | 20 ++++++++++++-------- pixie/vm/reader.py | 19 +++++++++++-------- tests/pixie/tests/test-keywords.pxi | 8 ++++++++ 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index b1ac4caa..bba4631a 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -544,6 +544,17 @@ def add_refer_symbol(self, sym, var): def include_stdlib(self): stdlib = _ns_registry.find_or_make(u"pixie.stdlib") self.add_refer(stdlib, refer_all=True) + + def resolve_ns(self, ns_alias): + refer = self._refers.get(ns_alias, None) + resolved_ns = None + if refer is not None: + resolved_ns = refer._namespace + if resolved_ns is None: + resolved_ns = _ns_registry.get(ns_alias, None) + if resolved_ns is None: + affirm(False, u"Unable to resolve namespace: " + ns_alias + u" inside namespace " + self._name) + return resolved_ns def resolve(self, s, use_refers=True): import pixie.vm.symbol as symbol @@ -552,14 +563,7 @@ def resolve(self, s, use_refers=True): name = rt.name(s) if ns is not None: - refer = self._refers.get(ns, None) - resolved_ns = None - if refer is not None: - resolved_ns = refer._namespace - if resolved_ns is None: - resolved_ns = _ns_registry.get(ns, None) - if resolved_ns is None: - affirm(False, u"Unable to resolve namespace: " + ns + u" inside namespace " + self._name) + resolved_ns = self.resolve_ns(ns) else: resolved_ns = self diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index d3872d12..64ad57c9 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -333,21 +333,24 @@ def invoke(self, rdr, ch): return cons(symbol(u"quote"), cons(itm)) class KeywordReader(ReaderHandler): + def fqd(self, itm): + ns_alias = rt.namespace(itm) + current_nms = rt.ns.deref() + + if ns_alias is None: + return keyword(rt.name(itm), rt.name(current_nms)) + else: + ns_fqd = current_nms.resolve_ns(ns_alias) + return keyword(rt.name(itm), rt.name(ns_fqd)) + def invoke(self, rdr, ch): - nms = u"" ch = rdr.read() if ch == u":": itm = read_inner(rdr, True) - nms = rt.name(rt.ns.deref()) + return self.fqd(itm) else: rdr.unread() itm = read_inner(rdr, True) - - affirm(isinstance(itm, Symbol), u"Can't keyword quote a non-symbol") - if nms: - affirm(rt.namespace(itm) is None, u"Kewyword cannot have two namespaces") - return keyword(rt.name(itm), nms) - else: return keyword(rt.name(itm), rt.namespace(itm)) class LiteralStringReader(ReaderHandler): diff --git a/tests/pixie/tests/test-keywords.pxi b/tests/pixie/tests/test-keywords.pxi index 5156d27a..cdd0672c 100644 --- a/tests/pixie/tests/test-keywords.pxi +++ b/tests/pixie/tests/test-keywords.pxi @@ -14,6 +14,14 @@ (t/assert= (namespace :cat/dog) "cat") (t/assert= (namespace ::foo) "pixie.tests.test-keywords")) +(t/deftest fqd-keywords + (t/assert-throws? (read-string "::x/bar")) + (t/assert-throws? (read-string "::a.b/foo")) + (refer-ns 'my.other.ns 'my.fake.core 'fake) + (binding [*ns* (the-ns 'my.other.ns)] + (t/assert= :my.fake.core/foo (read-string "::fake/foo")) + (t/assert= :my.fake.core/foo (read-string "::my.fake.core/foo")) + (t/assert-throws? (read-string "::f/foo")))) (t/deftest keyword-equality (t/assert= :foo/bar :foo/bar) From d99623d395f23a0ab4276a36df85fcc43d49fe98 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 31 May 2015 10:29:35 +0100 Subject: [PATCH 180/349] fixes typos --- pixie/channels.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index c44cc060..069bb2c6 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -46,7 +46,7 @@ (b/empty-buffer? puts)) nil (let [[val cfn] (b/remove! puts)] - (if (cancelled? cfn) + (if (canceled? cfn) (recur) (do (st/-run-later (partial cfn true)) (b/add! buffer val) From 54d503272e54256f7d4be7eb9b007c4ee3b7f92a Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 31 May 2015 13:45:52 +0100 Subject: [PATCH 181/349] adds ns-aliases lists all the aliases in a given a namespace as a map of alias -> ns --- pixie/stdlib.pxi | 5 +++++ pixie/vm/code.py | 2 +- pixie/vm/stdlib.py | 20 ++++++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 9 +++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6f14c9db..a973ec1e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2430,3 +2430,8 @@ Calling this function on something that is not ISeqable returns a seq with that (loop* ~(vec (interleave binding-syms binding-syms)) (let ~(vec (interleave bindings binding-syms)) ~@body))))) + +(extend -str Namespace + (fn [v] (str ""))) + +(extend -repr Namespace -str) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index b1ac4caa..b79fd8cd 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -540,7 +540,7 @@ def add_refer_symbol(self, sym, var): self._registry[name] = var return var - + def include_stdlib(self): stdlib = _ns_registry.find_or_make(u"pixie.stdlib") self.add_refer(stdlib, refer_all=True) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 05c309c3..5b4326a0 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -553,6 +553,26 @@ def ns_map(ns): return nil +@as_var("ns-aliases") +def ns_aliases(ns): + from pixie.vm.code import Namespace + from pixie.vm.symbol import Symbol + affirm(isinstance(ns, Namespace) or isinstance(ns, Symbol), u"ns must be a symbol or a namespace") + + if isinstance(ns, Symbol): + ns = rt.the_ns(ns) + if ns is nil: + return nil + + if isinstance(ns, Namespace): + m = rt.hashmap() + for alias in ns._refers: + refered_ns = ns._refers[alias]._namespace + m = rt.assoc(m, rt.symbol(rt.wrap(alias)), refered_ns) + return m + + return nil + @as_var("refer-ns") def refer(ns, refer, alias): from pixie.vm.symbol import Symbol diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 25643160..d291874b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -392,6 +392,15 @@ (t/assert= (set (keys (ns-map 'foo))) #{'bar 'baz})) +(t/deftest test-ns-aliases + (in-ns :ns-to-require) + (in-ns :my-fake-ns) + (require ns-to-require :as some-alias) + (in-ns :pixie.tests.test-stdlib) + (t/assert= {'some-alias (the-ns 'ns-to-require) + 'pixie.stdlib (the-ns 'pixie.stdlib)} + (ns-aliases (the-ns 'my-fake-ns)))) + (t/deftest test-while (t/assert= (while (pos? 0) true ) nil) (t/assert= (while (pos? 0) false) nil) From 41aca09e3a737a64eed97333bbef083ae50a3f34 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 1 Jun 2015 09:41:47 +0100 Subject: [PATCH 182/349] remove unused buffer for input streams --- pixie/channels.pxi | 2 +- pixie/io.pxi | 8 ++++---- pixie/io/tty.pxi | 10 ++++------ pixie/stacklets.pxi | 2 +- pixie/uv.pxi | 2 +- tests/pixie/tests/test-io.pxi | 4 +++- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index c44cc060..84b60474 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -23,7 +23,7 @@ (cond (= idx 0) val (= idx 1) cfn - :else (throw "Index out of range"))) + :else (throw [::OutOfRangeException "Index out of range"]))) (-nth-not-found [this idx not-found] (cond (= idx 0) val diff --git a/pixie/io.pxi b/pixie/io.pxi index e589b34b..a37188f6 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -79,7 +79,7 @@ _ (pixie.ffi/set! uvbuf :len (- (count buffer) buffer-offset)) write-count (fs_write fp uvbuf 1 offset)] (when (neg? write-count) - (throw (uv/uv_err_name read-count))) + (throw [::FileOutputStreamException (uv/uv_err_name read-count)])) (set-field! this :offset (+ offset write-count)) (if (< (+ buffer-offset write-count) (count buffer)) (recur (+ buffer-offset write-count)) @@ -136,7 +136,7 @@ (defn throw-on-error [result] (when (neg? result) - (throw (uv/uv_err_name result))) + (throw [::UVException (uv/uv_err_name result)])) result) (defn open-write @@ -169,7 +169,7 @@ utf8/utf8-output-stream-rf) (str content)) - :else (throw "Expected a string or IOutputStream"))) + :else (throw [::Exception "Expected a string or IOutputStream"]))) (defn slurp "Reads in the contents of input. Input must be a filename or an IInputStream" @@ -177,7 +177,7 @@ (let [stream (cond (string? input) (open-read input) (satisfies? IInputStream input) input - :else (throw "Expected a string or an IInputStream")) + :else (throw [:pixie.io/Exception "Expected a string or an IInputStream"])) result (transduce (map char) string-builder diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index cc75ad2b..44386f3e 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -5,14 +5,13 @@ [pixie.io.common :as common] [pixie.system :as sys])) -(deftype TTYInputStream [uv-client uv-write-buf] +(deftype TTYInputStream [uv-client] IInputStream (read [this buf len] (common/cb-stream-reader uv-client buf len)) IDisposable (-dispose! [this] - (dispose! uvbuf) - (fs_close fp)) + (uv/uv_close uv-client st/close_cb)) IReduce (-reduce [this f init] (common/stream-reducer this f init))) @@ -35,10 +34,9 @@ (defn tty-input-stream [fd] ;(assert (= uv/UV_TTY (uv/uv_guess_handle fd)) "fd is not a TTY") - (let [buf (uv/uv_buf_t) - tty (uv/uv_tty_t)] + (let [tty (uv/uv_tty_t)] (uv/uv_tty_init (uv/uv_default_loop) tty fd 0) - (->TTYInputStream tty buf))) + (->TTYInputStream tty))) (def stdin (tty-input-stream sys/stdin)) (def stdout (tty-output-stream sys/stdout)) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 30e0ada3..1255fde0 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -36,7 +36,7 @@ (reset! stacklet-loop-h h) (-set-current-var-frames nil frames) (if (instance? ThrowException val) - (throw (:ex val)) + (throw [::Exception (:ex val)]) val))) (defn -run-later [f] diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 199942f4..06f7af7d 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -231,7 +231,7 @@ (defn throw-on-error [result] (if (neg? result) - (throw (str "UV Error: " (uv_err_name result))) + (throw [::UVException (str "UV Error: " (uv_err_name result))]) result)) (defmacro defuvfsfn diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index c93e3dd9..eb47b86c 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -38,4 +38,6 @@ (t/deftest test-slurp-spit (let [val (vec (range 1280))] (io/spit "test.tmp" val) - (t/assert= val (read-string (io/slurp "test.tmp"))))) + (t/assert= val (read-string (io/slurp "test.tmp")))) + (t/assert-throws? (io/slurp 1)) + (t/assert-throws? (io/slurp :foo))) From 7225c81bb5750600ae3de3207128bec0e2a5978c Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 1 Jun 2015 09:34:25 +0100 Subject: [PATCH 183/349] slurping a utf-8 file works --- pixie/io.pxi | 11 ++++--- pixie/streams/utf8.pxi | 53 ++++++++++++++++++------------ tests/pixie/tests/test-io-utf8.txt | 1 + tests/pixie/tests/test-io.pxi | 4 ++- 4 files changed, 43 insertions(+), 26 deletions(-) create mode 100644 tests/pixie/tests/test-io-utf8.txt diff --git a/pixie/io.pxi b/pixie/io.pxi index a37188f6..56452320 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -113,9 +113,10 @@ (when (= idx (count buffer)) (set-field! this :idx 0) (read upstream buffer (buffer-capacity buffer))) - (let [val (nth buffer idx)] - (set-field! this :idx (inc idx)) - val)) + (when (pos? (count buffer)) + (let [val (nth buffer idx)] + (set-field! this :idx (inc idx)) + val))) IDisposable (-dispose! [this] (dispose! buffer))) @@ -181,7 +182,9 @@ result (transduce (map char) string-builder - stream)] + (-> stream + buffered-input-stream + utf8/utf8-input-stream))] (dispose! stream) result)) diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi index bc9b4044..e5605e18 100644 --- a/pixie/streams/utf8.pxi +++ b/pixie/streams/utf8.pxi @@ -31,29 +31,40 @@ (deftype UTF8InputStream [in bad-char] IUTF8InputStream (read-char [this] - (let [ch (int (read-byte in)) - [n bytes error?] (cond - (>= 0x7F ch) [ch 1] - (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2 false] - (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3 false] - (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4 false] - (= 0xF8 (bit-and ch 0xF8)) [(bit-and ch 3) 5 true] - (= 0xFC (bit-and ch 0xFE)) [(bit-and ch 1) 6 true] - :else [n 1 true])] - (loop [i (dec bytes) - n n] - (if (pos? i) - (recur (dec i) - (bit-or (bit-shift-left n 6) - (bit-and (read-byte in) 0x3F))) - (if error? - (if bad-char - bad-char - (throw (str "Invalid UTF8 character decoded: " n))) - (char n)))))) + (when-let [byte (read-byte in)] + (let [ch (int byte) + [n bytes error?] (cond + (>= 0x7F ch) [ch 1] + (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2 false] + (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3 false] + (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4 false] + (= 0xF8 (bit-and ch 0xF8)) [(bit-and ch 3) 5 true] + (= 0xFC (bit-and ch 0xFE)) [(bit-and ch 1) 6 true] + :else [n 1 true])] + (loop [i (dec bytes) + n n] + (if (pos? i) + (recur (dec i) + (bit-or (bit-shift-left n 6) + (bit-and (read-byte in) 0x3F))) + (if error? + (if bad-char + bad-char + (throw [::invalid-character (str "Invalid UTF8 character decoded: " n)])) + (char n))))))) IDisposable (-dispose! [this] - (dispose! in))) + (dispose! in)) + IReduce + (-reduce [this f init] + (let [rrf (preserving-reduced f)] + (loop [acc init] + (if-let [char (read-char this)] + (let [result (rrf acc (int char))] + (if (not (reduced? result)) + (recur result) + @result)) + acc))))) (defn utf8-input-stream "Creates a UTF8 decoder that reads characters from the given IByteInputStream. If a bad character is found diff --git a/tests/pixie/tests/test-io-utf8.txt b/tests/pixie/tests/test-io-utf8.txt new file mode 100644 index 00000000..37bf4044 --- /dev/null +++ b/tests/pixie/tests/test-io-utf8.txt @@ -0,0 +1 @@ +I love 🍺 . This is a thumbs up 👍 diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index eb47b86c..16f3778b 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -40,4 +40,6 @@ (io/spit "test.tmp" val) (t/assert= val (read-string (io/slurp "test.tmp")))) (t/assert-throws? (io/slurp 1)) - (t/assert-throws? (io/slurp :foo))) + (t/assert-throws? (io/slurp :foo)) + (t/assert= "I love 🍺 . This is a thumbs up 👍\n" + (io/slurp "tests/pixie/tests/test-io-utf8.txt"))) From 5970927cae69439d6c10d4d34b2aa30294536e3c Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 3 Jun 2015 17:17:29 +0100 Subject: [PATCH 184/349] adds promotion to bigint on overflow --- pixie/vm/numbers.py | 33 ++++++++++++++++++++++++++---- tests/pixie/tests/test-numbers.pxi | 11 ++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index ed54bd53..eac2878f 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -1,7 +1,7 @@ import pixie.vm.object as object from pixie.vm.object import affirm from pixie.vm.primitives import true, false -from rpython.rlib.rarithmetic import r_uint +from rpython.rlib.rarithmetic import r_uint, ovfcheck from rpython.rlib.rbigint import rbigint import rpython.rlib.jit as jit from pixie.vm.code import DoublePolymorphicFn, extend, Protocol, as_var, wrap_fn @@ -116,12 +116,29 @@ def {pfn}_{ty1}_{ty2}(a, b): return {wrap_start}a.{conv1}() {op} b.{conv2}(){wrap_end} """ +ovf_op_template = """@extend({pfn}, {ty1}._type, {ty2}._type) +def {pfn}_{ty1}_{ty2}(a, b): + assert isinstance(a, {ty1}) and isinstance(b, {ty2}) + try: + z = ovfcheck(a.{conv1}() {op} b.{conv2}()) + return {wrap_start}z{wrap_end} + except OverflowError: + z = rbigint.fromint(a.{conv1}()).{method_op}(rbigint.fromint(b.{conv2}())) + return {wrap_start}z{wrap_end} +""" + def extend_num_op(pfn, ty1, ty2, conv1, op, conv2, wrap_start = "rt.wrap(", wrap_end = ")"): tp = num_op_template.format(pfn=pfn, ty1=ty1.__name__, ty2=ty2.__name__, conv1=conv1, op=op, conv2=conv2, wrap_start=wrap_start, wrap_end=wrap_end) exec tp +def extend_ovf_op(pfn, ty1, ty2, conv1, op, method_op, conv2, wrap_start = "rt.wrap(", wrap_end = ")"): + tp = ovf_op_template.format(pfn=pfn, ty1=ty1.__name__, ty2=ty2.__name__, + conv1=conv1, op=op, method_op=method_op, conv2=conv2, + wrap_start=wrap_start, wrap_end=wrap_end) + exec tp + extend_num_op("_quot", Integer, Integer, "int_val", "/", "int_val") extend_num_op("_rem", Integer, Integer, "int_val", "%", "int_val") @@ -133,7 +150,14 @@ def define_num_ops(): for (op, sym) in [("_add", "+"), ("_sub", "-"), ("_mul", "*"), ("_div", "/")]: if op == "_div" and c1 == Integer and c2 == Integer: continue - extend_num_op(op, c1, c2, conv1, sym, conv2) + elif op == "_add" and c1 == Integer and c2 == Integer: + extend_ovf_op(op, c1, c2, conv1, sym, "add", conv2) + elif op == "_sub" and c1 == Integer and c2 == Integer: + extend_ovf_op(op, c1, c2, conv1, sym, "sub", conv2) + elif op == "_mul" and c1 == Integer and c2 == Integer: + extend_ovf_op(op, c1, c2, conv1, sym, "mul", conv2) + else: + extend_num_op(op, c1, c2, conv1, sym, conv2) if c1 != Integer or c2 != Integer: extend_num_op("_rem", c1, c2, conv1, ",", conv2, wrap_start = "rt.wrap(math.fmod(", wrap_end = "))") extend_num_op("_quot", c1, c2, conv1, "/", conv2, wrap_start = "rt.wrap(math.floor(", wrap_end = "))") @@ -157,9 +181,10 @@ def define_bigint_ops(): continue for (pfn, op) in [("_add", "add"), ("_sub", "sub"), ("_mul", "mul"), ("_div", "div"), ("_num_eq", "eq"), ("_lt", "lt"), ("_gt", "gt"), ("_lte", "le"), ("_gte", "ge")]: + code = bigint_ops_tmpl.format(pfn=pfn, op=op, - ty1=c1.__name__, conv1=conv1, get1=get1, - ty2=c2.__name__, conv2=conv2, get2=get2) + ty1=c1.__name__, conv1=conv1, get1=get1, + ty2=c2.__name__, conv2=conv2, get2=get2) exec code define_bigint_ops() diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 3b5f0aeb..0152adc4 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -62,3 +62,14 @@ (t/assert= Integer (type (quot 7/2 3/7))) (t/assert= Float (type (quot 7/2 3.0)))) +(t/deftest test-big-int-eq + (t/assert (-num-eq 1N 1)) + (t/assert (-num-eq 1 1N)) + ;(t/assert= 1N 1) this fails, should it? + (t/assert= 1 1N)) + +(t/deftest test-promotion + (t/assert= BigInteger (type (reduce * 1 (range 1 100)))) + (t/assert (-num-eq 1000000000000000000000N (* 10000000 + 10000000 + 10000000)))) From 45edc957c78dc6ad816ef1b34239adc4656452e7 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 3 Jun 2015 22:04:20 +0100 Subject: [PATCH 185/349] Add BigInteger to pxic_writer this should make compile_tests work --- pixie/vm/libs/pxic/writer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index 8f1318ec..5dd39dd0 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -4,7 +4,7 @@ from pixie.vm.string import String from pixie.vm.keyword import Keyword from pixie.vm.symbol import Symbol -from pixie.vm.numbers import Integer, Float +from pixie.vm.numbers import Integer, BigInteger, Float from pixie.vm.code import Code, Var, NativeFn, Namespace from pixie.vm.primitives import nil, true, false from pixie.vm.reader import LinePromise @@ -245,6 +245,8 @@ def write_object(obj, wtr): write_string(rt.name(obj), wtr) elif isinstance(obj, Integer): write_int(obj.int_val(), wtr) + elif isinstance(obj, BigInteger): + write_int(obj.bigint_val(), wtr) elif isinstance(obj, Float): write_float(obj.float_val(), wtr) elif isinstance(obj, Code): From fde801ff0b1a914a0a80b537198499ded8b33531 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 5 Jun 2015 13:44:38 +0100 Subject: [PATCH 186/349] Add a BIGINT_STRING and BIGINT to reader & writer BIGINT has not yet been implemented, BigIntegers will be written as strings --- pixie/vm/libs/pxic/reader.py | 5 ++++- pixie/vm/libs/pxic/tags.py | 2 ++ pixie/vm/libs/pxic/writer.py | 8 +++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/pixie/vm/libs/pxic/reader.py b/pixie/vm/libs/pxic/reader.py index 571cbddc..d3b44613 100644 --- a/pixie/vm/libs/pxic/reader.py +++ b/pixie/vm/libs/pxic/reader.py @@ -4,7 +4,7 @@ from pixie.vm.string import String from pixie.vm.keyword import Keyword, keyword from pixie.vm.symbol import Symbol, symbol -from pixie.vm.numbers import Integer, Float +from pixie.vm.numbers import Integer, Float, BigInteger from pixie.vm.code import Code, Var, NativeFn, Namespace, intern_var import pixie.vm.code as code from pixie.vm.primitives import nil, true, false @@ -13,6 +13,7 @@ from pixie.vm.persistent_list import create_from_list from pixie.vm.reader import LinePromise from rpython.rlib.rarithmetic import r_uint, intmask +from rpython.rlib.rbigint import rbigint from pixie.vm.libs.pxic.util import read_handlers import pixie.vm.rt as rt @@ -172,6 +173,8 @@ def read_obj(rdr): return read_namespace(rdr) elif tag == INT_STRING: return Integer(int(read_raw_string(rdr))) + elif tag == BIGINT_STRING: + return BigInteger(rbigint.fromstr(str(read_raw_string(rdr)))) elif tag == NEW_CACHED_OBJ: diff --git a/pixie/vm/libs/pxic/tags.py b/pixie/vm/libs/pxic/tags.py index abe92ac2..eb7694f8 100644 --- a/pixie/vm/libs/pxic/tags.py +++ b/pixie/vm/libs/pxic/tags.py @@ -1,7 +1,9 @@ tag_name = ["INT", + "BIGINT", "FLOAT", "INT_STRING", + "BIGINT_STRING", "STRING", "CODE", "TRUE", diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index 5dd39dd0..c86f8013 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -10,6 +10,7 @@ from pixie.vm.reader import LinePromise from rpython.rlib.objectmodel import specialize from rpython.rlib.rarithmetic import r_uint +from rpython.rlib.rbigint import rbigint import pixie.vm.rt as rt MAX_INT32 = r_uint(1 << 31) @@ -107,6 +108,11 @@ def write_int(i, wtr): wtr.write(chr(INT_STRING)) write_string_raw(unicode(str(i)), wtr) +def write_bigint(i, wtr): + # TODO implement a non string BIGINT writer + wtr.write(chr(BIGINT_STRING)) + write_string_raw(unicode(i.str()), wtr) + def write_float(f, wtr): write_tag(FLOAT, wtr) write_string_raw(unicode(str(f)), wtr) @@ -246,7 +252,7 @@ def write_object(obj, wtr): elif isinstance(obj, Integer): write_int(obj.int_val(), wtr) elif isinstance(obj, BigInteger): - write_int(obj.bigint_val(), wtr) + write_bigint(obj.bigint_val(), wtr) elif isinstance(obj, Float): write_float(obj.float_val(), wtr) elif isinstance(obj, Code): From 4d8aef8c075bb81ddac66ba8ff929bdf312bd5b4 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 14 Jun 2015 17:31:57 -0400 Subject: [PATCH 187/349] add select-keys, rand-int, some? --- pixie/stdlib.pxi | 19 +++++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 14 ++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a973ec1e..2c3b9904 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -552,6 +552,11 @@ returns true" (defn rem [num div] (-rem num div)) +(defn rand-int + {:doc "random integer between 0 (inclusive) and n (exclusive)"} + [n] + (rem (rand) n)) + (defn = {:doc "Returns true if all the arguments are equivalent. Otherwise, returns false. Uses -eq to perform equality checks." @@ -946,6 +951,16 @@ If further arguments are passed, invokes the method named by symbol, passing the (fn [v] (transduce ordered-hash-reducing-fn v))) +(defn select-keys + {:doc "Produces a map with only the values in m contained in key-seq"} + [m key-seq] + (with-meta + (transduce + (comp (filter (fn [k] (contains? m k))) + (map (fn [k] [k (get m k)]))) + conj {} key-seq) + (meta m))) + (defn keys {:doc "If called with no arguments returns a transducer that will extract the key from each map entry. If passed a collection, will assume that it is a hashmap and return a vector of all keys from the collection." @@ -1411,6 +1426,10 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn nil? [x] (identical? x nil)) +(defn some? [x] + {:doc "true if x is not nil"} + (not (nil? x))) + (defn fnil [f else] (fn [x & args] (apply f (if (nil? x) else x) args))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index d291874b..e464b475 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -189,6 +189,16 @@ (t/assert= (set (vals v)) #{1 2 3}) (t/assert= (transduce (vals) conj! v) (vals v)))) +(t/deftest test-select-keys + (let [m ^{:k :v} {:a 1 :b 2}] + (t/assert= (select-keys m [:a :b]) m) + (t/assert= :v + (-> (select-keys m [:a]) + meta + :k)) + (t/assert= (select-keys m [:a :not-found]) {:a 1}) + (t/assert= (select-keys m nil) {}) + (t/assert= (select-keys {} [:a]) {}))) (t/deftest test-empty (t/assert= (empty '(1 2 3)) '()) @@ -273,6 +283,10 @@ (t/assert= (every? even? []) true) (t/assert= (every? odd? []) true)) +(t/deftest test-rand-int + (let [vs (repeatedly 10 #(rand-int 4))] + (t/assert (every? #(and (>= % 0) (< % 4)) vs)))) + (t/deftest test-some (t/assert= (some even? [2 4 6 8]) true) (t/assert= (some odd? [2 4 6 8]) false) From 303226e0d324064370ce2041665d13ec1ac5e12c Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 14 Jun 2015 16:00:58 -0400 Subject: [PATCH 188/349] clarify parser docs, typo fix --- pixie/parser.pxi | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pixie/parser.pxi b/pixie/parser.pxi index e1b12a26..79e18f6e 100644 --- a/pixie/parser.pxi +++ b/pixie/parser.pxi @@ -191,10 +191,10 @@ rules))) (defmacro parser - "(parser nm inherits & rules) - Defines a new parser named `nm` that inherits from zero or more other parsers defined ion `inherits`. Rules are pairs - of names and rules that will be assigned to those names. Names are inherited from parent parsers in the order they are - defined." + "(parser inherits & rules) + Creates a parser that inherits from zero or more other parsers defined in `inherits`. Rules are pairs + of names and rules that will be assigned to those names. Names are inherited from parent parsers in the + order they are defined." [inherits & rules] (let [parted (apply merge (conj (mapv (fn [sym] @@ -303,7 +303,7 @@ fail)) (defn one-of - "Deines a parser that succeeds if the value being parsed is found in v" + "Defines a parser that succeeds if the value being parsed is found in v" [v] (parse-if (partial contains? v))) From 17117c8dac55eeb3cd22e60f5ffe7995f646ea5a Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 21 Jun 2015 14:17:43 +0100 Subject: [PATCH 189/349] fixes typo --- pixie/channels.pxi | 2 +- pixie/io.pxi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index 9937e7c2..f930bf17 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -7,7 +7,7 @@ (-commit! [this])) (defprotocol IReadPort - (-take! [this cfn] "Take a value from this port passing it to a cancellable function")) + (-take! [this cfn] "Take a value from this port passing it to a cancelable function")) (defprotocol IWritePort (-put! [this itm cfn] "Write a value to this port passing true if the write succeeds and the diff --git a/pixie/io.pxi b/pixie/io.pxi index 56452320..d3550c28 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -86,7 +86,7 @@ write-count)))) IDisposable (-dispose! [this] - (fclose fp))) + (fs_close fp))) (deftype BufferedOutputStream [downstream idx buffer] IByteOutputStream From 957f17b65b08f4c0e2be7bf009345f4e350ea919 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 24 Jun 2015 17:26:49 +0100 Subject: [PATCH 190/349] Removed circular dependency uv -> ffi-infer -> io-blocking -> io.common -> uv This is fixed by making io.common require only pixie.stream and move all uv related io stuff into io.uv-common. --- pixie/io-blocking.pxi | 2 -- pixie/io/common.pxi | 46 +----------------------------------------- pixie/io/tcp.pxi | 5 +++-- pixie/io/tty.pxi | 5 +++-- pixie/io/uv-common.pxi | 45 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 51 deletions(-) create mode 100644 pixie/io/uv-common.pxi diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index ecfbd5ee..4ac84eb3 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -2,7 +2,6 @@ (:require [pixie.streams :as st :refer :all] [pixie.io.common :as common])) - (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) (def fseek (ffi-fn libc "fseek" [CVoidP CInt CInt] CInt)) (def ftell (ffi-fn libc "ftell" [CVoidP] CInt)) @@ -15,7 +14,6 @@ (def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) (def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) - (deftype FileStream [fp] IInputStream (read [this buffer len] diff --git a/pixie/io/common.pxi b/pixie/io/common.pxi index ee23bdef..75a3e685 100644 --- a/pixie/io/common.pxi +++ b/pixie/io/common.pxi @@ -1,9 +1,6 @@ (ns pixie.io.common "Common functionality for handling IO" - (:require [pixie.streams :refer :all] - [pixie.uv :as uv] - [pixie.stacklets :as st] - [pixie.ffi :as ffi])) + (:require [pixie.streams :refer :all])) (def DEFAULT-BUFFER-SIZE 1024) @@ -18,44 +15,3 @@ (recur result) @result)) acc))))) - -(defn cb-stream-reader [uv-client buffer len] - (assert (<= (buffer-capacity buffer) len) - "Not enough capacity in the buffer") - (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) - read-cb (atom nil)] - (st/call-cc (fn [k] - (reset! read-cb (ffi/ffi-prep-callback - uv/uv_read_cb - (fn [stream nread uv-buf] - (set-buffer-count! buffer nread) - (try - (dispose! alloc-cb) - (dispose! @read-cb) - ;(dispose! uv-buf) - (uv/uv_read_stop stream) - (st/run-and-process k (or - (st/exception-on-uv-error nread) - nread)) - (catch ex - (println ex)))))) - (uv/uv_read_start uv-client alloc-cb @read-cb))))) - -(defn cb-stream-writer - [uv-client uv-write-buf buffer] - (let [write-cb (atom nil) - uv_write (uv/uv_write_t)] - (ffi/set! uv-write-buf :base buffer) - (ffi/set! uv-write-buf :len (count buffer)) - (st/call-cc - (fn [k] - (reset! write-cb (ffi/ffi-prep-callback - uv/uv_write_cb - (fn [req status] - (try - (dispose! @write-cb) - ;(uv/uv_close uv_write st/close_cb) - (st/run-and-process k status) - (catch ex - (println ex)))))) - (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index b3945782..4836e7a6 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -3,6 +3,7 @@ [pixie.streams :refer [IInputStream read IOutputStream write]] [pixie.io.common :as common] [pixie.uv :as uv] + [pixie.io.uv-common :as uv-common] [pixie.ffi :as ffi])) (defrecord TCPServer [ip port on-connect uv-server bind-addr on-connection-cb] @@ -15,10 +16,10 @@ (deftype TCPStream [uv-client uv-write-buf] IInputStream (read [this buffer len] - (common/cb-stream-reader uv-client buffer len)) + (uv-common/cb-stream-reader uv-client buffer len)) IOutputStream (write [this buffer] - (common/cb-stream-writer uv-client uv-write-buf buffer)) + (uv-common/cb-stream-writer uv-client uv-write-buf buffer)) IDisposable (-dispose! [this] (dispose! uv-write-buf) diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index 44386f3e..f4a1c091 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -3,12 +3,13 @@ [pixie.streams :refer [IInputStream read IOutputStream write]] [pixie.uv :as uv] [pixie.io.common :as common] + [pixie.io.uv-common :as uv-common] [pixie.system :as sys])) (deftype TTYInputStream [uv-client] IInputStream (read [this buf len] - (common/cb-stream-reader uv-client buf len)) + (uv/cb-stream-reader uv-client buf len)) IDisposable (-dispose! [this] (uv/uv_close uv-client st/close_cb)) @@ -19,7 +20,7 @@ (deftype TTYOutputStream [uv-client uv-write-buf] IOutputStream (write [this buffer] - (common/cb-stream-writer uv-client uv-write-buf buffer)) + (uv-common/cb-stream-writer uv-client uv-write-buf buffer)) IDisposable (-dispose! [this] (dispose! uv-write-buf) diff --git a/pixie/io/uv-common.pxi b/pixie/io/uv-common.pxi new file mode 100644 index 00000000..c8f10ee2 --- /dev/null +++ b/pixie/io/uv-common.pxi @@ -0,0 +1,45 @@ +(ns pixie.io.uv-common + (:require [pixie.stacklets :as st] + [pixie.uv :as uv] + [pixie.ffi :as ffi])) + +(defn cb-stream-reader [uv-client buffer len] + (assert (<= (buffer-capacity buffer) len) + "Not enough capacity in the buffer") + (let [alloc-cb (uv/-prep-uv-buffer-fn buffer len) + read-cb (atom nil)] + (st/call-cc (fn [k] + (reset! read-cb (ffi/ffi-prep-callback + uv/uv_read_cb + (fn [stream nread uv-buf] + (set-buffer-count! buffer nread) + (try + (dispose! alloc-cb) + (dispose! @read-cb) + ;(dispose! uv-buf) + (uv/uv_read_stop stream) + (st/run-and-process k (or + (st/exception-on-uv-error nread) + nread)) + (catch ex + (println ex)))))) + (uv/uv_read_start uv-client alloc-cb @read-cb))))) + +(defn cb-stream-writer + [uv-client uv-write-buf buffer] + (let [write-cb (atom nil) + uv_write (uv/uv_write_t)] + (ffi/set! uv-write-buf :base buffer) + (ffi/set! uv-write-buf :len (count buffer)) + (st/call-cc + (fn [k] + (reset! write-cb (ffi/ffi-prep-callback + uv/uv_write_cb + (fn [req status] + (try + (dispose! @write-cb) + ;(uv/uv_close uv_write st/close_cb) + (st/run-and-process k status) + (catch ex + (println ex)))))) + (uv/uv_write uv_write uv-client uv-write-buf 1 @write-cb))))) From a4a16f214910d2662cbac2242f80940f325c4d66 Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Sun, 28 Jun 2015 16:33:05 -0400 Subject: [PATCH 191/349] Update Executable size and use ;; comments --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 69a01bf9..eda32826 100644 --- a/README.md +++ b/README.md @@ -62,15 +62,14 @@ First of all, the word "magic" is in quotes as it's partly a play on words, pixi However there are a few features of pixie that although may not be uncommon, are perhaps unexpected from a lisp. -* Pixie implements its own virtual machine. It does not run on the JVM, CLR or Python VM. It implements its own bytecode, has its own GC and JIT. And it's small. Currently the interpreter, JIT, GC, and stdlib clock in at about 5.5MB once compiled down to an executable. +* Pixie implements its own virtual machine. It does not run on the JVM, CLR or Python VM. It implements its own bytecode, has its own GC and JIT. And it's small. Currently the interpreter, JIT, GC, and stdlib clock in at about 10.3MB once compiled down to an executable. * The JIT makes some things fast. Very fast. Code like the following compiles down to a loop with 6 CPU instructions. While this may not be too impressive for any language that uses a tracing jit, it is fairly unique for a language as young as Pixie. ```clojure -(comment - This code adds up to 10000 from 0 via calling a function that takes a variable number of arguments. - That function then reduces over the argument list to add up all given arguments.) +;; This code adds up to 10000 from 0 via calling a function that takes a variable number of arguments. +;; That function then reduces over the argument list to add up all given arguments. (defn add-fn [& args] (reduce -add 0 args)) From b82479ddf92c33b0761eb82301ae72cf257efe67 Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Sun, 28 Jun 2015 16:35:03 -0400 Subject: [PATCH 192/349] Abort compilation if boost library not found (#319) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It’s a bit of a hack way to implement, but essentially just makes compilation dependent on the boost library being found in either /usr/local/include or /usr/include. --- Makefile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 5829c583..57204a3b 100644 --- a/Makefile +++ b/Makefile @@ -19,11 +19,13 @@ help: @echo "make fetch_externals - download and unpack external deps" build_with_jit: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --opt=jit target.py + @if [ ! -d /usr/local/include/boost -a ! -d /usr/include/boost ] ; then echo "Boost C++ Library not found" && false; fi && \ + $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --opt=jit target.py && \ make compile_basics build_no_jit: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target.py + @if [ ! -d /usr/local/include/boost -a ! -d /usr/include/boost ] ; then echo "Boost C++ Library not found" && false; fi && \ + $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target.py && \ make compile_basics compile_basics: From f5c8c62eb552920e5c3c93b97b0176a4f6ba140b Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 29 Jun 2015 09:45:58 +0100 Subject: [PATCH 193/349] removed old scripts --- checkout-externals | 1 - make-no-jit | 1 - make-with-jit | 1 - run-interpreted | 1 - 4 files changed, 4 deletions(-) delete mode 100755 checkout-externals delete mode 100755 make-no-jit delete mode 100755 make-with-jit delete mode 100755 run-interpreted diff --git a/checkout-externals b/checkout-externals deleted file mode 100755 index db5f24d8..00000000 --- a/checkout-externals +++ /dev/null @@ -1 +0,0 @@ -echo "This script will be removed soon, please use 'make build_with_jit' or one of it's variants instead." \ No newline at end of file diff --git a/make-no-jit b/make-no-jit deleted file mode 100755 index c10d5f4b..00000000 --- a/make-no-jit +++ /dev/null @@ -1 +0,0 @@ -echo "This script will be removed soon, please use 'make build_no_jit' instead." \ No newline at end of file diff --git a/make-with-jit b/make-with-jit deleted file mode 100755 index 2d955b51..00000000 --- a/make-with-jit +++ /dev/null @@ -1 +0,0 @@ -echo "This script will be removed soon, please use 'make build_with_jit' instead." diff --git a/run-interpreted b/run-interpreted deleted file mode 100755 index cef13f95..00000000 --- a/run-interpreted +++ /dev/null @@ -1 +0,0 @@ -echo "This script will be removed soon, please use 'make run_interactive' instead." From 41acb27a324a4ef34b12d0c62c91027884e4420d Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 29 Jun 2015 13:51:51 +0100 Subject: [PATCH 194/349] fix typo --- pixie/io.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index d3550c28..d1e36168 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -79,7 +79,7 @@ _ (pixie.ffi/set! uvbuf :len (- (count buffer) buffer-offset)) write-count (fs_write fp uvbuf 1 offset)] (when (neg? write-count) - (throw [::FileOutputStreamException (uv/uv_err_name read-count)])) + (throw [::FileOutputStreamException (uv/uv_err_name write-count)])) (set-field! this :offset (+ offset write-count)) (if (< (+ buffer-offset write-count) (count buffer)) (recur (+ buffer-offset write-count)) From bb9c0fbffdba92de76925be49c78fe349aca0c2b Mon Sep 17 00:00:00 2001 From: "Matthew A. West" Date: Wed, 8 Jul 2015 12:59:01 -0400 Subject: [PATCH 195/349] Encode BigIntegers in pxic without using strings --- pixie/vm/compiler.py | 2 +- pixie/vm/libs/pxic/reader.py | 11 +++++++++++ pixie/vm/libs/pxic/writer.py | 21 +++++++++++++++++---- tests/pixie/tests/test-numbers.pxi | 4 ++-- 4 files changed, 31 insertions(+), 7 deletions(-) diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index 76ca7fae..a6bbd64f 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -1,4 +1,4 @@ -from pixie.vm.object import affirm +from pixie.vm.object import affirm from pixie.vm.primitives import nil, true, Bool from pixie.vm.persistent_vector import EMPTY, PersistentVector from pixie.vm.persistent_hash_set import PersistentHashSet diff --git a/pixie/vm/libs/pxic/reader.py b/pixie/vm/libs/pxic/reader.py index d3b44613..2cc5d799 100644 --- a/pixie/vm/libs/pxic/reader.py +++ b/pixie/vm/libs/pxic/reader.py @@ -55,6 +55,15 @@ def read_tag(rdr): def read_raw_integer(rdr): return r_uint(ord(rdr.read()[0]) | (ord(rdr.read()[0]) << 8) | (ord(rdr.read()[0]) << 16) | (ord(rdr.read()[0]) << 24)) +def read_raw_bigint(rdr): + nchars = read_raw_integer(rdr) + n = rbigint.fromint(0) + for i in range(nchars): + a = rbigint.fromint(ord(rdr.read()[0])) + a = a.lshift(8*i) + n = n.add(a) + return n + def read_raw_string(rdr): s = rdr.read_cached_string() return s @@ -138,6 +147,8 @@ def read_obj(rdr): if tag == INT: return Integer(intmask(read_raw_integer(rdr))) + elif tag == BIGINT: + return BigInteger(read_raw_bigint(rdr)) elif tag == CODE: return read_code(rdr) elif tag == NIL: diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index c86f8013..7aedcb17 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -100,6 +100,16 @@ def write_int_raw(i, wtr): def write_string_raw(si, wtr): wtr.write_raw_cached_string(si) +def write_bigint_raw(i, wtr): + bits = i.bit_length() + nchars = r_uint(bits / 8) + if (bits) % 8 != 0: + nchars += 1 + assert nchars <= MAX_INT32 + write_int_raw(nchars, wtr) # nchars used to represent the bigint + for j in range(nchars): + wtr.write(chr((i.rshift(j * 8).int_and_(0xFF).toint()))) + def write_int(i, wtr): if 0 <= i <= MAX_INT32: wtr.write(chr(INT)) @@ -109,9 +119,12 @@ def write_int(i, wtr): write_string_raw(unicode(str(i)), wtr) def write_bigint(i, wtr): - # TODO implement a non string BIGINT writer - wtr.write(chr(BIGINT_STRING)) - write_string_raw(unicode(i.str()), wtr) + if i.int_ge(0): + wtr.write(chr(BIGINT)) + write_bigint_raw(i, wtr) + else: + wtr.write(chr(BIGINT_STRING)) + write_string_raw(unicode(i.str()), wtr) def write_float(f, wtr): write_tag(FLOAT, wtr) @@ -251,7 +264,7 @@ def write_object(obj, wtr): write_string(rt.name(obj), wtr) elif isinstance(obj, Integer): write_int(obj.int_val(), wtr) - elif isinstance(obj, BigInteger): + elif isinstance(obj, BigInteger): #TODO test write_bigint(obj.bigint_val(), wtr) elif isinstance(obj, Float): write_float(obj.float_val(), wtr) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 0152adc4..28ab8b92 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -70,6 +70,6 @@ (t/deftest test-promotion (t/assert= BigInteger (type (reduce * 1 (range 1 100)))) - (t/assert (-num-eq 1000000000000000000000N (* 10000000 - 10000000 + (t/assert (-num-eq 1000000000000000000000N (* 10000000 + 10000000 10000000)))) From 2a1760fc60b6a2da488fa2a0a5fd9fbb4e2c8d43 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 21 Jun 2015 14:12:15 +0100 Subject: [PATCH 196/349] working zlib implementation pixies ffi can convert nil to an NULL PTR callback --- .travis.yml | 2 +- pixie/io.pxi | 7 +- pixie/io/tty.pxi | 2 +- pixie/stdlib.pxi | 4 +- pixie/streams/zlib.pxi | 218 ++++++++++++++++++++++++++++++++++ pixie/streams/zlib/ffi.pxi | 59 +++++++++ pixie/vm/libs/ffi.py | 19 +-- tests/pixie/tests/test-io.pxi | 39 +++++- 8 files changed, 337 insertions(+), 13 deletions(-) create mode 100644 pixie/streams/zlib.pxi create mode 100644 pixie/streams/zlib/ffi.pxi diff --git a/.travis.yml b/.travis.yml index 9d48c020..28ac48e9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,7 +17,7 @@ script: - make run_built_tests before_install: - - sudo apt-get install libffi-dev libedit-dev libboost-all-dev + - sudo apt-get install libffi-dev libedit-dev libboost-all-dev zlib1g-dev zlib-bin notifications: irc: "chat.freenode.net#pixie-lang" diff --git a/pixie/io.pxi b/pixie/io.pxi index d1e36168..3a14ca7c 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -100,12 +100,15 @@ IDisposable (-dispose! [this] (set-buffer-count! buffer idx) - (write downstream buffer)) + (write downstream buffer) + (flush this)) IFlushableStream (flush [this] (set-buffer-count! buffer idx) (set-field! this :idx 0) - (write downstream buffer))) + (write downstream buffer) + (when (satisfies? IFlushableStream downstream) + (flush downstream)))) (deftype BufferedInputStream [upstream idx buffer] IByteInputStream diff --git a/pixie/io/tty.pxi b/pixie/io/tty.pxi index f4a1c091..be8c0185 100644 --- a/pixie/io/tty.pxi +++ b/pixie/io/tty.pxi @@ -9,7 +9,7 @@ (deftype TTYInputStream [uv-client] IInputStream (read [this buf len] - (uv/cb-stream-reader uv-client buf len)) + (uv-common/cb-stream-reader uv-client buf len)) IDisposable (-dispose! [this] (uv/uv_close uv-client st/close_cb)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 8815e226..880efd42 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -645,7 +645,9 @@ returns true" :signatures [[coll]] :added "0.1"} [coll] - (not (seq coll))) + (if (satisfies? ICounted coll) + (zero? (count coll)) + (not (seq coll)))) (defn not-empty? {:doc "returns true if the collection has items, otherwise false" diff --git a/pixie/streams/zlib.pxi b/pixie/streams/zlib.pxi new file mode 100644 index 00000000..bae72ade --- /dev/null +++ b/pixie/streams/zlib.pxi @@ -0,0 +1,218 @@ +(ns pixie.streams.zlib + (:require [pixie.streams.zlib.ffi :as zlib.ffi] + [pixie.ffi :as ffi] + [pixie.streams :refer :all])) + +(defprotocol IZStream + (version [this]) + (set-input! [this] + "Should be called before deflate! to set a new chunk of input + to deflate") + + (full-output? [this] + "Returns true if the ouput buffer is full of deflated (compressed) data") + + (reset-output-buffer! [this] + "Make the output buffer ready to be refilled with data") + + (consumed-input? [this] + "Returns true if zlib has finished reading the input-buffer") + + (set-output-buffer-count! [this] + "Set the buffers count so down stream can safely read the buffer") + + ;; Deflation + (deflate-init! [this opts] + "Set up the compression with desired parameters") + + ;; Inflation + (inflate-init! [this opts] + "Set up decompression with desired parameters") + + ;; In/deflate depending on what the stream has been + ;; initialized as + (flate! [this down-stream mode] + "Compress/decompress") + + (flate-end! + "Cleanup")) + +(defn handle-errors! [status] + (cond + (= status zlib.ffi/Z_ERRNO) + (throw [::Error "Something went wrong"]) + + (= status zlib.ffi/Z_STREAM_ERROR) + (throw [::Error "The stream doesn't appear to be a valid zlib/gzip stream"]) + + (= status zlib.ffi/Z_DATA_ERROR) + (throw [::Error "There was something wrong with the data"]) + + + ;; TODO go through the different status and show + ;; appropriate messages + (neg? status) + (throw [::Error "There was something wrong with the data"]))) + + +;; This wraps the C data structure and stores some information about +;; how its been initialized: :deflate or :inflate. +(deftype ZStream [z-stream inited] + IZStream + (version [this] + (zlib.ffi/zlibVersion)) + + (full-output? [this] + (zero? (get z-stream :avail_out))) + + (consumed-input? [this] + (zero? (get z-stream :avail_in))) + + (reset-output-buffer! [this output-buffer] + (ffi/set! z-stream :next_out output-buffer) + (ffi/set! z-stream :avail_out (buffer-capacity output-buffer))) + + (set-output-buffer-count! [this output-buffer] + (let [fill-count (- (buffer-capacity output-buffer) + (get z-stream :avail_out))] + (set-buffer-count! output-buffer fill-count))) + + (set-input! [this input-buffer] + (ffi/set! z-stream :next_in input-buffer) + (ffi/set! z-stream :avail_in (count input-buffer))) + + (deflate-init! [this opts] + (assert (nil? inited) "ZStream can only be initialized once.") + (let [status (zlib.ffi/deflateInit2_ + z-stream + (get opts :level zlib.ffi/Z_BEST_COMPRESSION) ;level + zlib.ffi/Z_DEFLATED ;method + (+ 15 16) ;window (set for gz header) + 8 ;memlevel + zlib.ffi/Z_DEFAULT_STRATEGY ;strategy + (version this) ;version + (ffi/struct-size zlib.ffi/z_stream))] + (assert (= zlib.ffi/Z_OK status) "Failed to initiate zstream") + (set-field! this :inited :deflate))) + + (inflate-init! [this opts] + (assert (nil? inited) "ZStream can only be initialized once.") + (let [status (zlib.ffi/inflateInit2_ + z-stream + (+ 15 16) ;window (set for gz header) + (version this) ;version + (ffi/struct-size zlib.ffi/z_stream))] + (assert (= zlib.ffi/Z_OK status) "Failed to initiate zstream") + (set-field! this :inited :inflate))) + + (flate! [this output-buffer mode] + (case inited + :inflate + (let [status (zlib.ffi/inflate z-stream mode)] + (handle-errors! status) + (set-output-buffer-count! this output-buffer) + status) + + :deflate + (let [status (zlib.ffi/deflate z-stream mode)] + (handle-errors! status) + (set-output-buffer-count! this output-buffer) + status) + + (assert false "ZStream must be initialized before calling flate!"))) + + (flate-end! [this] + (case inited + :inflate + (zlib.ffi/inflateEnd z-stream) + + :deflate + (zlib.ffi/deflateEnd z-stream) + + (assert false "ZStream must be initialized before calling flate-end!")))) + +(defn z-stream [] + (let [z-stream (zlib.ffi/z_stream)] + ;; Set all the callbacks to NULL so zlib uses its default ones. + (ffi/set! z-stream :avail_in 0) + (ffi/set! z-stream :zalloc nil) + (ffi/set! z-stream :opaque nil) + (ffi/set! z-stream :zfree nil) + (->ZStream z-stream nil))) + +(deftype GZInputStream + [up-stream input-buffer z-stream] + IDisposable + (-dispose! [this] + (flate-end! z-stream)) + + IInputStream + (read [this buffer len] + (set-buffer-count! buffer 0) + (reset-output-buffer! z-stream buffer) + ;; We keep reading from upstream until we have filled our output buffer + (loop [] + (when (consumed-input? z-stream) + ;; If z-stream has finished reading the input-buffer we last gave it, + ;; give it a new one. + (read up-stream input-buffer (buffer-capacity input-buffer)) + (set-input! z-stream input-buffer)) + (flate! z-stream buffer zlib.ffi/Z_NO_FLUSH) + (if-not (empty? input-buffer) + (if (full-output? z-stream) + ;; The buffer is now filled up + (count buffer) + ;; We can still do some more de/compression + (recur)) + 0)))) + +(deftype GZOutputStream + [down-stream output-buffer z-stream] + IOutputStream + (write [this input-buffer] + (set-input! z-stream input-buffer) + (loop [] + (reset-output-buffer! z-stream output-buffer) + (flate! z-stream output-buffer zlib.ffi/Z_NO_FLUSH) + (when-not (empty? output-buffer) + (write down-stream output-buffer)) + ;; if there is still more 'flating to do, do it. + (when (full-output? z-stream) + (recur)))) + + IFlushableStream + (flush [this] + (loop [] + (reset-output-buffer! z-stream output-buffer) + (flate! z-stream output-buffer zlib.ffi/Z_FINISH) + (write down-stream output-buffer) + (when (full-output? z-stream) + (recur))) + (when (satisfies? IFlushableStream down-stream) + (flush down-stream))) + + IDisposable + (-dispose! [this] + (flate-end! z-stream) + (when (satisfies? IDisposable down-stream) + (-dispose! down-stream)))) + +(defn compressing-output-stream + "Takes a down-stream IInputStream and a buffer to store compressed chunks" + [down-stream output-buffer opts] + (->GZOutputStream down-stream output-buffer (deflate-init! (z-stream) opts))) + +(defn decompressing-output-stream + "Takes a down-stream IInputStream and a buffer to store compressed chunks" + [down-stream output-buffer opts] + (->GZOutputStream down-stream output-buffer (inflate-init! (z-stream) opts))) + +(defn decompressing-input-stream + "Takes a down-stream IInputStream and a buffer to store compressed chunks" + [up-stream input-buffer opts] + (->GZInputStream up-stream input-buffer (inflate-init! (z-stream) opts))) + +(defn compressing-input-stream + "Takes a down-stream IInputStream and a buffer to store compressed chunks" + [up-stream input-buffer opts] + (->GZInputStream up-stream input-buffer (deflate-init! (z-stream) opts))) diff --git a/pixie/streams/zlib/ffi.pxi b/pixie/streams/zlib/ffi.pxi new file mode 100644 index 00000000..8c8bcdbb --- /dev/null +++ b/pixie/streams/zlib/ffi.pxi @@ -0,0 +1,59 @@ +(ns pixie.streams.zlib.ffi + (:require [pixie.ffi-infer :as f] + [pixie.ffi :as ffi])) + +(f/with-config {:library "z" + :includes ["zlib.h"]} + (f/defcstruct z_stream [:next_in + :avail_in + :total_in + :next_out + :avail_out + :total_out + + :msg + :state + + :zalloc + :zfree + :opaque + + :data_type + :adler + + :reserved]) + + (f/defcfn zError) + (f/defcfn zlibVersion) + + ;; Inflating (decompressing) + (f/defcfn inflate) + (f/defcfn inflateEnd) + (f/defcfn inflateInit2_) + + ;; Defalting (compressing) + (f/defcfn deflate) + (f/defcfn deflateInit_) + (f/defcfn deflateInit2_) + (f/defcfn deflateEnd)) + +(def Z_OK 0) +(def Z_NO_FLUSH 0) +(def Z_PARTIAL_FLUSH 1) +(def Z_SYNC_FLUSH 2) +(def Z_FULL_FLUSH 3) +(def Z_FINISH 4) +(def Z_BLOCK 5) + +(def Z_ERRNO -1) +(def Z_STREAM_ERROR -2) +(def Z_DATA_ERROR -3) + +(def Z_NO_COMPRESSION 0) +(def Z_BEST_SPEED 1) +(def Z_BEST_COMPRESSION 9) +(def Z_DEFAULT_COMPRESSION -1) + +(def Z_DEFLATED 8) + +(def Z_DEFAULT_STRATEGY 0) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index a733464d..7d961ce4 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -680,11 +680,16 @@ def ffi_get_value(self, ptr): runtime_error(u"Cannot get a callback value via FFI") def ffi_set_value(self, ptr, val): - affirm(isinstance(val, CCallback), u"Can only encode CCallbacks as function pointers") - - - casted = rffi.cast(rffi.VOIDPP, ptr) - casted[0] = val.get_raw_closure() + if isinstance(val, CCallback): + casted = rffi.cast(rffi.VOIDPP, ptr) + casted[0] = val.get_raw_closure() + elif val is nil: + casted = rffi.cast(rffi.VOIDPP, ptr) + casted[0] = rffi.cast(rffi.VOIDP, 0) + else: + frm_name = rt.name(rt.str(val.type())) + to_name = rt.name(rt.str(self)) + affirm(False, u"Cannot encode " + frm_name + u" as " + to_name) return None @@ -751,8 +756,8 @@ def c_struct(name, size, spec): offset = rt.nth(row, rt.wrap(2)) affirm(isinstance(nm, Keyword), u"c-struct field names must be keywords") - if not isinstance(tp, CType): - runtime_error(u"c-struct field types must be c types, got: " + rt.name(rt.str(tp))) + #if not isinstance(tp, CType): + # runtime_error(u"c-struct field types must be c types, got: " + rt.name(rt.str(tp))) d[nm] = (tp, offset.int_val()) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 16f3778b..a3be00c7 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -1,7 +1,9 @@ (ns pixie.tests.test-io (require pixie.test :as t) (require pixie.streams :as st :refer :all) - (require pixie.io :as io)) + (require pixie.streams.utf8 :as utf8 :refer :all) + (require pixie.io :as io) + (require pixie.streams.zlib :as zlib)) (t/deftest test-file-reduction (let [f (io/open-read "tests/pixie/tests/test-io.txt")] @@ -43,3 +45,38 @@ (t/assert-throws? (io/slurp :foo)) (t/assert= "I love 🍺 . This is a thumbs up 👍\n" (io/slurp "tests/pixie/tests/test-io-utf8.txt"))) + +(defn compress-content [output-stream content] + (transduce (map identity) + (-> output-stream + (zlib/compressing-output-stream (buffer 512) {}) + (io/buffered-output-stream 1024) + utf8/utf8-output-stream-rf) + (str content))) + +(defn compress-and-decompress-content [output-stream content] + (transduce (map identity) + (-> output-stream + (zlib/decompressing-output-stream (buffer 512) {}) + (zlib/compressing-output-stream (buffer 512) {}) + (io/buffered-output-stream 1024) + utf8/utf8-output-stream-rf) + (str content))) + +(t/deftest test-write-compressed + (io/run-command "rm compressed-output.gz") + (compress-content (io/open-write "compressed-output.gz") (range 1000)) + ;; decompress the file with zcat + (io/run-command "zcat compressed-output.gz > compressed-output.txt") + (t/assert= (range 1000) (read-string (io/slurp "compressed-output.txt"))) + + ;; Wrapping an IInputStream in decompressing-stream should get the same result + (t/assert= (range 1000) (read-string (io/slurp + (zlib/decompressing-input-stream + (io/open-read "compressed-output.gz") + (buffer 512) {}))))) + +;; sticking a compressor into a decompressor should result in the original data +(t/deftest test-decompression + (compress-and-decompress-content (io/open-write "decompressed-output.txt") (range 1000)) + (t/assert= (range 1000) (read-string (io/slurp "decompressed-output.txt")))) From 73cc88dab7dbadd7cc28bd3c7ffb27faa1e3670f Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 3 Jun 2015 14:24:48 +0100 Subject: [PATCH 197/349] BufferedInputStreams implement ISeekableStream --- pixie/io.pxi | 20 ++++++++++++ tests/pixie/tests/test-io.pxi | 61 +++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/pixie/io.pxi b/pixie/io.pxi index 3a14ca7c..e8c5beb2 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -120,6 +120,26 @@ (let [val (nth buffer idx)] (set-field! this :idx (inc idx)) val))) + ISeekableStream + (position [this] + (+ (- (position upstream) + (count buffer)) + idx)) + (rewind [this] + (seek this 0)) + (seek [this pos] + ;; We can be clever about seeking. If we are seeking to somewhere with in + ;; our current buffer, we can avoid seeking in upstream. + (let [upper-bounds (position upstream) + lower-bounds (- upper-bounds (count buffer))] + (if (and (>= pos lower-bounds) + (<= pos upper-bounds)) + ;; We're in the buffer window :-) + (set-field! this :idx (- pos lower-bounds)) + ;; Put the index at the end of the buffer to force a read from upstream + (do + (set-field! this :idx (count buffer)) + (seek upstream pos))))) IDisposable (-dispose! [this] (dispose! buffer))) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index a3be00c7..b06807d6 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -37,6 +37,67 @@ (io/seek f (- (position f) 6)) (t/assert= (io/read-line f) "line."))) +(t/deftest test-buffered-input-streams + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt"))] + (t/assert= (char (io/read-byte f)) \T) + (t/assert= (char (io/read-byte f)) \h) + (t/assert= (char (io/read-byte f)) \i) + (t/assert= (char (io/read-byte f)) \s))) + +(t/deftest test-buffered-input-streams-seek + ;; We use a buffer size of 4 because the test file isn't huge and i am terrible at + ;; counting characters... + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt") 4)] + ;; Read the first word 'This' + (t/assert= (position f) 0) + (t/assert= (char (io/read-byte f)) \T) + (t/assert= (position f) 1) + (t/assert= (char (io/read-byte f)) \h) + (t/assert= (position f) 2) + (t/assert= (char (io/read-byte f)) \i) + (t/assert= (position f) 3) + (t/assert= (char (io/read-byte f)) \s) + (t/assert= (position f) 4) + + ;; Back to start of file (this is a seek with in the buffer) + (rewind f) + + ;; Should read the first word again + (t/assert= (char (io/read-byte f)) \T) + (t/assert= (position f) 1) + (t/assert= (char (io/read-byte f)) \h) + (t/assert= (position f) 2) + (t/assert= (char (io/read-byte f)) \i) + (t/assert= (position f) 3) + (t/assert= (char (io/read-byte f)) \s) + (t/assert= (position f) 4) + + ;; Skip the space (we will have caused a seek upstream) + (seek f 5) + + ;; Read 'is' + (t/assert= (position f) 5) + (t/assert= (char (io/read-byte f)) \i) + (t/assert= (position f) 6) + (t/assert= (char (io/read-byte f)) \s) + (t/assert= (position f) 7) + + ;; Jump ahead to 'file' (another seek upstream) + (seek f 15) + (t/assert= (position f) 15) + (t/assert= (char (io/read-byte f)) \f) + (t/assert= (position f) 16) + (t/assert= (char (io/read-byte f)) \i) + (t/assert= (position f) 17) + (t/assert= (char (io/read-byte f)) \l) + (t/assert= (position f) 18) + (t/assert= (char (io/read-byte f)) \e) + + ;; Another seek with in a buffer + (seek f 16) + (t/assert= (position f) 16) + (t/assert= (char (io/read-byte f)) \i))) + (t/deftest test-slurp-spit (let [val (vec (range 1280))] (io/spit "test.tmp" val) From 3c86e86c6687bb6d5317f220295a63b12ae7afce Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 19 Jul 2015 14:10:07 +0100 Subject: [PATCH 198/349] use empty? instead --- pixie/io.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index e8c5beb2..ee1d34bf 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -116,7 +116,7 @@ (when (= idx (count buffer)) (set-field! this :idx 0) (read upstream buffer (buffer-capacity buffer))) - (when (pos? (count buffer)) + (when-not (empty? buffer) (let [val (nth buffer idx)] (set-field! this :idx (inc idx)) val))) From b36e750423d146988579947cec7de41b426ff80c Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 19 Jul 2015 15:09:04 +0100 Subject: [PATCH 199/349] fixed ILookup on vectors --- pixie/vm/persistent_vector.py | 2 +- tests/pixie/tests/test-stdlib.pxi | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/pixie/vm/persistent_vector.py b/pixie/vm/persistent_vector.py index a0e1ae55..202e3c72 100644 --- a/pixie/vm/persistent_vector.py +++ b/pixie/vm/persistent_vector.py @@ -439,7 +439,7 @@ def _nth_not_found(self, idx, not_found): def _val_at(self, key, not_found): assert isinstance(self, PersistentVector) if isinstance(key, Integer): - return self.nth(key.int_val()) + return self.nth(key.int_val(), not_found) else: return not_found diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index f5650df7..441cf00b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -109,6 +109,14 @@ (t/assert= (nth (range 4) 1 :default) 1) (t/assert= (nth "hithere" 1 :deafult) \i)) +(t/deftest test-get-on-vector + (t/assert= (get [1 2 3] 0) 1) + (t/assert= (get [1 2 3] 1) 2) + (t/assert= (get [1 2 3] 2) 3) + (t/assert= (get [1 2 3] 4) nil) + (t/assert= (get [1 2 3] 5) nil) + (t/assert= (get [1 2 3] 5 :not-found) :not-found)) + (t/deftest test-first (t/assert= (first []) nil) (t/assert= (first '()) nil) From 314007d4e3c6a31d5f07cf67d86b3a59da76eccb Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 20 Jul 2015 12:58:01 +0100 Subject: [PATCH 200/349] flush on dispose not write --- pixie/io.pxi | 1 - 1 file changed, 1 deletion(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 3a14ca7c..06e8847c 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -100,7 +100,6 @@ IDisposable (-dispose! [this] (set-buffer-count! buffer idx) - (write downstream buffer) (flush this)) IFlushableStream (flush [this] From e1d8e3fb36d11b8514b13af8a4516a6fff6c0acd Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 20 Jul 2015 13:30:31 +0100 Subject: [PATCH 201/349] do not ignore length arg passed to read previously the length of the buffer was being read rather than the number passed in by the user --- pixie/io.pxi | 4 ++-- tests/pixie/tests/test-io.pxi | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 06e8847c..d1a6738c 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -16,10 +16,10 @@ (deftype FileStream [fp offset uvbuf] IInputStream (read [this buffer len] - (assert (<= (buffer-capacity buffer) len) + (assert (>= (buffer-capacity buffer) len) "Not enough capacity in the buffer") (let [_ (pixie.ffi/set! uvbuf :base buffer) - _ (pixie.ffi/set! uvbuf :len (buffer-capacity buffer)) + _ (pixie.ffi/set! uvbuf :len len) read-count (fs_read fp uvbuf 1 offset)] (assert (not (neg? read-count)) "Read Error") (set-field! this :offset (+ offset read-count)) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index a3be00c7..01fa0839 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -16,6 +16,22 @@ (let [f (io/run-command "ls tests/pixie/tests/test-io.txt")] (t/assert= f "tests/pixie/tests/test-io.txt\n"))) +(t/deftest test-read-into-buffer + (let [f (io/open-read "tests/pixie/tests/test-io.txt")] + (let [buf (buffer 16)] + (io/read f buf 4) + (t/assert= (transduce (map char) string-builder buf) "This") + + (io/read f buf 4) + (t/assert= (transduce (map char) string-builder buf) " is ") + + + (io/read f buf 0) + (t/assert= (transduce (map char) string-builder buf) "") + + (t/assert-throws? (io/read f buf 17)) + (t/assert-throws? (io/read f buf -2))))) + (t/deftest test-read-line (let [f (io/open-read "tests/pixie/tests/test-io.txt")] (io/read-line f) From 1524626651f3728313c083d21e37a9e373f503ed Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 20 Jul 2015 17:21:44 +0100 Subject: [PATCH 202/349] clean up unused code --- pixie/vm/bootstrap.py | 1 - pixie/vm/compiler.py | 8 +++----- pixie/vm/custom_types.py | 4 +--- pixie/vm/object.py | 5 +---- pixie/vm/stdlib.py | 5 ----- 5 files changed, 5 insertions(+), 18 deletions(-) diff --git a/pixie/vm/bootstrap.py b/pixie/vm/bootstrap.py index 623d9442..10b9f49b 100644 --- a/pixie/vm/bootstrap.py +++ b/pixie/vm/bootstrap.py @@ -3,7 +3,6 @@ @wrap_fn def bootstrap(): import pixie.vm.rt as rt - from pixie.vm.string import String assert False rt.load_ns(rt.wrap(u"pixie/stdlib.pxi")) diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index a6bbd64f..7dbb7477 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -258,7 +258,7 @@ def emit(self, ctx): -def resolve_var(ctx, name): +def resolve_var(name): return NS_VAR.deref().resolve(name) def resolve_local(ctx, name): @@ -270,7 +270,7 @@ def is_macro_call(form, ctx): name = rt.name(rt.first(form)) if resolve_local(ctx, name): return None - var = resolve_var(ctx, rt.first(form)) + var = resolve_var(rt.first(form)) if var and var.is_defined(): val = var.deref() @@ -377,7 +377,7 @@ def compile_form(form, ctx): ns = rt.namespace(form) loc = resolve_local(ctx, name) - var = resolve_var(ctx, form) + var = resolve_var(form) if var is None and loc: loc.emit(ctx) @@ -409,7 +409,6 @@ def compile_form(form, ctx): return if isinstance(form, PersistentVector): - vector_var = rt.vector() size = rt.count(form) #assert rt.count(form).int_val() == 0 ctx.push_const(code.intern_var(u"pixie.stdlib", u"vector")) @@ -513,7 +512,6 @@ def compile_fn(form, ctx): def compile_fn_body(name, args, body, ctx): new_ctx = Context(rt.name(name), rt.count(args), ctx) required_args = add_args(rt.name(name), args, new_ctx) - bc = 0 affirm(isinstance(name, symbol.Symbol), u"Function names must be symbols") diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index b1aa73c9..46c0f92a 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -1,6 +1,5 @@ from pixie.vm.object import Object, Type, affirm, runtime_error import rpython.rlib.jit as jit -from rpython.rlib.rarithmetic import r_uint from pixie.vm.code import as_var from pixie.vm.numbers import Integer, Float from pixie.vm.keyword import Keyword @@ -8,7 +7,6 @@ MAX_FIELDS = 32 - class CustomType(Type): _immutable_fields_ = ["_slots", "_rev?"] def __init__(self, name, slots): @@ -254,4 +252,4 @@ def set_mutable_cell_value(self, ct, fields, nm, idx, value): self._mutable_float_val = value.float_val() def get_mutable_cell_value(self): - return rt.wrap(self._mutable_float_val) \ No newline at end of file + return rt.wrap(self._mutable_float_val) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 4c39f162..4632eaf0 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -41,7 +41,6 @@ def register_type(self, nm, tp): self.var_for_type_and_name(nm, tp) def var_for_type_and_name(self, nm, tp): - from pixie.vm.symbol import symbol splits = nm.split(u".") size = len(splits) - 1 assert size >= 0 @@ -242,7 +241,6 @@ def __repr__(self): def trace_map(self): from pixie.vm.string import String - from pixie.vm.numbers import Integer from pixie.vm.keyword import keyword tp = self._tp @@ -261,7 +259,6 @@ def __repr__(self): def trace_map(self): from pixie.vm.string import String - from pixie.vm.numbers import Integer from pixie.vm.keyword import keyword tm = {keyword(u"type") : keyword(u"pixie")} @@ -292,4 +289,4 @@ def trace_map(self): def add_info(ex, data): assert isinstance(ex, WrappedException) ex._ex._trace.append(ExtraCodeInfo(data)) - return ex \ No newline at end of file + return ex diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 5b4326a0..9abbef3e 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -8,7 +8,6 @@ import pixie.vm.numbers as numbers import rpython.rlib.jit as jit from rpython.rlib.rarithmetic import r_uint -from pixie.vm.interpreter import ShallowContinuation from rpython.rlib.objectmodel import we_are_translated defprotocol("pixie.stdlib", "ISeq", ["-first", "-next"]) @@ -99,7 +98,6 @@ def __meta(self, meta): def default_str(x): - from pixie.vm.string import String tp = x.type() assert isinstance(tp, Type) return rt.wrap(u"") @@ -284,7 +282,6 @@ def nth_not_found(a, b, c): @as_var("str") def str__args(args): - from pixie.vm.string import String acc = [] for x in args: acc.append(rt.name(rt._str(x))) @@ -401,7 +398,6 @@ def _load_file(filename, compile=False): import pixie.vm.reader as reader import pixie.vm.libs.pxic.writer as pxic_writer import os.path as path - import os affirm(isinstance(filename, String), u"filename must be a string") @@ -684,7 +680,6 @@ def _try_catch(main_fn, catch_fn, final): return main_fn.invoke([]) except Exception as ex: if not isinstance(ex, WrappedException): - from pixie.vm.string import String if isinstance(ex, Exception): if not we_are_translated(): print "Python Error Info: ", ex.__dict__, ex From 9eed1c78e23f417ae70f29332871f1d5d5b03a60 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 20 Jul 2015 17:31:13 +0100 Subject: [PATCH 203/349] rm PromptReader --- pixie/vm/reader.py | 26 -------------------------- target.py | 7 +++---- 2 files changed, 3 insertions(+), 30 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 64ad57c9..0df93adc 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -69,32 +69,6 @@ def read(self): def unread(self): self._idx -= 1 -class PromptReader(PlatformReader): - def __init__(self): - self._string_reader = None - - - def read(self): - if self._string_reader is None: - result = _readline(str(rt.name(rt.ns.deref())) + " => ") - if result == u"": - raise EOFError() - self._string_reader = StringReader(result) - - try: - return self._string_reader.read() - except EOFError: - self._string_reader = None - return self.read() - - def reset_line(self): - self._string_reader = None - - def unread(self): - assert self._string_reader is not None - self._string_reader.unread() - - class UserSpaceReader(PlatformReader): def __init__(self, reader_fn): self._string_reader = None diff --git a/target.py b/target.py index 66f397c5..a4126317 100644 --- a/target.py +++ b/target.py @@ -1,12 +1,11 @@ -from pixie.vm.compiler import compile, with_ns, NS_VAR -from pixie.vm.reader import StringReader, read_inner, eof, PromptReader, MetaDataReader -from pixie.vm.interpreter import interpret +from pixie.vm.compiler import with_ns, NS_VAR +from pixie.vm.reader import StringReader from rpython.jit.codewriter.policy import JitPolicy from rpython.rlib.jit import JitHookInterface, Counters from rpython.rlib.rfile import create_stdio from rpython.annotator.policy import AnnotatorPolicy from pixie.vm.code import wrap_fn, NativeFn, intern_var, Var -from pixie.vm.object import RuntimeException, WrappedException +from pixie.vm.object import WrappedException from rpython.translator.platform import platform from pixie.vm.primitives import nil from pixie.vm.atom import Atom From e452d808d1cfedc766e840e8c9b39e98fe7de884 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 21 Jul 2015 09:28:53 +0100 Subject: [PATCH 204/349] s/False/false --- pixie/ffi-infer.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index f2074f53..9f13ac74 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -108,7 +108,7 @@ return 0; [{:keys [size]} _] (cond (= size 8) 'pixie.stdlib/CDouble - :else (assert False "unknown type"))) + :else (assert false "unknown type"))) (defmethod edn-to-ctype :void [_ _] From 0fc2621bd37fb4cb26be4ede06bd6636afb17110 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Mon, 27 Jul 2015 18:16:33 -0500 Subject: [PATCH 205/349] Adding a string reverse function. --- pixie/string.pxi | 9 ++++++++- tests/pixie/tests/test-strings.pxi | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pixie/string.pxi b/pixie/string.pxi index fdbbcbb3..4d1bf9a1 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -1,5 +1,6 @@ (ns pixie.string - (:require [pixie.string.internal :as si])) + (:require [pixie.stdlib :as std] + [pixie.string.internal :as si])) ; reexport native string functions (def substring si/substring) @@ -45,6 +46,12 @@ (str (substring s 0 i) r (substring s (+ i (count x)))) s)) +(defn reverse + "Returns s with its characters reversed." + [s] + (when s + (apply str (std/reverse s)))) + (defn join {:doc "Join the elements of the collection using an optional separator" :examples [["(require pixie.string :as s)"] diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 27b3f13b..c769cd8b 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -101,6 +101,12 @@ (t/assert= (s/replace-first "&&&" "&" "&&") "&&&&") (t/assert= (s/replace-first "oops" "" "WAT") "WAToops")) +(t/deftest test-reverse + (t/assert= (s/reverse "not a palindrome") "emordnilap a ton") + (t/assert= (s/reverse "tacocat") "tacocat") + (t/assert= (s/reverse "") "") + (t/assert= (s/reverse nil) nil)) + (t/deftest test-join (t/assert= (s/join []) "") (t/assert= (s/join [1]) "1") From 022631929813f256e3af56cddea3f03e437b5ca6 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 6 Aug 2015 19:49:16 -0500 Subject: [PATCH 206/349] Adding a string escape function. --- pixie/string.pxi | 13 +++++++++++++ tests/pixie/tests/test-strings.pxi | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/pixie/string.pxi b/pixie/string.pxi index fdbbcbb3..c65dfda5 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -73,6 +73,19 @@ false)))) true)) +(defn escape + "Return a new string, using cmap to escape each character ch + from s as follows: + + If (cmap ch) is nil, append ch to the new string. + If (cmap ch) is non-nil, append (str (cmap ch)) instead." + [s cmap] + (if (or (nil? s) + (nil? cmap)) + s + (apply str (map #(if-let [c (cmap %)] c %) + (vec s))))) + (defmacro interp ; TODO: This might merit special read syntax {:doc "String interpolation." diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 27b3f13b..e9201e1b 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -141,3 +141,12 @@ (t/assert= (s/blank? " ") true) (t/assert= (s/blank? " \t \n \r ") true) (t/assert= (s/blank? " foo ") false)) + +(t/deftest test-escape + (t/assert= (s/escape "foo" {\f \z}) "zoo") + (t/assert= (s/escape "foo" {\z \f}) "foo") + (t/assert= (s/escape "foobar" {\f \b \o \e \b \j}) "beejar") + (t/assert= (s/escape "foo" {}) "foo") + (t/assert= (s/escape "foo" nil) "foo") + (t/assert= (s/escape "" {\f \z}) "") + (t/assert= (s/escape nil {\f \z}) nil)) From ece248621a36e1215017d583f1a90109f7a182ed Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Tue, 11 Aug 2015 12:59:33 -0500 Subject: [PATCH 207/349] Adding a string-split function to pixie.string. --- pixie/string.pxi | 5 +++++ tests/pixie/tests/test-strings.pxi | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/pixie/string.pxi b/pixie/string.pxi index 9b40d8fd..866085a8 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -7,6 +7,11 @@ (def index-of (comp #(if (not= -1 %) %) si/index-of)) (def split si/split) +(defn split-lines + "Splits on \\n or \\r\\n, the two typical line breaks." + [s] + (when s (apply concat (map #(split % "\n") (split s "\r\n"))))) + (def ends-with? si/ends-with) (def starts-with? si/starts-with) diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 3c244c56..7e3f6376 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -27,6 +27,27 @@ (t/assert= (s/split s ",") ["hey" "ho" "huh"]) (t/assert= (s/split s "h") ["" "ey," "o," "u" ""]))) +(t/deftest test-split-lines + ;; Splits unix-style lines. + (t/assert= (s/split-lines "bibbidi\nbobbidi\nboo") + ["bibbidi" "bobbidi" "boo"]) + ;; Splits windows-style lines. + (t/assert= (s/split-lines "bibbidi\r\nbobbidi\r\nboo") + ["bibbidi" "bobbidi" "boo"]) + ;; Splits mixed up stuff. + (t/assert= (s/split-lines "bibbidi\nbobbidi\r\nboo") + ["bibbidi" "bobbidi" "boo"]) + ;; Doesn't split lonely \r + (t/assert= (s/split-lines "bibbidi\nbobbidi\rboo") + ["bibbidi" "bobbidi\rboo"]) + ;; Works with a single line. + (t/assert= (s/split-lines "BibbidiBobbidiBoo") + ["BibbidiBobbidiBoo"]) + ;; Works with empty strings. + (t/assert= (s/split-lines "") "") + ;; Nil pass-through. + (t/assert= (s/split-lines nil) nil)) + (t/deftest test-index-of (let [s "heyhohuh"] (t/assert= (s/index-of s "hey") 0) From 429962a63eff75ac5ce017ee6235e97ec7128bfa Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Tue, 11 Aug 2015 13:52:28 -0500 Subject: [PATCH 208/349] Fixing empty string test for split-lines. --- tests/pixie/tests/test-strings.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 7e3f6376..129c5768 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -44,7 +44,7 @@ (t/assert= (s/split-lines "BibbidiBobbidiBoo") ["BibbidiBobbidiBoo"]) ;; Works with empty strings. - (t/assert= (s/split-lines "") "") + (t/assert= (s/split-lines "") [""]) ;; Nil pass-through. (t/assert= (s/split-lines nil) nil)) From 0246159063300bcf8465b1ae65e6f05fc9ef4933 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 20 Jul 2015 17:21:44 +0100 Subject: [PATCH 209/349] clean up unused code --- pixie/vm/cons.py | 7 ------- pixie/vm/keyword.py | 2 +- pixie/vm/stdlib.py | 19 +++++++------------ tests/pixie/tests/test-keywords.pxi | 7 ++++++- tests/pixie/tests/test-stdlib.pxi | 7 +++++++ 5 files changed, 21 insertions(+), 21 deletions(-) diff --git a/pixie/vm/cons.py b/pixie/vm/cons.py index e9f0eb92..bc27357e 100644 --- a/pixie/vm/cons.py +++ b/pixie/vm/cons.py @@ -57,12 +57,5 @@ def _with_meta(self, meta): def cons(head, tail): return Cons(head, tail) -def count(self): - cnt = 0 - while self is not nil: - self = self.next() - cnt += 1 - return cnt - def cons(head, tail=nil): return Cons(head, tail, nil) diff --git a/pixie/vm/keyword.py b/pixie/vm/keyword.py index f6ce6dbc..7da9af14 100644 --- a/pixie/vm/keyword.py +++ b/pixie/vm/keyword.py @@ -77,5 +77,5 @@ def _hash(self): def _keyword(s): if not isinstance(s, String): from pixie.vm.object import runtime_error - runtime_error(u"Symbol name must be a string") + runtime_error(u"Keyword name must be a string") return keyword(s._str) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 9abbef3e..54358636 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,14 +1,16 @@ # -*- coding: utf-8 -*- from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ runtime_error, add_info, ExtraCodeInfo -from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ - list_copy, returns, intern_var +from pixie.vm.code import Namespace, BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ + list_copy, returns, intern_var, _ns_registry import pixie.vm.code as code from pixie.vm.primitives import true, false, nil import pixie.vm.numbers as numbers import rpython.rlib.jit as jit from rpython.rlib.rarithmetic import r_uint from rpython.rlib.objectmodel import we_are_translated +import os.path as path +import sys defprotocol("pixie.stdlib", "ISeq", ["-first", "-next"]) defprotocol("pixie.stdlib", "ISeqable", ["-seq"]) @@ -351,7 +353,6 @@ def is_undefined(var): def load_ns(filename): import pixie.vm.string as string import pixie.vm.symbol as symbol - import os.path as path if isinstance(filename, symbol.Symbol): affirm(rt.namespace(filename) is None, u"load-file takes a un-namespaced symbol") @@ -397,7 +398,6 @@ def _load_file(filename, compile=False): from pixie.vm.util import unicode_from_utf8 import pixie.vm.reader as reader import pixie.vm.libs.pxic.writer as pxic_writer - import os.path as path affirm(isinstance(filename, String), u"filename must be a string") @@ -439,7 +439,6 @@ def load_pxic_file(filename): from pixie.vm.libs.pxic.reader import Reader, read_obj from pixie.vm.reader import eof import pixie.vm.compiler as compiler - import sys if not we_are_translated(): print "Loading precompiled file while interpreted, this may take time" @@ -463,7 +462,6 @@ def load_pxic_file(filename): def load_reader(rdr): import pixie.vm.reader as reader import pixie.vm.compiler as compiler - import sys if not we_are_translated(): print "Loading file while interpreted, this may take time" @@ -531,7 +529,6 @@ def in_ns(ns_name): @as_var("ns-map") def ns_map(ns): - from pixie.vm.code import Namespace from pixie.vm.symbol import Symbol affirm(isinstance(ns, Namespace) or isinstance(ns, Symbol), u"ns must be a symbol or a namespace") @@ -551,7 +548,6 @@ def ns_map(ns): @as_var("ns-aliases") def ns_aliases(ns): - from pixie.vm.code import Namespace from pixie.vm.symbol import Symbol affirm(isinstance(ns, Namespace) or isinstance(ns, Symbol), u"ns must be a symbol or a namespace") @@ -573,7 +569,6 @@ def ns_aliases(ns): def refer(ns, refer, alias): from pixie.vm.symbol import Symbol from pixie.vm.string import String - from pixie.vm.code import _ns_registry if isinstance(ns, Symbol) or isinstance(ns, String): ns = _ns_registry.find_or_make(rt.name(ns)) @@ -594,9 +589,9 @@ def refer(ns, refer, alias): def refer_symbol(ns, sym, var): from pixie.vm.symbol import Symbol - affirm(isinstance(ns, code.Namespace), u"First argument must be a namespace") + affirm(isinstance(ns, Namespace), u"First argument must be a namespace") affirm(isinstance(sym, Symbol) and rt.namespace(sym) is None, u"Second argument must be a non-namespaced symbol") - affirm(isinstance(var, code.Var), u"Third argument must be a var") + affirm(isinstance(var, Var), u"Third argument must be a var") ns.add_refer_symbol(sym, var) return nil @@ -712,7 +707,7 @@ def _throw(ex): @as_var("resolve-in") def _var(ns, nm): - affirm(isinstance(ns, code.Namespace), u"First argument to resolve-in must be a namespace") + affirm(isinstance(ns, Namespace), u"First argument to resolve-in must be a namespace") var = ns.resolve(nm) return var if var is not None else nil diff --git a/tests/pixie/tests/test-keywords.pxi b/tests/pixie/tests/test-keywords.pxi index cdd0672c..9b4357e7 100644 --- a/tests/pixie/tests/test-keywords.pxi +++ b/tests/pixie/tests/test-keywords.pxi @@ -30,4 +30,9 @@ (t/deftest string-to-keyword (t/assert= (keyword "foo") :foo) - (t/assert= (keyword "foo/bar") :foo/bar)) + (t/assert= (keyword "foo/bar") :foo/bar) + (t/assert-throws? (keyword 1)) + (t/assert-throws? (keyword :a)) + (t/assert-throws? (keyword 'a)) + (t/assert-throws? (keyword nil)) + (t/assert-throws? (keyword true))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 441cf00b..9591da37 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -544,6 +544,13 @@ "c must be a type" (instance? [Keyword :also-not-a-type] 123))) +(t/deftest test-types-are-types + (t/assert= Type (type Keyword)) + (t/assert= Type (type Integer)) + (t/assert= Type (type Number)) + (t/assert= Type (type Object)) + (t/assert= Type (type Type))) + (t/deftest test-satisfies? (t/assert= (satisfies? IIndexed [1 2]) true) (t/assert= (satisfies? IIndexed '(1 2)) false) From 3c9b164d0dc51e810b81845b50690989a5e52d65 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 12 Aug 2015 21:38:13 +0100 Subject: [PATCH 210/349] read-line can handle buffered-streams --- pixie/io.pxi | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 0993b53d..2e8f19b8 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -47,10 +47,21 @@ (assert (string? filename) "Filename must be a string") (->FileStream (fs_open filename uv/O_RDONLY 0) 0 (uv/uv_buf_t))) +(defn buffered-read-line + [input-stream] + (let [line-feed (into #{} (map int [\newline \return]))] + (loop [acc []] + (let [ch (read-byte input-stream)] + (cond + (nil? ch) nil + (zero? ch) nil -(defn read-line - "Read one line from input-stream for each invocation. - nil when all lines have been read" + (and (pos? ch) (not (line-feed ch))) + (recur (conj acc ch)) + + :else (transduce (map char) string-builder acc)))))) + +(defn unbuffered-read-line [input-stream] (let [line-feed (into #{} (map int [\newline \return])) buf (buffer 1)] @@ -62,7 +73,22 @@ (and (zero? len) (empty? acc)) nil - :else (apply str (map char acc))))))) + :else (transduce (map char) string-builder acc)))))) + +(defn read-line + "Read one line from input-stream for each invocation. + nil when all lines have been read. + Pass a BufferedInputStream for best performance." + [input-stream] + (cond + (instance? BufferedInputStream input-stream) + (buffered-read-line input-stream) + + (satisfies? IInputStream input-stream) + (unbuffered-read-line input-stream) + + :else + (throw [::Exception "Expected an IInputStream or IByteInputStream"]))) (defn line-seq "Returns the lines of text from input-stream as a lazy sequence of strings. @@ -153,9 +179,11 @@ ([upstream] (buffered-input-stream upstream common/DEFAULT-BUFFER-SIZE)) ([upstream size] - (let [b (buffer size)] - (set-buffer-count! b size) - (->BufferedInputStream upstream size b)))) + (if (satisfies? IInputStream upstream) + (let [b (buffer size)] + (set-buffer-count! b size) + (->BufferedInputStream upstream size b)) + (throw [::Exception "Expected upstream to satisfy IInputStream"])))) (defn throw-on-error [result] (when (neg? result) From 9b5757820baeb451c01b4a05d6bee9952539e9da Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 13 Aug 2015 20:28:40 +0100 Subject: [PATCH 211/349] Simplify string/blank? --- pixie/string.pxi | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/pixie/string.pxi b/pixie/string.pxi index 866085a8..dc0fc7b7 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -75,14 +75,8 @@ "True if s is nil, empty, or contains only whitespace." [s] (if s - (let [white (set whitespace) - length (count s)] - (loop [index 0] - (if (= length index) - true - (if (white (nth s index)) - (recur (inc index)) - false)))) + (let [white (set whitespace)] + (every? white s)) true)) (defn escape From 8d0b9dc91eb9ef940d89d6b49ed23254907393d1 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 13 Aug 2015 20:29:33 +0100 Subject: [PATCH 212/349] added benchmarks --- benchmarks/read-line.pxi | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 benchmarks/read-line.pxi diff --git a/benchmarks/read-line.pxi b/benchmarks/read-line.pxi new file mode 100644 index 00000000..f09e687a --- /dev/null +++ b/benchmarks/read-line.pxi @@ -0,0 +1,18 @@ +(ns benchmarks.readline + (:require [pixie.time :as time] + [pixie.io :as io])) + +(def file-name "/usr/share/dict/words") + +(println "testing unbuffered") +(time/time (-> file-name + (io/open-read) + (io/line-seq) + (count))) + +(println "testing buffered") +(time/time (-> file-name + (io/open-read) + (io/buffered-input-stream) + (io/line-seq) + (count))) From a27b4fb6f1869476fa81a3e338a994d47fdb2843 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 13 Aug 2015 20:38:31 +0100 Subject: [PATCH 213/349] added test around buffered-input-stream creation --- pixie/io.pxi | 2 +- tests/pixie/tests/test-io.pxi | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 2e8f19b8..c07ca1a4 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -88,7 +88,7 @@ (unbuffered-read-line input-stream) :else - (throw [::Exception "Expected an IInputStream or IByteInputStream"]))) + (throw [::Exception "Expected an IInputStream or BufferedInputStream"]))) (defn line-seq "Returns the lines of text from input-stream as a lazy sequence of strings. diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 387c1440..532d9890 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -60,6 +60,10 @@ (t/assert= (char (io/read-byte f)) \i) (t/assert= (char (io/read-byte f)) \s))) +(t/deftest test-buffered-input-streams-throws-on-non-input-streams + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt"))] + (t/assert-throws? (io/buffered-input-stream f)))) + (t/deftest test-buffered-input-streams-seek ;; We use a buffer size of 4 because the test file isn't huge and i am terrible at ;; counting characters... From 920d05d266344585119d676de4b2d656062b1377 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 26 Jun 2015 11:41:28 +0100 Subject: [PATCH 214/349] Basic comparisons on some primitives --- pixie/stdlib.pxi | 97 ++++++++++++++++++++++++++++++ pixie/vm/object.py | 3 + pixie/vm/stdlib.py | 18 ++++-- tests/pixie/tests/test-compare.pxi | 59 ++++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 10 ++- 5 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 tests/pixie/tests/test-compare.pxi diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 880efd42..fd323a65 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2457,3 +2457,100 @@ Calling this function on something that is not ISeqable returns a seq with that (fn [v] (str ""))) (extend -repr Namespace -str) + + +(defn bool? + [x] + (instance? Bool x)) + +(defprotocol IComparable + (-compare [x y] + "Compare to objects returing 0 if the same -1 with x is logically smaller than y and 1 if x is logically larger")) + +(defn compare-numbers + [x y] + (cond + (> x y) 1 + (< x y) -1 + :else 0)) + +(defn compare-counted + [x y] + (if (= x y) + 0 + (let [min-length (min (count x) (count y))] + (loop [n 0] + (if (not= min-length n) + (let [diff (-compare (nth x n) + (nth y n))] + (if-not (zero? diff) + diff + (recur (inc n)))) + ;; We have compared all characters of the smallest string + ;; against the largest string. + ;; If equal lengths 0 otherwise -1 or 1 + (compare-numbers (count x) (count y))))))) + +(defn compare-named + [x y] + (if (= x y) + 0 + (compare-counted (str x) (str y)))) + +(extend-protocol IComparable + Number + (-compare [x y] + (if (number? y) + (compare-numbers x y) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + Character + (-compare [x y] + (if (char? y) + (compare-numbers (int x) (int y)) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + PersistentVector + (-compare [x y] + (if (vector? y) + (compare-counted x y) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + String + (-compare [x y] + (if (string? y) + (compare-counted (str x) (str y)) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + Keyword + (-compare [x y] + (if (keyword? y) + (compare-counted (str x) (str y)) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + Symbol + (-compare [x y] + (if (symbol? y) + (compare-counted (str x) (str y)) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) + + Bool + (-compare [x y] + (if (bool? y) + (cond + (= x y) 0 + (and (true? x) (false? y)) 1 + :else -1)) + (throw [::ComparisonError (str "Cannot compare: " x " to " y)])) + + Nil + (-compare [x y] + (if (nil? y) + 0 + (throw [::ComparisonError (str "Cannot compare: " x " to " y)])))) + +(defn compare + [x y] + (if (satisfies? IComparable x) + (-compare x y) + (throw [::ComparisonError (str x " does not satisfy IComparable")]))) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 4632eaf0..b80259e8 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -86,6 +86,9 @@ def name(self): def type(self): return Type._type + def parent(self): + return self._parent + def add_subclass(self, tp): self._subclasses.append(tp) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 9abbef3e..3a698060 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ +from pixie.vm.object import Object, Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ runtime_error, add_info, ExtraCodeInfo from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ list_copy, returns, intern_var @@ -319,13 +319,23 @@ def _instance(c, o): return true if istypeinstance(o, c) else false +def type_satisfies(proto, type): + affirm(isinstance(type, Type), u"type must be a Type") + if proto.satisfies(type): + return true + elif type == Object._type: + # top level type do not recurse + return false + elif type.parent(): + return type_satisfies(proto, type.parent()) + else: + return false + @returns(bool) @as_var("-satisfies?") def _satisfies(proto, o): affirm(isinstance(proto, Protocol), u"proto must be a Protocol") - - return true if proto.satisfies(o.type()) else false - + return type_satisfies(proto, o.type()) import pixie.vm.rt as rt diff --git a/tests/pixie/tests/test-compare.pxi b/tests/pixie/tests/test-compare.pxi new file mode 100644 index 00000000..3811e7c8 --- /dev/null +++ b/tests/pixie/tests/test-compare.pxi @@ -0,0 +1,59 @@ +(ns pixie.tests.test-compare + (require pixie.test :as t)) + +(t/deftest test-compare-numbers + (t/assert= (compare 1 1) 0) + (t/assert= (compare 1 2) -1) + (t/assert= (compare 1 -1) 1) + + (t/assert= (compare 1 1.0) 0) + (t/assert= (compare 1.0 1) 0) + (t/assert= (compare 1.0 2.0) -1) + (t/assert= (compare 1.0 -1.0) 1) + + (t/assert= (compare 1/2 1/2) 0) + (t/assert= (compare 1/3 1/2) -1) + (t/assert= (compare 1/2 1/3) 1)) + +(t/deftest test-compare-strings + (t/assert= (compare "a" "a") 0) + (t/assert= (compare "a" "b") -1) + (t/assert= (compare "b" "a") 1) + + (t/assert= (compare "aa" "a") 1) + (t/assert= (compare "a" "aa") -1) + + (t/assert= (compare "aa" "b") -1) + (t/assert= (compare "b" "aa") 1) + + (t/assert= (compare "aaaaaaaa" "azaaaaaa") -1) + (t/assert= (compare "azaaaaaa" "aaaaaaaa") 1)) + +(t/deftest test-compare-keywords + (t/assert= (compare :a :a) 0) + (t/assert= (compare :a :b) -1) + (t/assert= (compare :b :a) 1) + (t/assert= (compare :ns/a :ns/a) 0) + (t/assert= (compare :ns/a :ns/b) -1) + (t/assert= (compare :a :aa) -1) + (t/assert= (compare :aa :a) 1)) + +(t/deftest test-compare-symbols + (t/assert= (compare 'a 'a) 0) + (t/assert= (compare 'a 'b) -1) + (t/assert= (compare 'b 'a) 1) + (t/assert= (compare 'ns/a 'ns/a) 0) + (t/assert= (compare 'ns/a 'ns/b) -1) + (t/assert= (compare 'a 'aa) -1) + (t/assert= (compare 'aa 'a) 1)) + +(t/deftest test-compare-vectors + (t/assert= (compare [] []) 0) + (t/assert= (compare [1] []) 1) + (t/assert= (compare [1] [2]) -1) + (t/assert= (compare [1 2] [1 3]) -1) + (t/assert= (compare [:a] [:a]) 0) + (t/assert= (compare [:a] [:b]) -1) + (t/assert= (compare [:a] [:a :a]) -1) + (t/assert= (compare ["a"] ["a"]) 0) + (t/assert= (compare ["a"] ["a" "b"]) -1)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 441cf00b..e41d9207 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -555,7 +555,15 @@ (satisfies? :not-a-proto 123)) (t/assert-throws? RuntimeException "proto must be a Protocol" - (satisfies? [IIndexed :also-not-a-proto] [1 2]))) + (satisfies? [IIndexed :also-not-a-proto] [1 2])) + (defprotocol IFoo (foo [this])) + (extend-protocol IFoo + Number + (foo [this] this)) + (t/assert= (satisfies? IFoo 1) true) + (t/assert= (satisfies? IFoo 1.0) true) + (t/assert= (satisfies? IFoo 1/2) true) + (t/assert= (satisfies? IFoo \a) false)) (t/deftest test-reduce (t/assert= 5050 (reduce + (range 101))) From 70ea4345674fdfb05b35e8a4cbd3c0a77959cb76 Mon Sep 17 00:00:00 2001 From: Joshua Greenberg Date: Mon, 17 Aug 2015 21:44:23 -0700 Subject: [PATCH 215/349] improve the speed of repeated get-field calls to same custom type --- pixie/vm/custom_types.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 46c0f92a..498bf9fe 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -8,7 +8,7 @@ MAX_FIELDS = 32 class CustomType(Type): - _immutable_fields_ = ["_slots", "_rev?"] + _immutable_fields_ = ["_slots[*]", "_rev?"] def __init__(self, name, slots): Type.__init__(self, name) @@ -16,7 +16,7 @@ def __init__(self, name, slots): self._mutable_slots = {} self._rev = 0 - @jit.elidable_promote() + @jit.elidable def get_slot_idx(self, nm): return self._slots.get(nm, -1) @@ -26,19 +26,19 @@ def set_mutable(self, nm): self._mutable_slots[nm] = nm - @jit.elidable_promote() + @jit.elidable def _is_mutable(self, nm, rev): return nm in self._mutable_slots def is_mutable(self, nm): return self._is_mutable(nm, self._rev) - @jit.elidable_promote() + @jit.elidable def get_num_slots(self): return len(self._slots) class CustomTypeInstance(Object): - _immutable_fields_ = ["_type"] + _immutable_fields_ = ["_custom_type"] def __init__(self, type): affirm(isinstance(type, CustomType), u"Can't create a instance of a non custom type") self._custom_type = type @@ -60,7 +60,7 @@ def set_field(self, name, val): self.set_field_by_idx(idx, val) return self - @jit.elidable_promote() + @jit.elidable def _get_field_immutable(self, idx, rev): return self.get_field_by_idx(idx) From e5a6d291af4e6669c87266787374a3b5066fe9cd Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 18 Aug 2015 21:57:26 -0600 Subject: [PATCH 216/349] rebase master --- pixie/stacklets.pxi | 59 ++++++++++++++++++++-------- pixie/uv.pxi | 2 + pixie/vm/code.py | 8 ++++ pixie/vm/libs/ffi.py | 91 ++++++++++++++++++++++++++++++-------------- pixie/vm/object.py | 37 ++++++++++++++++++ pixie/vm/reader.py | 6 +++ pixie/vm/stdlib.py | 18 +++++++++ 7 files changed, 177 insertions(+), 44 deletions(-) diff --git a/pixie/stacklets.pxi b/pixie/stacklets.pxi index 1255fde0..267c7530 100644 --- a/pixie/stacklets.pxi +++ b/pixie/stacklets.pxi @@ -65,21 +65,26 @@ pixie.ffi/dispose!)) ;;; Sleep -(defn sleep [ms] - (let [f (fn [k] - (let [cb (atom nil) - timer (uv/uv_timer_t)] - (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb - (fn [handle] - (try - (run-and-process k) - (uv/uv_timer_stop timer) - (-dispose! @cb) - (catch ex - (println ex)))))) - (uv/uv_timer_init (uv/uv_default_loop) timer) - (uv/uv_timer_start timer @cb ms 0)))] - (call-cc f))) +(defn sleep + ([ms] + (sleep ms false)) + ([ms background?] + (let [f (fn [k] + (let [cb (atom nil) + timer (uv/uv_timer_t)] + (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb + (fn [handle] + (try + (run-and-process k) + (uv/uv_timer_stop timer) + (-dispose! @cb) + (catch ex + (println ex)))))) + (uv/uv_timer_init (uv/uv_default_loop) timer) + (when background? + (uv/uv_unref timer)) + (uv/uv_timer_start timer @cb ms 0)))] + (call-cc f)))) ;; Spawn (defn -spawn [start-fn] @@ -101,6 +106,17 @@ (catch e (println e))))))) +(defmacro spawn-background [& body] + `(let [frames (-get-current-var-frames nil)] + (-spawn (fn [h# _] + (-set-current-var-frames nil frames) + (try + (reset! stacklet-loop-h h#) + (let [result# (do ~@body)] + (call-cc (fn [_] nil))) + (catch e + (println e))))))) + (defn spawn-from-non-stacklet [f] (let [s (new-stacklet (fn [h _] @@ -117,6 +133,14 @@ (run-and-process s))))) +(defn finalizer-loop [] + (spawn-background + (loop [] + (-run-finalizers) + (sleep 1000 true) + (recur)))) + + (defn -with-stacklets [fn] (swap! running-threads inc) (reset! main-loop-running? true) @@ -134,12 +158,15 @@ (fn [h# _] (try (reset! stacklet-loop-h h#) + (finalizer-loop) (let [result# (do ~@body)] (swap! running-threads dec) (call-cc (fn [_] nil))) (catch e (println e)))))) + + (defn run-with-stacklets [f] (with-stacklets (f))) @@ -166,3 +193,5 @@ (fn [] (let [result (apply f args)] (-run-later (fn [] (run-and-process k result))))))))) + + diff --git a/pixie/uv.pxi b/pixie/uv.pxi index 06f7af7d..0bcf4fba 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -20,6 +20,8 @@ (f/defcfn uv_run) (f/defcfn uv_loop_alive) + (f/defcfn uv_unref) + (f/defcfn uv_ref) (f/defcfn uv_stop) (f/defcfn uv_loop_size) (f/defcfn uv_backend_fd) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 83fa6cd1..573273c1 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -693,6 +693,14 @@ def extend(self, tp, fn): self._fn_cache = {} self._protocol.add_satisfies(tp) + ## We have to special case this so that the GC doesn't go nuts trying to do a ton during + ## collection. + self.maybe_mark_finalizer(tp) + + def maybe_mark_finalizer(self, tp): + ## Gets overridden in stdlib + pass + def _find_parent_fn(self, tp): ## Search the entire object tree to find the function to execute assert isinstance(tp, object.Type) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 7d961ce4..0fc34ddb 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -29,6 +29,9 @@ """ +class PointerType(object.Object): + pass + class CType(object.Type): def __init__(self, name): @@ -89,54 +92,54 @@ def get_fn_ptr(self, nm): class FFIFn(object.Object): _type = object.Type(u"pixie.stdlib.FFIFn") - _immutable_fields_ = ["_is_inited", "_lib", "_name", "_arg_types[*]", "_arity", "_ret_type", "_is_variadic", \ - "_transfer_size", "_arg0_offset", "_ret_offset", "_cd"] + _immutable_fields_ = ["_name", "_f_ptr", "_c_fn_type"] def type(self): return FFIFn._type - def __init__(self, lib, name, arg_types, ret_type, is_variadic): + def __init__(self, name, fn_ptr, c_fn_type): + assert isinstance(c_fn_type, CFunctionType) self._rev = 0 self._name = name - self._lib = lib - self._arg_types = arg_types - self._arity = len(arg_types) - self._ret_type = ret_type - self._is_variadic = is_variadic - self._f_ptr = self._lib.get_fn_ptr(self._name) - self._cd = CifDescrBuilder(self._arg_types, self._ret_type).rawallocate() + self._f_ptr = fn_ptr + self._c_fn_type = c_fn_type @jit.unroll_safe def prep_exb(self, args): - size = jit.promote(self._cd.exchange_size) + cd = self._c_fn_type.get_cd() + fn_tp = self._c_fn_type + + size = jit.promote(cd.exchange_size) exb = rffi.cast(rffi.VOIDP, lltype.malloc(rffi.CCHARP.TO, size, flavor="raw")) tokens = [None] * len(args) - for i, tp in enumerate(self._arg_types): - offset_p = rffi.ptradd(exb, jit.promote(self._cd.exchange_args[i])) + for i, tp in enumerate(fn_tp._arg_types): + offset_p = rffi.ptradd(exb, jit.promote(cd.exchange_args[i])) tokens[i] = tp.ffi_set_value(offset_p, args[i]) return exb, tokens def get_ret_val_from_buffer(self, exb): - offset_p = rffi.ptradd(exb, jit.promote(self._cd.exchange_result)) - ret_val = self._ret_type.ffi_get_value(offset_p) + cd = self._c_fn_type.get_cd() + offset_p = rffi.ptradd(exb, jit.promote(cd.exchange_result)) + ret_val = self._c_fn_type._ret_type.ffi_get_value(offset_p) return ret_val @jit.unroll_safe def _invoke(self, args): arity = len(args) - if self._is_variadic: - if arity < self._arity: + tp_arity = len(self._c_fn_type._arg_types) + if self._c_fn_type._is_variadic: + if arity < tp_arity: runtime_error(u"Wrong number of args to fn: got " + unicode(str(arity)) + - u", expected at least " + unicode(str(self._arity))) + u", expected at least " + unicode(str(tp_arity))) else: - if arity != self._arity: + if arity != tp_arity: runtime_error(u"Wrong number of args to fn: got " + unicode(str(arity)) + - u", expected " + unicode(str(self._arity))) + u", expected " + unicode(str(tp_arity))) exb, tokens = self.prep_exb(args) - cd = jit.promote(self._cd) + cd = jit.promote(self._c_fn_type.get_cd()) #fp = jit.promote(self._f_ptr) jit_ffi_call(cd, self._f_ptr, @@ -194,7 +197,9 @@ def _ffi_fn__args(args): else: affirm(False, u"unknown ffi-fn option: :" + k) - f = FFIFn(lib, rt.name(nm), new_args, ret_type, is_variadic) + tp = CFunctionType(new_args, ret_type, is_variadic) + nm = rt.name(nm) + f = FFIFn(nm, lib.get_fn_ptr(nm), tp) return f @as_var("ffi-voidp") @@ -209,7 +214,7 @@ def _ffi_voidp(lib, nm): -class Buffer(object.Object): +class Buffer(PointerType): """ Defines a byte buffer with non-gc'd (therefore non-movable) contents """ _type = object.Type(u"pixie.stdlib.Buffer") @@ -474,9 +479,10 @@ def ffi_type(self): return clibffi.ffi_type_pointer cvoidp = CVoidP() -class VoidP(object.Object): +class VoidP(PointerType): + _type = cvoidp def type(self): - return cvoidp + return VoidP._type def __init__(self, raw_data): self._raw_data = raw_data @@ -567,7 +573,7 @@ def invoke(self, args): registered_callbacks = {} -class CCallback(object.Object): +class CCallback(PointerType): _type = object.Type(u"pixie.ffi.CCallback") def __init__(self, cft, raw_closure, id, fn): @@ -625,6 +631,17 @@ def ffi_callback(args, ret_type): return CFunctionType(args_w, ret_type) + +class TranslatedIDGenerator(py_object): + def __init__(self): + self._val = 0 + + def get_next(self): + self._val += 1 + return self._val + +id_generator = TranslatedIDGenerator() + @as_var(u"pixie.ffi", u"ffi-prep-callback") def ffi_prep_callback(tp, f): """(ffi-prep-callback callback-tp fn) @@ -634,7 +651,10 @@ def ffi_prep_callback(tp, f): affirm(isinstance(tp, CFunctionType), u"First argument to ffi-prep-callback must be a CFunctionType") raw_closure = rffi.cast(rffi.VOIDP, clibffi.closureHeap.alloc()) - unique_id = rffi.cast(lltype.Signed, raw_closure) + if not we_are_translated(): + unique_id = id_generator.get_next() + else: + unique_id = rffi.cast(lltype.Signed, raw_closure) res = clibffi.c_ffi_prep_closure(rffi.cast(clibffi.FFI_CLOSUREP, raw_closure), tp.get_cd().cif, invoke_callback, @@ -670,14 +690,16 @@ class CFunctionType(object.Type): base_type = object.Type(u"pixie.ffi.CType") _immutable_fields_ = ["_arg_types", "_ret-type", "_cd"] - def __init__(self, arg_types, ret_type): + def __init__(self, arg_types, ret_type, is_variadic=False): object.Type.__init__(self, name_gen.next(), CStructType.base_type) self._arg_types = arg_types self._ret_type = ret_type + self._is_variadic = is_variadic self._cd = CifDescrBuilder(self._arg_types, self._ret_type).rawallocate() def ffi_get_value(self, ptr): - runtime_error(u"Cannot get a callback value via FFI") + casted = rffi.cast(rffi.VOIDPP, ptr) + return FFIFn(u"", casted[0], self) def ffi_set_value(self, ptr, val): if isinstance(val, CCallback): @@ -804,7 +826,18 @@ def prep_ffi_call__args(args): affirm(isinstance(fn, CFunctionType), u"First arg must be a FFI function") +def comp_ptrs(a, b): + print a, b + assert isinstance(a, PointerType) + if not isinstance(b, PointerType): + return false + if a.raw_data() == b.raw_data(): + return true + return false +extend(proto._eq, Buffer)(comp_ptrs) +extend(proto._eq, CStructType.base_type)(comp_ptrs) +extend(proto._eq, VoidP)(comp_ptrs) import sys diff --git a/pixie/vm/object.py b/pixie/vm/object.py index b80259e8..54d1c38f 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -1,6 +1,26 @@ from rpython.rlib.objectmodel import compute_identity_hash import rpython.rlib.jit as jit + +class FinalizerRegistry(object): + def __init__(self): + # TODO: PyPy uses a linked list, investigate if we need that too + self._registry = [] + + def register(self, o): + print "register finalizer ", o + self._registry.append(o) + + def run_finalizers(self): + import pixie.vm.rt as rt + + vals = self._registry + self._registry = [] + for x in vals: + rt._finalize_BANG_(x) + +finalizer_registry = FinalizerRegistry() + class Object(object): """ Base Object for all VM objects """ @@ -29,6 +49,13 @@ def hash(self): def promote(self): return self + def __del__(self): + if self.type().has_finalizer(): + finalizer_registry.register(self) + + + + class TypeRegistry(object): def __init__(self): self._types = {} @@ -66,6 +93,7 @@ def get_type_by_name(nm): return _type_registry.get_by_name(nm) class Type(Object): + _immutable_fields_ = ["_name", "_has_finalizer?"] def __init__(self, name, parent=None, object_inited=True): assert isinstance(name, unicode), u"Type names must be unicode" _type_registry.register_type(name, self) @@ -79,6 +107,7 @@ def __init__(self, name, parent=None, object_inited=True): self._parent = parent self._subclasses = [] + self._has_finalizer = False def name(self): return self._name @@ -95,6 +124,14 @@ def add_subclass(self, tp): def subclasses(self): return self._subclasses + @jit.elidable_promote() + def has_finalizer(self): + return self._has_finalizer + + def set_finalizer(self): + self._has_finalizer = True + + Object._type = Type(u"pixie.stdlib.Object", None, False) Type._type = Type(u"pixie.stdlib.Type") diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 0df93adc..a6ae64cd 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -43,6 +43,9 @@ class PlatformReader(object.Object): _type = object.Type(u"PlatformReader") + def type(self): + return PlatformReader._type + def read(self): assert False @@ -53,6 +56,9 @@ def reset_line(self): return self class StringReader(PlatformReader): + _type = object.Type(u"pixie.stdlib.StringReader") + def type(self): + return StringReader._type def __init__(self, s): affirm(isinstance(s, unicode), u"StringReader requires unicode") diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 52fa547c..a69370d1 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ + runtime_error, add_info, ExtraCodeInfo, finalizer_registry +from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ + list_copy, returns, intern_var from pixie.vm.object import Object, Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ runtime_error, add_info, ExtraCodeInfo from pixie.vm.code import Namespace, BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ @@ -59,6 +63,15 @@ defprotocol("pixie.stdlib", "ITransientStack", ["-push!", "-pop!"]) defprotocol("pixie.stdlib", "IDisposable", ["-dispose!"]) +defprotocol("pixie.stdlib", "IFinalize", ["-finalize!"]) + +def maybe_mark_finalizer(self, tp): + if self is _finalize_BANG_: + print "MARKING ", tp + + tp.set_finalizer() + +code.PolymorphicFn.maybe_mark_finalizer = maybe_mark_finalizer @as_var("pixie.stdlib.internal", "-defprotocol") def _defprotocol(name, methods): @@ -913,3 +926,8 @@ def _add_exception_info(ex, str, data): assert isinstance(ex, RuntimeException) ex._trace.append(ExtraCodeInfo(rt.name(str), data)) return ex + +@as_var("-run-finalizers") +def _run_finalizers(): + finalizer_registry.run_finalizers() + return nil From f0be04a78cb6a9a6417318f38e79041ff8c6f161 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 6 Aug 2015 22:07:53 -0600 Subject: [PATCH 217/349] added finalizers latest work on some interop stuff --- Makefile | 8 +++- lib_pixie.py | 11 +++++ pixie/lib_pixie.py | 15 +++++++ pixie/stdlib.pxi | 87 +++++++++++++++++++++---------------- pixie/vm/c_api.py | 31 +++++++++++++ pixie/vm/compiler.py | 45 +++++++++++-------- pixie/vm/custom_types.py | 7 ++- pixie/vm/libs/ffi.py | 14 ++++-- pixie/vm/object.py | 3 -- pixie/vm/persistent_list.py | 3 ++ pixie/vm/rt.py | 2 + pixie/vm/stdlib.py | 8 ++-- setup.py | 17 ++++++++ target.py | 17 +++++--- 14 files changed, 193 insertions(+), 75 deletions(-) create mode 100644 lib_pixie.py create mode 100644 pixie/lib_pixie.py create mode 100644 pixie/vm/c_api.py create mode 100644 setup.py diff --git a/Makefile b/Makefile index 57204a3b..f857a332 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ PYTHON ?= python PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy -COMMON_BUILD_OPTS?=--thread --no-shared --gcrootfinder=shadowstack --continuation +COMMON_BUILD_OPTS?=--thread --gcrootfinder=shadowstack --continuation JIT_OPTS?=--opt=jit TARGET_OPTS?=target.py @@ -28,6 +28,12 @@ build_no_jit: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target.py && \ make compile_basics +build_no_jit_shared: fetch_externals + @if [ ! -d /usr/local/include/boost -a ! -d /usr/include/boost ] ; then echo "Boost C++ Library not found" && false; fi && \ + $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --shared target.py && \ + make compile_basics + + compile_basics: @echo -e "\n\n\n\nWARNING: Compiling core libs. If you want to modify one of these files delete the .pxic files first\n\n\n\n" ./pixie-vm -c pixie/uv.pxi -c pixie/io.pxi -c pixie/stacklets.pxi -c pixie/stdlib.pxi -c pixie/repl.pxi diff --git a/lib_pixie.py b/lib_pixie.py new file mode 100644 index 00000000..1a9f2967 --- /dev/null +++ b/lib_pixie.py @@ -0,0 +1,11 @@ +import ctypes, sys + +dll = ctypes.CDLL("libpixie-vm.dylib") + +dll.rpython_startup_code() +dll.pixie_init(sys.argv[0]) + +def repl(): + dll.pixie_execute_source("(ns user (:require [pixie.repl :as repl])) (pixie.repl/repl)") + +repl() \ No newline at end of file diff --git a/pixie/lib_pixie.py b/pixie/lib_pixie.py new file mode 100644 index 00000000..4bf67b59 --- /dev/null +++ b/pixie/lib_pixie.py @@ -0,0 +1,15 @@ +import ctypes +import os.path + +dll_name = os.path.join(os.path.dirname(__file__), "libpixie-vm.dylib") +print("Loading Pixie from " + dll_name) +dll = ctypes.CDLL(dll_name) + +dll.rpython_startup_code() +dll.pixie_init("/Users/tim/oss/pixie/pixie-vm".encode("ascii")) + + +def repl(): + dll.pixie_execute_source("(ns user (:require [pixie.repl :as repl])) (pixie.repl/repl)".encode('ascii')) + +#repl() \ No newline at end of file diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index fd323a65..fe4a85bb 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -841,7 +841,7 @@ there's a value associated with the key. Use `some` for checking for values." (fn [] ~@finally))))))) -(defn . +#_(defn . {:doc "Access the field named by the symbol. If further arguments are passed, invokes the method named by symbol, passing the object and arguments." @@ -1279,9 +1279,7 @@ and implements IAssociative, ILookup and IObject." "dissoc is not supported on defrecords"])) 'ILookup `(-val-at [self k not-found] - (if (contains? ~(set fields) k) - (. self k) - not-found)) + (get-field self k)) 'IObject `(-str [self] (str "<" ~(name nm) " " (reduce #(assoc %1 %2 (. self %2)) {} ~fields) ">")) @@ -2072,7 +2070,48 @@ The params can be destructuring bindings, see `(doc let)` for details."} `(fn* ~@name ~(first (first decls)) ~@(next (first decls))) `(fn* ~@name ~@decls)))) +;; TODO: implement :>> like in Clojure? +(defmacro condp + "Takes a binary predicate, an expression and a number of two-form clauses. +Calls the predicate on the first value of each clause and the expression. +If the result is truthy returns the second value of the clause. + +If the number of arguments is odd and no clause matches, the last argument is returned. +If the number of arguments is even and no clause matches, throws an exception." + [pred-form expr & clauses] + (let [x (gensym 'expr), pred (gensym 'pred)] + `(let [~x ~expr, ~pred ~pred-form] + (cond ~@(mapcat + (fn [[a b :as clause]] + (if (> (count clause) 1) + `((~pred ~a ~x) ~b) + `(:else ~a))) + (partition 2 clauses)) + :else (throw [:pixie.stdlib/MissingClauseException + "No matching clause!"]))))) + +(defmacro case + "Takes an expression and a number of two-form clauses. +Checks for each clause if the first part is equal to the expression. +If yes, returns the value of the second part. + +The first part of each clause can also be a set. If that is the case, the clause matches when the result of the expression is in the set. + +If the number of arguments is odd and no clause matches, the last argument is returned. +If the number of arguments is even and no clause matches, throws an exception." + [expr & args] + `(condp #(if (set? %1) (%1 %2) (= %1 %2)) + ~expr ~@args)) + + + + (deftype MultiMethod [dispatch-fn default-val methods] + IMessageObject + (-get-attr [this kw] + (case kw + :methods methods + :else nil)) IFn (-invoke [self & args] (let [dispatch-val (apply dispatch-fn args) @@ -2082,6 +2121,7 @@ The params can be destructuring bindings, see `(doc let)` for details."} _ (assert method (str "no method defined for " dispatch-val))] (apply method args)))) + (defmacro defmulti {:doc "Define a multimethod, which dispatches to its methods based on dispatch-fn." :examples [["(defmulti greet first)"] @@ -2107,13 +2147,17 @@ The params can be destructuring bindings, see `(doc let)` for details."} :added "0.1"} [name dispatch-val params & body] `(do - (let [methods (.methods ~name)] + (let [methods (.-methods ~name)] (swap! methods assoc ~dispatch-val (fn ~params ~@body)) ~name))) +(defmulti Foo :r) +(defmethod Foo :r + [x] x) + (defmacro declare {:doc "Forward declare the given variable names, setting them to nil." :added "0.1"} @@ -2215,39 +2259,6 @@ Expands to calls to `extend-type`." "Returns a collection that contains all the elements of the argument in reverse order." (into () coll)) -;; TODO: implement :>> like in Clojure? -(defmacro condp - "Takes a binary predicate, an expression and a number of two-form clauses. -Calls the predicate on the first value of each clause and the expression. -If the result is truthy returns the second value of the clause. - -If the number of arguments is odd and no clause matches, the last argument is returned. -If the number of arguments is even and no clause matches, throws an exception." - [pred-form expr & clauses] - (let [x (gensym 'expr), pred (gensym 'pred)] - `(let [~x ~expr, ~pred ~pred-form] - (cond ~@(mapcat - (fn [[a b :as clause]] - (if (> (count clause) 1) - `((~pred ~a ~x) ~b) - `(:else ~a))) - (partition 2 clauses)) - :else (throw [:pixie.stdlib/MissingClauseException - "No matching clause!"]))))) - -(defmacro case - "Takes an expression and a number of two-form clauses. -Checks for each clause if the first part is equal to the expression. -If yes, returns the value of the second part. - -The first part of each clause can also be a set. If that is the case, the clause matches when the result of the expression is in the set. - -If the number of arguments is odd and no clause matches, the last argument is returned. -If the number of arguments is even and no clause matches, throws an exception." - [expr & args] - `(condp #(if (set? %1) (%1 %2) (= %1 %2)) - ~expr ~@args)) - (defmacro use [ns] `(do diff --git a/pixie/vm/c_api.py b/pixie/vm/c_api.py new file mode 100644 index 00000000..38b30e6e --- /dev/null +++ b/pixie/vm/c_api.py @@ -0,0 +1,31 @@ + + +from rpython.rlib.entrypoint import entrypoint, RPython_StartupCode +from rpython.rtyper.lltypesystem import rffi, lltype +from rpython.rtyper.lltypesystem.lloperation import llop + + +@entrypoint('main', [rffi.CCHARP], c_name='pixie_init') +def pypy_execute_source(ll_progname): + from target import init_vm + after = rffi.aroundstate.after + if after: after() + progname = rffi.charp2str(ll_progname) + init_vm(progname) + res = 0 + before = rffi.aroundstate.before + if before: before() + return rffi.cast(rffi.INT, res) + +@entrypoint('main', [rffi.CCHARP], c_name='pixie_execute_source') +def pypy_execute_source(ll_source): + from target import EvalFn, run_with_stacklets + after = rffi.aroundstate.after + if after: after() + source = rffi.charp2str(ll_source) + f = EvalFn(source) + run_with_stacklets.invoke([f]) + res = 0 + before = rffi.aroundstate.before + if before: before() + return rffi.cast(rffi.INT, res) \ No newline at end of file diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index 7dbb7477..5d0f214f 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -10,6 +10,8 @@ from pixie.vm.atom import Atom from rpython.rlib.rarithmetic import r_uint, intmask from pixie.vm.persistent_list import EmptyList +from pixie.vm.cons import cons +from pixie.vm.persistent_list import create_from_list import pixie.vm.rt as rt @@ -321,23 +323,6 @@ def compile_set_literal(form, ctx): compile_cons(set_call, ctx) -def macroexpand(form): - sym = rt.first(form) - if isinstance(sym, symbol.Symbol): - s = rt.name(sym) - if s.startswith(".") and s != u".": - if rt.count(form) < 2: - raise Exception("malformed dot expression, expecting (.member obj ...)") - - method = rt.keyword(rt.wrap(rt.name(sym)[1:])) - obj = rt.first(rt.next(form)) - dot = rt.symbol(rt.wrap(u".")) - call = rt.cons(dot, rt.cons(obj, rt.cons(method, rt.next(rt.next(form))))) - - return call - - return form - def compile_meta(meta, ctx): ctx.push_const(code.intern_var(u"pixie.stdlib", u'with-meta')) ctx.bytecode.append(code.DUP_NTH) @@ -351,13 +336,37 @@ def compile_meta(meta, ctx): ctx.bytecode.append(1) ctx.sub_sp(1) +def maybe_oop_invoke(form): + head = rt.first(form) + if isinstance(rt.first(form), symbol.Symbol) and rt.name(head).startswith(".-"): + postfix = rt.next(form) + affirm(rt.count(postfix) == 1, u" Attribute lookups must only have one argument") + subject = rt.first(postfix) + kw = keyword(rt.name(head)[2:]) + fn = symbol.symbol(u"pixie.stdlib/-get-attr") + return create_from_list([fn, subject, kw]) + + elif isinstance(rt.first(form), symbol.Symbol) and rt.name(head).startswith("."): + subject = rt.first(rt.next(form)) + postfix = rt.next(rt.next(form)) + form = cons(keyword(rt.name(head)[1:]), postfix) + form = cons(subject, form) + form = cons(symbol.symbol(u"pixie.stdlib/-call-method"), form) + return form + + else: + return form + + def compile_form(form, ctx): if form is nil: ctx.push_const(nil) return if rt._satisfies_QMARK_(rt.ISeq.deref(), form) and form is not nil: - form = macroexpand(form) + + form = maybe_oop_invoke(form) + return compile_cons(form, ctx) if isinstance(form, numbers.Integer): ctx.push_const(form) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 498bf9fe..68a10d8b 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -1,4 +1,4 @@ -from pixie.vm.object import Object, Type, affirm, runtime_error +from pixie.vm.object import Object, Type, affirm, runtime_error, finalizer_registry import rpython.rlib.jit as jit from pixie.vm.code import as_var from pixie.vm.numbers import Integer, Float @@ -86,6 +86,11 @@ def get_field(self, name): return value + def __del__(self): + if self.type().has_finalizer(): + finalizer_registry.register(self) + + create_type_prefix = """ def new_inst(tp, fields): l = len(fields) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 0fc34ddb..86fdc840 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -688,7 +688,7 @@ def next(self): class CFunctionType(object.Type): base_type = object.Type(u"pixie.ffi.CType") - _immutable_fields_ = ["_arg_types", "_ret-type", "_cd"] + _immutable_fields_ = ["_arg_types", "_ret_type", "_cd", "_is_variadic"] def __init__(self, arg_types, ret_type, is_variadic=False): object.Type.__init__(self, name_gen.next(), CStructType.base_type) @@ -724,7 +724,7 @@ def ffi_size(self): def ffi_type(self): return clibffi.ffi_type_pointer -class CStruct(object.Object): +class CStruct(PointerType): _immutable_fields_ = ["_type", "_buffer"] def __init__(self, tp, buffer): self._type = tp @@ -827,7 +827,6 @@ def prep_ffi_call__args(args): def comp_ptrs(a, b): - print a, b assert isinstance(a, PointerType) if not isinstance(b, PointerType): return false @@ -835,10 +834,19 @@ def comp_ptrs(a, b): return true return false +def hash_ptr(a): + assert isinstance(a, PointerType) + hashval = rffi.cast(lltype.Signed, a.raw_data()) + return rt.wrap(hashval) + extend(proto._eq, Buffer)(comp_ptrs) extend(proto._eq, CStructType.base_type)(comp_ptrs) extend(proto._eq, VoidP)(comp_ptrs) +extend(proto._hash, Buffer)(hash_ptr) +extend(proto._hash, CStructType.base_type)(hash_ptr) +extend(proto._hash, VoidP)(hash_ptr) + import sys diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 54d1c38f..ccddf276 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -49,9 +49,6 @@ def hash(self): def promote(self): return self - def __del__(self): - if self.type().has_finalizer(): - finalizer_registry.register(self) diff --git a/pixie/vm/persistent_list.py b/pixie/vm/persistent_list.py index 91f76da8..54d6b11a 100644 --- a/pixie/vm/persistent_list.py +++ b/pixie/vm/persistent_list.py @@ -82,6 +82,9 @@ def create_from_list(lst): i -= 1 return acc +def create(*args): + return create_from_list(args) + @extend(proto._meta, PersistentList) def _meta(self): assert isinstance(self, PersistentList) diff --git a/pixie/vm/rt.py b/pixie/vm/rt.py index 37fa0676..c17389cb 100644 --- a/pixie/vm/rt.py +++ b/pixie/vm/rt.py @@ -73,6 +73,8 @@ def wrapper(*args): import pixie.vm.string_builder import pixie.vm.stacklet + import pixie.vm.c_api + @specialize.argtype(0) def wrap(x): if isinstance(x, bool): diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index a69370d1..a9b9aea9 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,10 +1,6 @@ # -*- coding: utf-8 -*- -from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ - runtime_error, add_info, ExtraCodeInfo, finalizer_registry -from pixie.vm.code import BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ - list_copy, returns, intern_var from pixie.vm.object import Object, Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ - runtime_error, add_info, ExtraCodeInfo + runtime_error, add_info, ExtraCodeInfo, finalizer_registry from pixie.vm.code import Namespace, BaseCode, PolymorphicFn, wrap_fn, as_var, defprotocol, extend, Protocol, Var, \ list_copy, returns, intern_var, _ns_registry import pixie.vm.code as code @@ -65,6 +61,8 @@ defprotocol("pixie.stdlib", "IDisposable", ["-dispose!"]) defprotocol("pixie.stdlib", "IFinalize", ["-finalize!"]) +defprotocol("pixie.stdlib", "IMessageObject", ["-call-method", "-get-attr"]) + def maybe_mark_finalizer(self, tp): if self is _finalize_BANG_: print "MARKING ", tp diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..6046e6f4 --- /dev/null +++ b/setup.py @@ -0,0 +1,17 @@ +from setuptools import setup, find_packages +from codecs import open +from os import path + +here = path.abspath(path.dirname(__file__)) + +setup( + name="pixie", + version="0.2.0", + description="A fast lightweight lisp with 'magical' powers", + + license="LGPL", + + keywords="development language", + + package_data={"pixie": ["libpixie-vm.dylib", "pixie-vm"]} +) \ No newline at end of file diff --git a/target.py b/target.py index a4126317..c5c3fed8 100644 --- a/target.py +++ b/target.py @@ -147,19 +147,23 @@ def load_stdlib(): from pixie.vm.code import intern_var run_with_stacklets = intern_var(u"pixie.stacklets", u"run-with-stacklets") +def init_vm(progname): + import pixie.vm.stacklet + pixie.vm.stacklet.init() + + init_load_path(progname) + load_stdlib() + add_to_load_paths(".") + def entry_point(args): try: - import pixie.vm.stacklet - pixie.vm.stacklet.init() + + init_vm(args[0]) interactive = True exit = False script_args = [] - init_load_path(args[0]) - load_stdlib() - add_to_load_paths(".") - i = 1 while i < len(args): arg = args[i] @@ -227,6 +231,7 @@ def entry_point(args): def add_to_load_paths(path): rt.reset_BANG_(LOAD_PATHS.deref(), rt.conj(rt.deref(LOAD_PATHS.deref()), rt.wrap(path))) + def init_load_path(self_path): if not path.isfile(self_path): self_path = find_in_path(self_path) From 5865ccefc91df08dceb325a781e42fd7b4d708d3 Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Tue, 18 Aug 2015 22:01:40 -0600 Subject: [PATCH 218/349] remove old file --- setup.py | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 setup.py diff --git a/setup.py b/setup.py deleted file mode 100644 index 6046e6f4..00000000 --- a/setup.py +++ /dev/null @@ -1,17 +0,0 @@ -from setuptools import setup, find_packages -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -setup( - name="pixie", - version="0.2.0", - description="A fast lightweight lisp with 'magical' powers", - - license="LGPL", - - keywords="development language", - - package_data={"pixie": ["libpixie-vm.dylib", "pixie-vm"]} -) \ No newline at end of file From 3d25e8d25ce656b392d8df05279a2b44ef6cc96a Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 19 Aug 2015 06:38:17 -0600 Subject: [PATCH 219/349] fixup tests and deftype to use the new OOP model --- pixie/stdlib.pxi | 51 +++++++++++++++++++--------- tests/pixie/tests/test-defrecord.pxi | 3 +- tests/pixie/tests/test-deftype.pxi | 31 +++++++---------- tests/pixie/tests/test-io.pxi | 2 +- 4 files changed, 51 insertions(+), 36 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index fe4a85bb..26bb1b6a 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1183,14 +1183,9 @@ Creates new maps if the keys are not present." (defmacro deftype {:doc "Define a custom type." :examples [["(deftype Person [name] - Object - (say-hi [self other-name] - (str \"Hi, I'm \" name \". You're \" other-name \", right?\")) - IObject (-str [self] (str \"\")))"] - ["(.say-hi (->Person \"James\") \"Paul\")" nil "Hi, I'm James. You're Paul, right?"] ["(str (->Person \"James\"))" nil ""]] :added "0.1"} [nm fields & body] @@ -1256,40 +1251,64 @@ Creates new maps if the keys are not present." ~ctor ~@proto-bodies))) +(defn -make-record-assoc-body [cname fields] + (let [k-sym (gensym "k") + v-sym (gensym "v") + this-sym (gensym "this") + result `(-assoc [~this-sym ~k-sym ~v-sym] + (case ~k-sym + ~@(mapcat + (fn [k] + [k `(~cname ~@(mapv (fn [x] + (if (= x k) + v-sym + `(get-field ~this-sym ~x))) + fields))]) + fields) + (throw [:pixie.stdlib/NotImplementedException + (str "Can't assoc to a unknown field: " ~k-sym)])))] + result)) + (defmacro defrecord {:doc "Define a record type. Similar to `deftype`, but supports construction from a map using `map->Type` and implements IAssociative, ILookup and IObject." :added "0.1"} - [nm fields & body] + [nm field-syms & body] (let [ctor-name (symbol (str "->" (name nm))) map-ctor-name (symbol (str "map" (name ctor-name))) - fields (transduce (map (comp keyword name)) conj fields) + fields (transduce (map (comp keyword name)) conj field-syms) type-from-map `(defn ~map-ctor-name [m] (apply ~ctor-name (map #(get m %) ~fields))) default-bodies ['IAssociative - `(-assoc [self k v] - (let [m (reduce #(assoc %1 %2 (. self %2)) {} ~fields)] - (~map-ctor-name (assoc m k v)))) + (-make-record-assoc-body ctor-name fields) + `(-contains-key [self k] (contains? ~(set fields) k)) `(-dissoc [self k] (throw [:pixie.stdlib/NotImplementedException "dissoc is not supported on defrecords"])) 'ILookup - `(-val-at [self k not-found] - (get-field self k)) + (let [self-nm (gensym "self") + k-nm (gensym "k")] + `(-val-at [~self-nm ~k-nm not-found#] + (case ~k-nm + ~@(mapcat + (fn [k] + [k `(get-field ~self-nm ~k-nm)]) + fields) + not-found#))) 'IObject - `(-str [self] - (str "<" ~(name nm) " " (reduce #(assoc %1 %2 (. self %2)) {} ~fields) ">")) + `(-str [self#] + (str "<" ~(name nm) " " (reduce #(assoc %1 %2 (%2 self#)) {} ~fields) ">")) `(-eq [self other] (and (instance? ~nm other) ~@(map (fn [field] - `(= (. self ~field) (. other ~field))) + `(= (~field self) (~field other))) fields))) `(-hash [self] - (throw [:pixie.stdlib/NotImplementedException "not implemented"]))] + (hash [~@field-syms]))] deftype-decl `(deftype ~nm ~fields ~@default-bodies ~@body)] `(do ~type-from-map ~deftype-decl))) diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index 382247d1..bc63724a 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -38,7 +38,8 @@ (t/assert (satisfies? IAssociative t)) (t/assert= t (assoc t4 :three 3)) (let [t' (assoc t :one 42) - t-oops (assoc t :oops 'never-found)] + t-oops (try (assoc t :oops 'never-found) + (catch ex t))] (t/assert (not (= t t'))) (t/assert= (get t' :one) 42) (t/assert= t t-oops) diff --git a/tests/pixie/tests/test-deftype.pxi b/tests/pixie/tests/test-deftype.pxi index 49f5e444..f6123aa0 100644 --- a/tests/pixie/tests/test-deftype.pxi +++ b/tests/pixie/tests/test-deftype.pxi @@ -10,8 +10,7 @@ (foreach [obj-and-val [[o1 1] [o2 2]]] (let [o (first obj-and-val) v (second obj-and-val)] - (t/assert= (. o :val) v) - (t/assert= (.val o) v))))) + (t/assert= (get-field o :val) v))))) (deftype MagicalVectorMap [] IMap IVector) @@ -34,14 +33,17 @@ (foreach [obj-and-val [[o1 1] [o2 2]]] (let [o (first obj-and-val) v (second obj-and-val)] - (t/assert= (. o :val) v) - (t/assert= (.val o) v) + (t/assert= (get-field o :val) v) (t/assert (satisfies? ICounted o)) (t/assert= (-count o) v) (t/assert= (count o) v))))) +(defprotocol TestObject + (add [self x & args]) + (one-plus [self x & xs])) + (deftype Three [:one :two :three] - Object + TestObject (add [self x & args] (apply + x args)) (one-plus [self x & xs] @@ -50,7 +52,7 @@ (-count [self] (+ one two three))) (deftype Three2 [one two three] - Object + TestObject (add [self x & args] (apply + x args)) (one-plus [self x & xs] @@ -66,20 +68,13 @@ one (second obj-and-vals) two (third obj-and-vals) three (fourth obj-and-vals)] - (t/assert= (. o :one) one) - (t/assert= (.one o) one) - (t/assert= (. o :two) two) - (t/assert= (.two o) two) - (t/assert= (. o :three) three) - (t/assert= (.three o) three) + (t/assert= (get-field o :one) one) + (t/assert= (get-field o :two) two) + (t/assert= (get-field o :three) three) (t/assert (satisfies? ICounted o)) (t/assert= (-count o) (+ one two three)) (t/assert= (count o) (+ one two three)) - (t/assert= (.add o 21 21) 42) - (t/assert= (.one-plus o 9) (+ one 9)) - - ; arity-1 (just the self arg) not supported for now - (t/assert= (.add o) (. o :add)) - (t/assert= (.one-plus o) (. o :one-plus)))))) + (t/assert= (add o 21 21) 42) + (t/assert= (one-plus o 9) (+ one 9)))))) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 532d9890..523d124e 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -148,7 +148,7 @@ (io/run-command "rm compressed-output.gz") (compress-content (io/open-write "compressed-output.gz") (range 1000)) ;; decompress the file with zcat - (io/run-command "zcat compressed-output.gz > compressed-output.txt") + (io/run-command "cat compressed-coutput | zcat > compressed-output.txt") (t/assert= (range 1000) (read-string (io/slurp "compressed-output.txt"))) ;; Wrapping an IInputStream in decompressing-stream should get the same result From b7036d1dc56386f78b9a36e2b723d0d137e636cd Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 19 Aug 2015 06:42:53 -0600 Subject: [PATCH 220/349] fixed compat issue with OSX and gzip tests --- tests/pixie/tests/test-io.pxi | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 523d124e..26cf8e70 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -148,7 +148,6 @@ (io/run-command "rm compressed-output.gz") (compress-content (io/open-write "compressed-output.gz") (range 1000)) ;; decompress the file with zcat - (io/run-command "cat compressed-coutput | zcat > compressed-output.txt") (t/assert= (range 1000) (read-string (io/slurp "compressed-output.txt"))) ;; Wrapping an IInputStream in decompressing-stream should get the same result From 884d98397df4d58d230cc79c0226be9a50681b7a Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Wed, 19 Aug 2015 16:03:32 -0600 Subject: [PATCH 221/349] use gunzip --- tests/pixie/tests/test-io.pxi | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 26cf8e70..663bf52b 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -148,6 +148,7 @@ (io/run-command "rm compressed-output.gz") (compress-content (io/open-write "compressed-output.gz") (range 1000)) ;; decompress the file with zcat + (io/run-command "gunzip compressed-output.gz -c > compressed-output.txt") (t/assert= (range 1000) (read-string (io/slurp "compressed-output.txt"))) ;; Wrapping an IInputStream in decompressing-stream should get the same result From b408e7e4868f3bfb839297cc45a5d3eeb997b2fa Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 20 Aug 2015 15:31:33 +0100 Subject: [PATCH 222/349] simplifies -repr and -str code --- pixie/stdlib.pxi | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 26bb1b6a..fd105624 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -343,17 +343,17 @@ (extend -str PersistentVector (fn [v] - (apply str "[" (conj (transduce (interpose " ") conj v) "]")))) + (str "[" (transduce (interpose " ") string-builder v) "]"))) (extend -repr PersistentVector (fn [v] - (apply str "[" (conj (transduce (comp (map -repr) (interpose " ")) conj v) "]")))) + (str "[" (transduce (comp (map -repr) (interpose " ")) string-builder v) "]"))) (extend -str Cons (fn [v] - (apply str "(" (conj (transduce (interpose " ") conj v) ")")))) + (str "(" (transduce (interpose " ") string-builder v) ")"))) (extend -repr Cons (fn [v] - (apply str "(" (conj (transduce (comp (map -repr) (interpose " ")) conj v) ")")))) + (str "(" (transduce (comp (map -repr) (interpose " ")) string-builder v) ")"))) (extend -hash Cons (fn [v] @@ -361,10 +361,10 @@ (extend -str PersistentList (fn [v] - (apply str "(" (conj (transduce (interpose " ") conj v) ")")))) + (str "(" (transduce (interpose " ") string-builder v) ")"))) (extend -repr PersistentList (fn [v] - (apply str "(" (conj (transduce (comp (map -repr) (interpose " ")) conj v) ")")))) + (str "(" (transduce (comp (map -repr) (interpose " ")) string-builder v) ")"))) (extend -hash PersistentList (fn [v] @@ -373,10 +373,10 @@ (extend -str LazySeq (fn [v] - (apply str "(" (conj (transduce (interpose " ") conj v) ")")))) + (str "(" (transduce (interpose " ") string-builder v) ")"))) (extend -repr LazySeq (fn [v] - (apply str "(" (conj (transduce (comp (map -repr) (interpose " ")) conj v) ")")))) + (str "(" (transduce (comp (map -repr) (interpose " ")) string-builder v) ")"))) (extend -hash PersistentVector (fn [v] @@ -945,10 +945,10 @@ If further arguments are passed, invokes the method named by symbol, passing the (extend -str MapEntry (fn [v] - (apply str "[" (conj (transduce (interpose " ") conj v) "]")))) + (str "[" (transduce (interpose " ") string-builder v) "]"))) (extend -repr MapEntry (fn [v] - (apply str "[" (conj (transduce (comp (map -repr) (interpose " ")) conj v) "]")))) + (str "[" (transduce (comp (map -repr) (interpose " ")) string-builder v) "]"))) (extend -hash MapEntry (fn [v] @@ -989,11 +989,11 @@ If further arguments are passed, invokes the method named by symbol, passing the (extend -str PersistentHashMap (fn [v] (let [entry->str (map (fn [e] (vector (key e) " " (val e))))] - (apply str "{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + (str "{" (transduce (comp entry->str (interpose [", "]) cat) string-builder v) "}")))) (extend -repr PersistentHashMap (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] - (apply str "{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + (str "{" (transduce (comp entry->str (interpose [", "]) cat) string-builder v) "}")))) (extend -hash PersistentHashMap (fn [v] @@ -1005,10 +1005,10 @@ If further arguments are passed, invokes the method named by symbol, passing the (extend -str PersistentHashSet (fn [s] - (apply str "#{" (conj (transduce (interpose " ") conj s) "}")))) + (str "#{" (transduce (interpose " ") string-builder s) "}"))) (extend -repr PersistentHashSet (fn [s] - (apply str "#{" (conj (transduce (comp (map -repr) (interpose " ")) conj s) "}")))) + (str "#{" (transduce (comp (map -repr) (interpose " ")) string-builder s) "}"))) (extend -empty Cons (fn [_] '())) (extend -empty LazySeq (fn [_] '())) @@ -2408,12 +2408,12 @@ Calling this function on something that is not ISeqable returns a seq with that (extend -str Environment (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] - (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + (str "#Environment{" (transduce (comp entry->str (interpose [", "]) cat) string-builder v) "}")))) (extend -repr Environment (fn [v] (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] - (apply str "#Environment{" (conj (transduce (comp entry->str (interpose [", "]) cat) conj v) "}"))))) + (str "#Environment{" (transduce (comp entry->str (interpose [", "]) cat) string-builder v) "}")))) (defn interleave "Returns a seq of all the items in the input collections interleaved" From d4954723a85babf8aecde90276257095a3170162 Mon Sep 17 00:00:00 2001 From: Joshua Greenberg Date: Thu, 20 Aug 2015 20:06:57 -0700 Subject: [PATCH 223/349] add back jit.elidable_promote in the CustomType class --- pixie/vm/custom_types.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 68a10d8b..0cbbc4ef 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -16,7 +16,7 @@ def __init__(self, name, slots): self._mutable_slots = {} self._rev = 0 - @jit.elidable + @jit.elidable_promote() def get_slot_idx(self, nm): return self._slots.get(nm, -1) @@ -26,14 +26,14 @@ def set_mutable(self, nm): self._mutable_slots[nm] = nm - @jit.elidable + @jit.elidable_promote() def _is_mutable(self, nm, rev): return nm in self._mutable_slots def is_mutable(self, nm): return self._is_mutable(nm, self._rev) - @jit.elidable + @jit.elidable_promote() def get_num_slots(self): return len(self._slots) From af63494ddc48612f51fbdbe743fc91437607fbe7 Mon Sep 17 00:00:00 2001 From: Joshua Greenberg Date: Thu, 20 Aug 2015 21:26:36 -0700 Subject: [PATCH 224/349] improve "repeat": faster reducing, yet stays lazy even for finite sizes --- pixie/stdlib.pxi | 52 +++++++++++++++++++++++++++---- tests/pixie/tests/test-stdlib.pxi | 21 +++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 26bb1b6a..398a6144 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1347,12 +1347,6 @@ and implements IAssociative, ILookup and IObject." (puts (apply pr-str args)) nil) -(defn repeat - ([x] - (cons x (lazy-seq* (fn [] (repeat x))))) - ([n x] - (take n (repeat x)))) - (defn repeatedly {:doc "Returns a lazy seq that contains the return values of repeated calls to f. @@ -1814,6 +1808,52 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (* -1 x) x)) +(deftype Repeat [n x] + IReduce + (-reduce [self f init] + (loop [i 0 + acc init] + (if (< i n) + (let [acc (f acc x)] + (if (reduced? acc) + @acc + (recur (inc i) acc))) + acc))) + ICounted + (-count [self] + n) + IIndexed + (-nth [self idx] + (if (and (>= idx 0) (< idx n)) + x + (throw [:pixie.stdlib/OutOfRangeException "Index out of Range"]))) + (-nth-not-found [self idx not-found] + (if (and (>= idx 0) (< idx n)) + x + not-found)) + ISeqable + (-seq [self] + (when (>= n 1) + (cons x (lazy-seq* (fn [] (->Repeat (dec n) x))))))) + +(extend -str Repeat + (fn [v] + (-str (seq v)))) + +(extend -repr Repeat -str) + +(defn repeat + {:doc "Returns a seqable of repetitions of a value." + :examples [["(repeat 3 :buffalo)" nil (:buffalo :buffalo :buffalo)] + ["(map vector '(1 2 3) (repeat :ahahah))" nil ([1 :ahahah] [2 :ahahah] [3 :ahahah])]] + :signatures [[x] [n x]] + :added "0.1"} + ([x] + (let [positive-infinity (/ 1.0 0)] + (repeat positive-infinity x))) + ([n x] + (->Repeat n x))) + (deftype Range [start stop step] IReduce (-reduce [self f init] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index fa6d3f16..9dc61e20 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -10,6 +10,7 @@ (t/assert= (map inc [1 2 3]) [2 3 4]) (t/assert= (map + [1 2 3] [4 5 6]) [5 7 9]) (t/assert= (map + [1 2 3] [4 5 6] [7 8 9]) [12 15 18]) + (t/assert= (map + [1 2 3] (repeat 7)) [8 9 10]) (let [value (map identity [1 2 3])] (t/assert= (seq value) [1 2 3]) (t/assert= (seq value) [1 2 3]))) @@ -37,6 +38,7 @@ (t/assert= (str (type 3)) "") (t/assert= (str [1 {:a 1} "hey"]) "[1 {:a 1} hey]") (t/assert= (seq (map identity "iterable")) '(\i \t \e \r \a \b \l \e)) + (t/assert= (str (repeat 3 7)) "(7 7 7)") (t/assert= (str (range 3)) "(0 1 2)")) (t/deftest test-repr @@ -60,6 +62,7 @@ (t/assert= (-repr (type 3)) "pixie.stdlib.Integer") (t/assert= (-repr [1 {:a 1} "hey"]) "[1 {:a 1} \"hey\"]") + (t/assert= (-repr (repeat 3 7)) "(7 7 7)") (t/assert= (-repr (range 3)) "(0 1 2)")) (t/deftest test-nth @@ -67,6 +70,7 @@ (t/assert= (nth [1 2 3] 1) 2) (t/assert= (nth '(1 2 3) 1) 2) (t/assert= (nth (make-array 3) 2) nil) + (t/assert= (nth (repeat 4 1) 3) 1) (t/assert= (nth (range 4) 1) 1) (t/assert= (nth "hithere" 1) \i) @@ -92,6 +96,9 @@ (try (nth '() 0) (catch ex (t/assert= (ex-msg ex) "Index out of Range"))) + (try + (nth (repeat 99 nil) 99) + (catch ex (t/assert= (ex-msg ex) "Index out of Range"))) (try (nth (range 0 0) 0) (catch ex (t/assert= (ex-msg ex) "Index out of Range"))) @@ -100,12 +107,14 @@ (t/assert= (nth [1 2 3] 99 :default) :default) (t/assert= (nth '(1 2 3) 99 :default) :default) (t/assert= (nth (make-array 3) 99 :default) :default) + (t/assert= (nth (repeat 4 1) 99 :default) :default) (t/assert= (nth (range 4) 99 :default) :default) (t/assert= (nth "hithere" 99 :default) :default) (t/assert= (nth [1 2 3] 1 :default) 2) (t/assert= (nth '(1 2 3) 1 :default) 2) (t/assert= (nth (make-array 3) 2 :default) nil) + (t/assert= (nth (repeat 4 1) 3 :default) 1) (t/assert= (nth (range 4) 1 :default) 1) (t/assert= (nth "hithere" 1 :deafult) \i)) @@ -138,6 +147,7 @@ r (range 1 6)] (t/assert= (last nil) nil) (t/assert= (last []) nil) + (t/assert= (last (repeat 3 nil)) nil) (t/assert= (last (range 0 0)) nil) (t/assert= (last v) 5) (t/assert= (last l) 5) @@ -161,6 +171,7 @@ (t/assert= (empty? (make-array 0)) true) (t/assert= (empty? {}) true) (t/assert= (empty? #{}) true) + (t/assert= (empty? (repeat '())) false) (t/assert= (empty? (range 1 5)) false) (t/assert= (empty? [1 2 3]) false) @@ -177,6 +188,7 @@ (t/assert= (not-empty? (make-array 0)) false) (t/assert= (not-empty? {}) false) (t/assert= (not-empty? #{}) false) + (t/assert= (not-empty? (repeat 0 'x)) false) (t/assert= (not-empty? (range 1 5)) true) (t/assert= (not-empty? [1 2 3]) true) @@ -399,6 +411,12 @@ (t/assert= (f ::catch-this) :found) (t/assert= (f :something-else) :not-found))) +(t/deftest test-repeat + (t/assert= (seq (repeat 3 1)) '(1 1 1)) + (t/assert= (seq (repeat 0 1)) nil) + (t/assert= (count (repeat 4096 'x)) 4096) + (t/assert= (count (repeat 0 'x)) 0)) + (t/deftest test-range (t/assert= (= (-seq (range 10)) '(0 1 2 3 4 5 6 7 8 9)) @@ -573,6 +591,9 @@ (t/assert= (satisfies? IFoo \a) false)) (t/deftest test-reduce + (t/assert= 300 (reduce + (repeat 100 3))) + (t/assert= 0 (reduce + (repeat 0 3))) + (t/assert= [9 9 9] (reduce (partial map +) (repeat 0) (repeat 3 (repeat 3 3)))) (t/assert= 5050 (reduce + (range 101))) (t/assert= 3628800 (reduce * (range 1 11))) (t/assert= 5051 (reduce + 1 (range 101)))) From ab082c93f2bc3385519c38f19992998300a86edb Mon Sep 17 00:00:00 2001 From: Joshua Greenberg Date: Fri, 28 Aug 2015 11:42:22 -0700 Subject: [PATCH 225/349] fixed (count (lazy-seq [])) incorrectly returning 1 --- pixie/vm/stdlib.py | 7 +++++-- tests/pixie/tests/test-stdlib.pxi | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index a9b9aea9..487080c6 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -258,9 +258,12 @@ def count(x): while True: _count_driver.jit_merge_point(tp=rt.type(x)) if ICounted.satisfies(rt.type(x)): - return rt._add(rt.wrap(acc), rt._count(x)) + return rt._add(rt.wrap(acc), rt._count(x)) + seq = rt.seq(x) + if seq is nil: + return rt.wrap(acc) acc += 1 - x = rt.next(rt.seq(x)) + x = rt._next(seq) @as_var("+") diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index fa6d3f16..9462bada 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -218,6 +218,28 @@ (t/assert= (empty {:a 1, :b 2, :c 3}) {}) (t/assert= (empty #{1 2 3}) #{})) +(t/deftest test-count + (t/assert= (count nil) 0) + (t/assert= (count '()) 0) + (t/assert= (count '(1 2 '(3 4))) 3) + (t/assert= (count '(nil nil nil)) 3) + (t/assert= (count (cons 1 [2 3])) 3) + (t/assert= (count (list)) 0) + (t/assert= (count (list 1 2 3)) 3) + (t/assert= (count []) 0) + (t/assert= (count [1 2 3]) 3) + (t/assert= (count {}) 0) + (t/assert= (count {:a 1, :b 2, :c 3}) 3) + (t/assert= (count (first (seq {:a 1, :b 2, :c 3}))) 2) + (t/assert= (count #{}) 0) + (t/assert= (count (conj #{1 2 3} 3)) 3) + (t/assert= (count (lazy-seq '())) 0) + (t/assert= (count (lazy-seq '(1 2 3))) 3) + (t/assert= (count (cons 1 (lazy-seq [2 3]))) 3) + (t/assert= (count (range 0 -9 -3)) 3) + (t/assert= (count "") 0) + (t/assert= (count "123") 3) + (t/assert= (count (make-array 3)) 3)) (t/deftest test-vec (let [v '(1 2 3 4 5)] From 3e589e510fc71d1ee11553529b9540287e5f407a Mon Sep 17 00:00:00 2001 From: The Gitter Badger Date: Tue, 1 Sep 2015 09:20:46 +0000 Subject: [PATCH 226/349] Added Gitter badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index eda32826..d66d94d1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ [![Build Status](https://travis-ci.org/pixie-lang/pixie.svg?branch=master)](https://travis-ci.org/pixie-lang/pixie)[![License: LGPL] (http://img.shields.io/badge/license-LGPL-green.svg)](http://img.shields.io/badge/license-LGPL-green.svg) # Pixie +[![Join the chat at https://gitter.im/pixie-lang/pixie](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/pixie-lang/pixie?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + ## Intro Pixie is a lightweight lisp suitable for both general use as well as shell scripting. The language is still in a "pre-alpha" phase and as such changes fairly quickly. From c5f3c56f357608fab3212b1279e35cc63e8eb3eb Mon Sep 17 00:00:00 2001 From: Timothy Baldridge Date: Thu, 3 Sep 2015 16:52:29 -0600 Subject: [PATCH 227/349] improvements to jit and batch mode --- pixie/stdlib.pxi | 62 ++++++++++++++++++++++++++++------------------ pixie/vm/code.py | 29 ++++++++++++++-------- pixie/vm/stdlib.py | 11 ++++++++ target.py | 8 ++++-- 4 files changed, 73 insertions(+), 37 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 398a6144..40e7a190 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -21,7 +21,6 @@ (def libm (ffi-library (str "libm." pixie.platform/so-ext))) (def atan2 (ffi-fn libm "atan2" [CDouble CDouble] CDouble)) -(def floor (ffi-fn libm "floor" [CDouble] CDouble)) (def lround (ffi-fn libm "lround" [CDouble] CInt)) @@ -872,29 +871,6 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn indexed? [v] (satisfies? IIndexed v)) (defn counted? [v] (satisfies? ICounted v)) -(defn float - {:doc "Converts a number to a float." - :since "0.1"} - [x] - (cond - (number? x) (+ x 0.0) - :else (throw - [:pixie.stdlib/ConversionException - (str "Can't convert a value of type " (type x) " to a Float")]))) - -(defn int - {:doc "Converts a number to an integer." - :since "0.1"} - [x] - (cond - (integer? x) x - (float? x) (lround (floor x)) - (ratio? x) (int (/ (float (numerator x)) (float (denominator x)))) - (char? x) (+ x 0) - :else (throw - [:pixie.stdlib/ConversionException - (throw (str "Can't convert a value of type " (type x) " to an Integer"))]))) - (defn last {:doc "Returns the last element of the collection, or nil if none." :signatures [[coll]] @@ -2286,6 +2262,44 @@ Expands to calls to `extend-type`." tps)] `(do ~@exts))) +(defprotocol IToFloat + (-float [this])) + +(defn float + {:doc "Converts a number to a float." + :since "0.1"} + [x] + (-float x)) + +(extend-type Number + IToFloat + (-float [x] (+ x 0.0))) + +(defprotocol IToInteger + (-int [x])) + +(extend-protocol IToInteger + Integer + (-int [x] x) + + Float + (-int [x] (floor x)) + + Ratio + (-int [x] + (int (/ (float (numerator x)) (float (denominator x))))) + + Character + (-int [x] + (+ x 0))) + +(defn int + {:doc "Converts a number to an integer." + :since "0.1"} + [x] + (-int x)) + + (defmacro for {:doc "A list comprehension for the bindings." :examples [["(for [x [1 2 3]] x)" nil [1 2 3]] diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 573273c1..920c3dd9 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -91,7 +91,7 @@ def slice_from_start(from_list, count, extra=r_uint(0)): class BaseCode(object.Object): - _immutable_fields_ = ["_meta"] + _immutable_fields_ = ["_meta", "_name"] def __init__(self): assert isinstance(self, BaseCode) self._name = u"unknown" @@ -215,7 +215,7 @@ def invoke_with(self, args, this_fn): class Code(BaseCode): """Interpreted code block. Contains consts and """ _type = object.Type(u"pixie.stdlib.Code") - _immutable_fields_ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta"] + _immutable_fields_ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta", "_debug_points"] def type(self): return Code._type @@ -411,22 +411,22 @@ def set_var_value(self, var, val): class Var(BaseCode): _type = object.Type(u"pixie.stdlib.Var") - _immutable_fields_ = ["_rev?"] + _immutable_fields_ = ["_ns_ref"] def type(self): return Var._type - def __init__(self, ns, name): + def __init__(self, ns_ref, ns, name): BaseCode.__init__(self) + self._ns_ref = ns_ref self._ns = ns self._name = name - self._rev = 0 self._root = undefined self._dynamic = False def set_root(self, o): affirm(o is not None, u"Invalid var set") - self._rev += 1 + self._ns_ref._rev += 1 self._root = o return self @@ -437,7 +437,7 @@ def set_value(self, val): def set_dynamic(self): self._dynamic = True - self._rev += 1 + self._ns_ref._rev += 1 def get_dynamic_value(self): @@ -450,12 +450,16 @@ def _is_dynamic(self, rev): return self._dynamic def is_dynamic(self): - return self._is_dynamic(self._rev) + return self._is_dynamic(self.ns_ref()._rev) @elidable_promote() def get_root(self, rev): return self._root + @elidable_promote() + def ns_ref(self): + return self._ns_ref + def deref(self): if self.is_dynamic(): if we_are_translated(): @@ -465,9 +469,9 @@ def deref(self): if globals().has_key("_dynamic_vars"): return self.get_dynamic_value() else: - return self.get_root(self._rev) + return self.get_root(self.ns_ref()._rev) else: - val = self.get_root(self._rev) + val = self.get_root(self.ns_ref()._rev) affirm(val is not undefined, u"Var " + self._name + u" is undefined") return val @@ -503,10 +507,13 @@ def __init__(self, ns, refer_syms=[], refer_all=False): class Namespace(object.Object): _type = object.Type(u"pixie.stdlib.Namespace") + _immutable_fields_ = ["_rev?"] + def type(self): return Namespace._type def __init__(self, name): + self._rev = 0 self._registry = {} self._name = name self._refers = {} @@ -516,7 +523,7 @@ def intern_or_make(self, name): affirm(isinstance(name, unicode), u"Var names must be unicode") v = self._registry.get(name, None) if v is None: - v = Var(self._name, name) + v = Var(self, self._name, name) self._registry[name] = v return v diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 487080c6..45287c85 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -427,6 +427,10 @@ def _load_file(filename, compile=False): affirm(isinstance(filename, String), u"filename must be a string") filename = str(rt.name(filename)) + if filename.endswith(".pxic"): + load_pxic_file(filename) + return nil + if path.isfile(filename + "c") and not compile: load_pxic_file(filename + "c") return nil @@ -932,3 +936,10 @@ def _add_exception_info(ex, str, data): def _run_finalizers(): finalizer_registry.run_finalizers() return nil + + +@as_var("floor") +def _floor(x): + affirm(isinstance(x, numbers.Float), u"floor expects a Float") + return numbers.Integer(int(x.float_val())) + diff --git a/target.py b/target.py index c5c3fed8..7eb8932c 100644 --- a/target.py +++ b/target.py @@ -39,7 +39,7 @@ def jitpolicy(driver): LOAD_PATHS = intern_var(u"pixie.stdlib", u"load-paths") LOAD_PATHS.set_root(nil) -load_path = Var(u"pixie.stdlib", u"internal-load-path") +load_path = intern_var(u"pixie.stdlib", u"internal-load-path") class ReplFn(NativeFn): def __init__(self, args): @@ -54,6 +54,8 @@ def inner_invoke(self, args): with with_ns(u"user"): repl.invoke([]) +load_file = intern_var(u"pixie.stdlib", u"load-file") + class BatchModeFn(NativeFn): def __init__(self, args): self._file = args[0] @@ -81,7 +83,9 @@ def inner_invoke(self, args): if not path.isfile(self._file): print "Error: Cannot open '" + self._file + "'" os._exit(1) - f = open(self._file) + load_file.invoke([rt.wrap(self._file)]) + return None + data = f.read() f.close() From ee883e52b0af421170272274a4cc141841883ec6 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 6 Sep 2015 13:19:00 -0400 Subject: [PATCH 228/349] reset! returns new value --- pixie/vm/atom.py | 2 +- tests/pixie/tests/test-stdlib.pxi | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/pixie/vm/atom.py b/pixie/vm/atom.py index d372e920..ae42ab2d 100644 --- a/pixie/vm/atom.py +++ b/pixie/vm/atom.py @@ -18,7 +18,7 @@ def __init__(self, boxed_value): def _reset(self, v): assert isinstance(self, Atom) self._boxed_value = v - return self + return v @extend(proto._deref, Atom) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index b8147548..61896a88 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -623,3 +623,9 @@ (t/deftest test-comp (t/assert= 5 ((comp inc inc inc inc) 1)) (t/assert= :xyz ((comp) :xyz))) + +(t/deftest test-swap-reset + (let [a (atom 0)] + (t/assert= 1 (swap! a inc)) + (t/assert= 2 (swap! a inc)) + (t/assert= 3 (reset! a 3)))) From 475a73a9990a1055a8e079427158af8e145b7dab Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 10 Sep 2015 21:40:59 +0100 Subject: [PATCH 229/349] take transducer --- pixie/stdlib.pxi | 20 ++++++++++++++++---- tests/pixie/tests/test-stdlib.pxi | 10 ++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 398a6144..af9b40c0 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1569,10 +1569,22 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn take {:doc "Takes n elements from the collection, or fewer, if not enough." :added "0.1"} - [n coll] - (when (pos? n) - (when-let [s (seq coll)] - (cons (first s) (take (dec n) (next s)))))) + ([n] + (fn [rf] + (let [seen (atom 0)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (let [s (swap! seen inc)] + (if (<= s n) + (rf result input) + result))))))) + ([n coll] + (lazy-seq + (when (pos? n) + (when-let [s (seq coll)] + (cons (first s) (take (dec n) (next s)))))))) (defn drop {:doc "Drops n elements from the start of the collection." diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 61896a88..7cc23a84 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -493,6 +493,16 @@ a (recur (inc a)))))) +(t/deftest test-take + (t/assert= (take 0 [1 2 3 4]) ()) + (t/assert= (take 1 [1 2 3 4]) [1]) + (t/assert= (take 2 [1 2 3 4]) [1 2]) + (t/assert= (take 3 [1 2 3 4]) [1 2 3]) + (t/assert= (transduce (take 0) conj [1 2 3 4]) []) + (t/assert= (transduce (take 1) conj [1 2 3 4]) [1]) + (t/assert= (transduce (take 2) conj [1 2 3 4]) [1 2]) + (t/assert= (transduce (take 3) conj [1 2 3 4]) [1 2 3])) + (t/deftest test-take-while (t/assert= (take-while pos? [1 2 3 -1]) [1 2 3]) (t/assert= (take-while pos? [-1 2]) ()) From 83f0860dfacf99347c08bacc96a5e867aaf74a69 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 10 Sep 2015 22:31:18 +0100 Subject: [PATCH 230/349] add drop transducer --- pixie/stdlib.pxi | 32 ++++++++++++++++++++++--------- tests/pixie/tests/test-stdlib.pxi | 10 ++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index af9b40c0..1ea331f7 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1571,15 +1571,16 @@ The new value is thus `(apply f current-value-of-atom args)`." :added "0.1"} ([n] (fn [rf] - (let [seen (atom 0)] + (let [rrf (preserving-reduced rf) + seen (atom 0)] (fn ([] (rf)) ([result] (rf result)) ([result input] (let [s (swap! seen inc)] - (if (<= s n) - (rf result input) - result))))))) + (if (<= s n) + (rrf result input) + (reduced result)))))))) ([n coll] (lazy-seq (when (pos? n) @@ -1589,11 +1590,24 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn drop {:doc "Drops n elements from the start of the collection." :added "0.1"} - [n coll] - (let [s (seq coll)] - (if (and (pos? n) s) - (recur (dec n) (next s)) - s))) + ([n] + (fn [rf] + (let [rrf (preserving-reduced rf) + seen (atom 0)] + (fn + ([] (rf)) + ([result] + (rf result)) + ([result input] + (let [s (swap! seen inc)] + (if (> s n) + (rrf result input) + result))))))) + ([n coll] + (let [s (seq coll)] + (if (and (pos? n) s) + (recur (dec n) (next s)) + s)))) (defn split-at {:doc "Returns a vector of the first n elements of the collection, and the remaining elements." diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 7cc23a84..d60f4e66 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -503,6 +503,16 @@ (t/assert= (transduce (take 2) conj [1 2 3 4]) [1 2]) (t/assert= (transduce (take 3) conj [1 2 3 4]) [1 2 3])) +(t/deftest test-drop + (t/assert= (drop 0 [1 2 3 4]) [1 2 3 4]) + (t/assert= (drop 1 [1 2 3 4]) [2 3 4]) + (t/assert= (drop 2 [1 2 3 4]) [3 4]) + (t/assert= (drop 3 [1 2 3 4]) [4]) + (t/assert= (transduce (drop 0) conj [1 2 3 4]) [1 2 3 4]) + (t/assert= (transduce (drop 1) conj [1 2 3 4]) [2 3 4]) + (t/assert= (transduce (drop 2) conj [1 2 3 4]) [3 4]) + (t/assert= (transduce (drop 3) conj [1 2 3 4]) [4])) + (t/deftest test-take-while (t/assert= (take-while pos? [1 2 3 -1]) [1 2 3]) (t/assert= (take-while pos? [-1 2]) ()) From 5a88bc4c53dc133c3af140cff76f48a6cf2bc8e8 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Wed, 16 Sep 2015 09:34:56 -0400 Subject: [PATCH 231/349] fn pre and post conditions --- pixie/stdlib.pxi | 19 ++++++++++++++++++- tests/pixie/tests/test-stdlib.pxi | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1ea331f7..8e199705 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2144,7 +2144,24 @@ The params can be destructuring bindings, see `(doc let)` for details."} (recur (inc i) bindings) (recur (inc i) (reduce conj bindings [(nth argv i) (nth names i)]))) bindings)) - body (next decl)] + body (next decl) + conds (when (and (next body) (map? (first body))) + (first body)) + pre (:pre conds) + post (:post conds) + body (if conds (next body) body) + body (if post + `((let [~'% ~(if (> (count body) 1) + `(do ~@body) + (first body))] + ~@(map (fn* [c] `(assert ~c)) post) + ~'%)) + body) + body (if pre + (seq (concat + (map (fn* [c] `(assert ~c)) pre) + body)) + body)] (if (every? symbol? argv) `(~argv ~@body) `(~names diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index d60f4e66..bf5faac8 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -649,3 +649,18 @@ (t/assert= 1 (swap! a inc)) (t/assert= 2 (swap! a inc)) (t/assert= 3 (reset! a 3)))) + +(t/deftest pre-post-conds + (let [f (fn ([a] {:pre [(even? a)] :post [(= % 6)]} (/ a 2)) + ([a b] {:pre [(= (+ 1 a) b)] :post [(odd? %)]} (+ a b)))] + (= 6 (f 12)) + (t/assert-throws? RuntimeException + "Assert failed" + (f 13)) + (t/assert-throws? RuntimeException + "Assert failed" + (f 14)) + (= 15 (f 7 8)) + (t/assert-throws? RuntimeException + "Assert failed" + (f 1 1)))) From 0a95ba6f385f7b70329275c1b96b7c3b44933e49 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Fri, 18 Sep 2015 10:54:43 -0400 Subject: [PATCH 232/349] pre & post assert msgs --- pixie/stdlib.pxi | 4 ++-- tests/pixie/tests/test-stdlib.pxi | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 8e199705..1d202472 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2154,12 +2154,12 @@ The params can be destructuring bindings, see `(doc let)` for details."} `((let [~'% ~(if (> (count body) 1) `(do ~@body) (first body))] - ~@(map (fn* [c] `(assert ~c)) post) + ~@(map (fn* [c] `(assert ~c (str '~c))) post) ~'%)) body) body (if pre (seq (concat - (map (fn* [c] `(assert ~c)) pre) + (map (fn* [c] `(assert ~c (str '~c))) pre) body)) body)] (if (every? symbol? argv) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index bf5faac8..0b99ce67 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -653,14 +653,14 @@ (t/deftest pre-post-conds (let [f (fn ([a] {:pre [(even? a)] :post [(= % 6)]} (/ a 2)) ([a b] {:pre [(= (+ 1 a) b)] :post [(odd? %)]} (+ a b)))] - (= 6 (f 12)) + (t/assert= 6 (f 12)) (t/assert-throws? RuntimeException - "Assert failed" + "Assert failed: (even? a)" (f 13)) (t/assert-throws? RuntimeException - "Assert failed" + "Assert failed: (= % 6)" (f 14)) - (= 15 (f 7 8)) + (t/assert= 15 (f 7 8)) (t/assert-throws? RuntimeException - "Assert failed" + "Assert failed: (= (+ 1 a) b)" (f 1 1)))) From b5c2796615add7d20d963ef11cb0b3ae3806819f Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 15 Sep 2015 19:43:59 +0100 Subject: [PATCH 233/349] wip --- benchmarks/read-line.pxi | 22 ++++++----- pixie/io.pxi | 82 ++++++++++++++++++++++++---------------- 2 files changed, 63 insertions(+), 41 deletions(-) diff --git a/benchmarks/read-line.pxi b/benchmarks/read-line.pxi index f09e687a..441ccaeb 100644 --- a/benchmarks/read-line.pxi +++ b/benchmarks/read-line.pxi @@ -1,18 +1,22 @@ (ns benchmarks.readline (:require [pixie.time :as time] - [pixie.io :as io])) + [pixie.io :as io] + [pixie.streams.utf8 :as utf8])) (def file-name "/usr/share/dict/words") -(println "testing unbuffered") +(println "Lazy line-seq") (time/time (-> file-name (io/open-read) (io/line-seq) - (count))) + (count) + (println))) -(println "testing buffered") -(time/time (-> file-name - (io/open-read) - (io/buffered-input-stream) - (io/line-seq) - (count))) +(println "Reducing line-reader") +(time/time + (-> file-name + (io/open-read) + (io/line-reader) + (into []) + (count) + (println))) diff --git a/pixie/io.pxi b/pixie/io.pxi index c07ca1a4..a3160405 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -47,55 +47,64 @@ (assert (string? filename) "Filename must be a string") (->FileStream (fs_open filename uv/O_RDONLY 0) 0 (uv/uv_buf_t))) -(defn buffered-read-line - [input-stream] - (let [line-feed (into #{} (map int [\newline \return]))] - (loop [acc []] - (let [ch (read-byte input-stream)] - (cond - (nil? ch) nil - (zero? ch) nil +(defprotocol ILineReader + (-read-line [this])) - (and (pos? ch) (not (line-feed ch))) - (recur (conj acc ch)) +(def line-feed? #{\newline \return}) - :else (transduce (map char) string-builder acc)))))) +(deftype LineReader + [buffered-input-stream] + ILineReader + (-read-line [this] + (loop [string (string-builder)] + (if-let [i (read-byte buffered-input-stream)] + (let [ch (char i)] + (if-not (line-feed? ch) + (recur (conj! string ch)) + (str string)))))) + IReduce + (-reduce [this f init] + (let [rrf (preserving-reduced f)] + (loop [acc init] + (if-let [line (-read-line this)] + (let [result (rrf acc line)] + (if (not (reduced? result)) + (recur result) + @result)) + acc))))) -(defn unbuffered-read-line +(defn line-reader [input-stream] - (let [line-feed (into #{} (map int [\newline \return])) - buf (buffer 1)] - (loop [acc []] - (let [len (read input-stream buf 1)] - (cond - (and (pos? len) (not (line-feed (first buf)))) - (recur (conj acc (first buf))) + (cond + (satisfies? ILineReader input-stream) + input-stream - (and (zero? len) (empty? acc)) nil + (instance? BufferedInputStream input-stream) + (-> input-stream + (->LineReader)) - :else (transduce (map char) string-builder acc)))))) + (satisfies? IInputStream input-stream) + (-> input-stream + (buffered-input-stream) + (->LineReader)) + + :else + (throw [::Exception "Expected a LineReader, an IInputStream or BufferedInputStream"]))) (defn read-line "Read one line from input-stream for each invocation. nil when all lines have been read. Pass a BufferedInputStream for best performance." [input-stream] - (cond - (instance? BufferedInputStream input-stream) - (buffered-read-line input-stream) - - (satisfies? IInputStream input-stream) - (unbuffered-read-line input-stream) - - :else - (throw [::Exception "Expected an IInputStream or BufferedInputStream"]))) + (-read-line (line-reader input-stream))) (defn line-seq "Returns the lines of text from input-stream as a lazy sequence of strings. input-stream must implement IInputStream" [input-stream] - (when-let [line (read-line input-stream)] - (cons line (lazy-seq (line-seq input-stream))))) + (let [lr (line-reader input-stream)] + (when-let [line (-read-line lr)] + (cons line (lazy-seq (line-seq lr)))))) (deftype FileOutputStream [fp offset uvbuf] IOutputStream @@ -136,6 +145,15 @@ (flush downstream)))) (deftype BufferedInputStream [upstream idx buffer] + IReduce + (-reduce [this f init] + (loop [acc init] + (if-let [next-byte (read-byte this)] + (let [step (f acc next-byte)] + (if (reduced? step) + @step + (recur step))) + acc))) IByteInputStream (read-byte [this] (when (= idx (count buffer)) From 118e36a7556e9798347902813796879a414ff4a8 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Sun, 20 Sep 2015 16:04:36 -0400 Subject: [PATCH 234/349] doto macro --- pixie/stdlib.pxi | 11 +++++++++++ tests/pixie/tests/test-stdlib.pxi | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1ea331f7..4eee557e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2337,6 +2337,17 @@ Expands to calls to `extend-type`." [~@body])))] `(or (seq ~(gen-loop [] bindings)) '()))) +(defmacro doto + {:doc "Evaluate o, uses the value as the first argument in each form. Returns o"} + [o & forms] + (let [s (gensym o)] + `(let [~s ~o] + ~@(for [f forms] + (if (seq? f) + `(~(first f) ~s ~@(rest f)) + `(~f ~s))) + ~s))) + (defn reverse ; TODO: We should probably have a protocol IReversible, so we can e.g. ; reverse vectors efficiently, etc.. diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index d60f4e66..943a9d1e 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -399,6 +399,11 @@ [2 :a] [2 :b] [2 :c] [3 :a] [3 :b] [3 :c]])) +(t/deftest test-doto + (let [a (atom 0)] + (t/assert= a (doto a (swap! + 3) (swap! str))) + (t/assert= @a "3"))) + (t/deftest test-into (t/assert= [1 3] (into [] (comp (map inc) (filter odd?)) (range 3))) (t/assert= {:a 1 :b 2} (into {} [[:a 1] [:b 2]]))) From 880331c2575417fa151b2ca3d08aaa47a2b1212e Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 23 Sep 2015 20:25:34 +0100 Subject: [PATCH 235/349] fix first on Seqables --- pixie/stdlib.pxi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1ea331f7..c24e6db7 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -686,7 +686,9 @@ returns true" [coll] (if (satisfies? IIndexed coll) (nth coll 0 nil) - (-first coll))) + (if (satisfies? ISeq coll) + (-first coll) + (-first (seq coll))))) (defn second {:doc "Returns the second item in coll, if coll implements IIndexed nth will be used to retrieve From c927e8d0cb3125e1d02c5686f67ae7d317b71b69 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 23 Sep 2015 20:27:41 +0100 Subject: [PATCH 236/349] enable tests --- tests/pixie/tests/test-stdlib.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index d60f4e66..0e0ec67c 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -130,8 +130,8 @@ (t/assert= (first []) nil) (t/assert= (first '()) nil) (t/assert= (first (make-array 0)) nil) - (comment (t/assert= (first {}) nil)) - (comment (t/assert= (first #{}) nil)) + (t/assert= (first {}) nil) + (t/assert= (first #{}) nil) (t/assert= (first [1 2 3]) 1) (t/assert= (first '(1 2 3)) 1) From ae3bb32ab993ab23bbfa5b847aad73e8899771ec Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Wed, 23 Sep 2015 17:01:02 -0400 Subject: [PATCH 237/349] readline/add_history --- pixie/repl.pxi | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pixie/repl.pxi b/pixie/repl.pxi index 639035db..6b21c862 100644 --- a/pixie/repl.pxi +++ b/pixie/repl.pxi @@ -5,7 +5,8 @@ (f/with-config {:library "edit" :includes ["editline/readline.h"]} - (f/defcfn readline)) + (f/defcfn readline) + (f/defcfn add_history)) (defn repl [] @@ -15,7 +16,9 @@ "") line (st/apply-blocking readline prompt)] (if line - (str line "\n") + (do + (add_history line) + (str line "\n")) ""))))] (loop [] (try (let [form (read rdr false)] From c0ac40c28b720a424e6c84bf496073e6fe9cc770 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Wed, 23 Sep 2015 22:10:37 +0100 Subject: [PATCH 238/349] alt solution --- pixie/stdlib.pxi | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index c24e6db7..f32b6b25 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -686,9 +686,7 @@ returns true" [coll] (if (satisfies? IIndexed coll) (nth coll 0 nil) - (if (satisfies? ISeq coll) - (-first coll) - (-first (seq coll))))) + (-first coll))) (defn second {:doc "Returns the second item in coll, if coll implements IIndexed nth will be used to retrieve @@ -2595,6 +2593,11 @@ Calling this function on something that is not ISeqable returns a seq with that 0 (compare-counted (str x) (str y)))) +(extend-protocol ISeq + ISeqable + (-first [coll] (-first (seq coll))) + (-next [coll] (-next (seq coll)))) + (extend-protocol IComparable Number (-compare [x y] From 4adcc1a1347733380df0cad931ca945af70026df Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 24 Sep 2015 09:58:33 +0100 Subject: [PATCH 239/349] add non empty tests and sort MapEntry equality --- pixie/stdlib.pxi | 5 +++++ tests/pixie/tests/test-stdlib.pxi | 3 +++ 2 files changed, 8 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index f32b6b25..41f16056 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -940,6 +940,11 @@ If further arguments are passed, invokes the method named by symbol, passing the (cond (= idx 0) (-key self) (= idx 1) (-val self) :else not-found))) +(extend -eq MapEntry (fn [self other] + (and (= (-key self) + (-key other)) + (= (-val self) + (-val other))))) (extend -reduce MapEntry indexed-reduce) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 0e0ec67c..6eed1535 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -133,6 +133,9 @@ (t/assert= (first {}) nil) (t/assert= (first #{}) nil) + (t/assert= (first {:a 1}) (map-entry :a 1)) + (t/assert= (first #{:a}) :a) + (t/assert= (first [1 2 3]) 1) (t/assert= (first '(1 2 3)) 1) (let [a (make-array 3)] From 43345421b5633d44d4aad44005ad3f57fad14b15 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 20 Sep 2015 13:58:39 +0100 Subject: [PATCH 240/349] Improves line-seq and read-line performance Introduces a LineReader which is reducable and speeds up UTF8 decoding --- benchmarks/read-line.pxi | 42 ++++++++++++++++++++++++++--------- pixie/io.pxi | 40 ++++++++++++++++----------------- pixie/stdlib.pxi | 13 ++++++----- pixie/streams/utf8.pxi | 39 +++++++++++++++----------------- tests/pixie/tests/test-io.pxi | 6 ++--- 5 files changed, 79 insertions(+), 61 deletions(-) diff --git a/benchmarks/read-line.pxi b/benchmarks/read-line.pxi index 441ccaeb..c252fd09 100644 --- a/benchmarks/read-line.pxi +++ b/benchmarks/read-line.pxi @@ -6,17 +6,37 @@ (def file-name "/usr/share/dict/words") (println "Lazy line-seq") -(time/time (-> file-name - (io/open-read) - (io/line-seq) - (count) - (println))) +(time/time + (->> file-name + (io/open-read) + (io/buffered-input-stream) + (io/line-seq) + (count))) (println "Reducing line-reader") (time/time - (-> file-name - (io/open-read) - (io/line-reader) - (into []) - (count) - (println))) + (->> file-name + (io/open-read) + (io/buffered-input-stream) + (io/line-reader) + (into []) + (count))) + +(println "Lazy UTF8 line-seq") +(time/time + (->> file-name + (io/open-read) + (io/buffered-input-stream) + (utf8/utf8-input-stream) + (io/line-seq) + (count))) + +(println "Reducing UTF8 line-reader") +(time/time + (->> file-name + (io/open-read) + (io/buffered-input-stream) + (utf8/utf8-input-stream) + (io/line-reader) + (into []) + (count))) diff --git a/pixie/io.pxi b/pixie/io.pxi index a3160405..4143386e 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -53,12 +53,14 @@ (def line-feed? #{\newline \return}) (deftype LineReader - [buffered-input-stream] + [input-stream] ILineReader (-read-line [this] - (loop [string (string-builder)] - (if-let [i (read-byte buffered-input-stream)] - (let [ch (char i)] + (let [read-fn (if (satisfies? utf8/IUTF8InputStream input-stream) + utf8/read-char + (fn [stream] (when-let [i (read-byte stream)] (char i))))] + (loop [string (string-builder)] + (if-let [ch (read-fn input-stream)] (if-not (line-feed? ch) (recur (conj! string ch)) (str string)))))) @@ -79,17 +81,14 @@ (satisfies? ILineReader input-stream) input-stream + (satisfies? utf8/IUTF8InputStream input-stream) + (-> input-stream ->LineReader) + (instance? BufferedInputStream input-stream) - (-> input-stream - (->LineReader)) + (-> input-stream ->LineReader) - (satisfies? IInputStream input-stream) - (-> input-stream - (buffered-input-stream) - (->LineReader)) - :else - (throw [::Exception "Expected a LineReader, an IInputStream or BufferedInputStream"]))) + (throw [::Exception "Expected a LineReader, UTF8InputStream, or BufferedInputStream"]))) (defn read-line "Read one line from input-stream for each invocation. @@ -147,13 +146,14 @@ (deftype BufferedInputStream [upstream idx buffer] IReduce (-reduce [this f init] - (loop [acc init] - (if-let [next-byte (read-byte this)] - (let [step (f acc next-byte)] - (if (reduced? step) - @step - (recur step))) - acc))) + (let [rrf (preserving-reduced f)] + (loop [acc init] + (if-let [next-byte (read-byte this)] + (let [step (rrf acc next-byte)] + (if (reduced? step) + @step + (recur step))) + acc)))) IByteInputStream (read-byte [this] (when (= idx (count buffer)) @@ -248,7 +248,7 @@ (satisfies? IInputStream input) input :else (throw [:pixie.io/Exception "Expected a string or an IInputStream"])) result (transduce - (map char) + (map identity) string-builder (-> stream buffered-input-stream diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 1ea331f7..a99b1059 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1633,13 +1633,14 @@ The new value is thus `(apply f current-value-of-atom args)`." :added "0.1"} ([pred] (fn [rf] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] + (let [rrf (preserving-reduced rf)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] (if (pred input) - (rf result input) - (reduced result)))))) + (rrf result input) + (reduced result))))))) ([pred coll] (lazy-seq (when-let [s (seq coll)] diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi index e5605e18..8e8ab95f 100644 --- a/pixie/streams/utf8.pxi +++ b/pixie/streams/utf8.pxi @@ -27,30 +27,27 @@ (-dispose! [this] (dispose! out))) - (deftype UTF8InputStream [in bad-char] IUTF8InputStream (read-char [this] (when-let [byte (read-byte in)] - (let [ch (int byte) - [n bytes error?] (cond - (>= 0x7F ch) [ch 1] - (= 0xC0 (bit-and ch 0xE0)) [(bit-and ch 31) 2 false] - (= 0xE0 (bit-and ch 0xF0)) [(bit-and ch 15) 3 false] - (= 0xF0 (bit-and ch 0xF8)) [(bit-and ch 7) 4 false] - (= 0xF8 (bit-and ch 0xF8)) [(bit-and ch 3) 5 true] - (= 0xFC (bit-and ch 0xFE)) [(bit-and ch 1) 6 true] - :else [n 1 true])] - (loop [i (dec bytes) - n n] - (if (pos? i) - (recur (dec i) - (bit-or (bit-shift-left n 6) - (bit-and (read-byte in) 0x3F))) - (if error? - (if bad-char - bad-char - (throw [::invalid-character (str "Invalid UTF8 character decoded: " n)])) + (let [[n bytes error?] + (cond + (>= 0x7F byte) [byte 1 false] + (= 0xC0 (bit-and byte 0xE0)) [(bit-and byte 31) 2 false] + (= 0xE0 (bit-and byte 0xF0)) [(bit-and byte 15) 3 false] + (= 0xF0 (bit-and byte 0xF8)) [(bit-and byte 7) 4 false] + (= 0xF8 (bit-and byte 0xF8)) [(bit-and byte 3) 5 true] + (= 0xFC (bit-and byte 0xFE)) [(bit-and byte 1) 6 true] + :else [n 1 true])] + (if error? + (or bad-char + (throw [::invalid-character (str "Invalid UTF8 character decoded: " n)])) + (loop [i (dec bytes) n n] + (if (pos? i) + (recur (dec i) + (bit-or (bit-shift-left n 6) + (bit-and (read-byte in) 0x3F))) (char n))))))) IDisposable (-dispose! [this] @@ -60,7 +57,7 @@ (let [rrf (preserving-reduced f)] (loop [acc init] (if-let [char (read-char this)] - (let [result (rrf acc (int char))] + (let [result (rrf acc char)] (if (not (reduced? result)) (recur result) @result)) diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 663bf52b..1d41c4a5 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -33,18 +33,18 @@ (t/assert-throws? (io/read f buf -2))))) (t/deftest test-read-line - (let [f (io/open-read "tests/pixie/tests/test-io.txt")] + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt"))] (io/read-line f) (t/assert= (io/read-line f) "Second line.") (t/assert= (io/read-line f) nil))) (t/deftest test-line-seq - (let [f (io/open-read "tests/pixie/tests/test-io.txt") + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt")) s (io/line-seq f)] (t/assert= (last s) "Second line."))) (t/deftest test-seek - (let [f (io/open-read "tests/pixie/tests/test-io.txt")] + (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt"))] (io/read-line f) (t/assert= (io/read-line f) "Second line.") (io/rewind f) From 4f38016810399870e7ba9a6721b61ee44c30ec7b Mon Sep 17 00:00:00 2001 From: Brandon Adams Date: Fri, 25 Sep 2015 01:13:34 -0500 Subject: [PATCH 241/349] Let LazySeq conj --- pixie/stdlib.pxi | 12 ++++++++---- tests/pixie/tests/test-stdlib.pxi | 3 +++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 216c4a12..6e40bf01 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1049,6 +1049,10 @@ If further arguments are passed, invokes the method named by symbol, passing the (fn [coll x] (cons x coll))) +(extend -conj LazySeq + (fn [coll x] + (cons x coll))) + (defn empty {:doc "Returns an empty collection of the same type, or nil." :added "0.1"} @@ -1601,7 +1605,7 @@ The new value is thus `(apply f current-value-of-atom args)`." seen (atom 0)] (fn ([] (rf)) - ([result] + ([result] (rf result)) ([result input] (let [s (swap! seen inc)] @@ -2611,7 +2615,7 @@ Calling this function on something that is not ISeqable returns a seq with that (let [min-length (min (count x) (count y))] (loop [n 0] (if (not= min-length n) - (let [diff (-compare (nth x n) + (let [diff (-compare (nth x n) (nth y n))] (if-not (zero? diff) diff @@ -2644,7 +2648,7 @@ Calling this function on something that is not ISeqable returns a seq with that (if (char? y) (compare-numbers (int x) (int y)) (throw [::ComparisonError (str "Cannot compare: " x " to " y)]))) - + PersistentVector (-compare [x y] (if (vector? y) @@ -2677,7 +2681,7 @@ Calling this function on something that is not ISeqable returns a seq with that (and (true? x) (false? y)) 1 :else -1)) (throw [::ComparisonError (str "Cannot compare: " x " to " y)])) - + Nil (-compare [x y] (if (nil? y) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index aa8547c8..a4cb9c38 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -672,3 +672,6 @@ (t/assert-throws? RuntimeException "Assert failed: (= (+ 1 a) b)" (f 1 1)))) + +(t/deftest test-lazyseq-conj + (t/assert= '(1 2 3) (conj (lazy-seq '(2 3)) 1))) From 9990b235a186454e36171f84c78a0ebfb18ee5d1 Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Tue, 29 Sep 2015 11:27:01 -0400 Subject: [PATCH 242/349] Mandelbrot demo from Strange Loop talk --- examples/mandelbrot.pxi | 101 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 examples/mandelbrot.pxi diff --git a/examples/mandelbrot.pxi b/examples/mandelbrot.pxi new file mode 100644 index 00000000..4258280d --- /dev/null +++ b/examples/mandelbrot.pxi @@ -0,0 +1,101 @@ +;; Mandelbrot demo from Timothy Baldridge's 2015 Strange Loop talk +;; https://www.youtube.com/watch?v=1AjhFZVfB9c + + +(ns mandelbrot + (:require [pixie.ffi-infer :refer :all] + [pixie.ffi :as ffi] + [pixie.time :refer [time]])) + +(with-config {:library "SDL2" + :cxx-flags ["`sdl2-config --cflags`"] + :includes ["SDL.h"]} + + (defcfn SDL_Init) + + (defconst SDL_INIT_VIDEO) + (defconst SDL_WINDOWPOS_UNDEFINED) + (defcfn SDL_CreateWindow) + (defcfn SDL_CreateRenderer) + (defcfn SDL_CreateTexture) + (defconst SDL_PIXELFORMAT_RGBA8888) + (defconst SDL_TEXTUREACCESS_STREAMING) + (defcfn SDL_UpdateTexture) + (defcfn SDL_RenderClear) + (defcfn SDL_RenderCopy) + + (defconst SDL_WINDOW_SHOWN) + (defcfn SDL_RenderPresent) + (defcfn SDL_LockSurface)) + +(println "starting") +(def WIDTH 1024) +(def HEIGHT 512) + +(assert (>= (SDL_Init SDL_INIT_VIDEO) 0)) + +(def WINDOW (SDL_CreateWindow "Pixie MandelBrot" + SDL_WINDOWPOS_UNDEFINED + SDL_WINDOWPOS_UNDEFINED + WIDTH + HEIGHT + SDL_WINDOW_SHOWN)) + +(assert WINDOW "Could not create window") + +(def RENDERER (SDL_CreateRenderer WINDOW -1 0)) + +(def DRAW_SURFACE (SDL_CreateTexture RENDERER + SDL_PIXELFORMAT_RGBA8888 + SDL_TEXTUREACCESS_STREAMING + WIDTH + HEIGHT)) + +(defn bit-or [& args] + (reduce pixie.stdlib/bit-or 0 args)) + +(defn put-pixel [ptr x y r g b] + (let [loc (* 4 (+(* y WIDTH) x))] + (ffi/pack! ptr loc CUInt32 (bit-or (bit-shift-left r 24) + (bit-shift-left g 16) + (bit-shift-left b 8) + 255)))) + +(def BUFFER (buffer (* 4 WIDTH HEIGHT))) + +(defn mandel-point [x y width height max_iterations] + (let [x0 (float (- (* (/ x width) 3.5) 2.5)) + y0 (float (- (* (/ y height) 2) 1))] + (loop [x 0.0 + y 0.0 + iteration 0] + (let [xsq (* x x) + ysq (* y y)] + (if (and (< (+ xsq + ysq) + (* 2 2)) + (< iteration max_iterations)) + (let [xtemp (+ (- xsq + ysq) + x0) + y (+ (* 2 x y) y0)] + (recur xtemp y (inc iteration))) + (- 1 (/ iteration max_iterations))))))) + +(dotimes [x 3] + (time + (let [max (* WIDTH HEIGHT)] + (dotimes [y HEIGHT] + (dotimes [x WIDTH] + (let [result (mandel-point (float x) (float y) (float WIDTH) (float HEIGHT) 1000) + color (int (* 16777216 result))] + (put-pixel BUFFER x y + (bit-shift-right color 16) + (bit-and (bit-shift-right color 8) 0xff) + (bit-and color 0xff)))))))) + +(SDL_UpdateTexture DRAW_SURFACE nil BUFFER (* 4 WIDTH)) +(SDL_RenderCopy RENDERER DRAW_SURFACE nil nil) +(SDL_RenderPresent RENDERER) + +(pixie.stacklets/sleep 10000) From 8d89628e029f2809c2ea55c93bcb3065a4dcc285 Mon Sep 17 00:00:00 2001 From: Brandon Adams Date: Thu, 24 Sep 2015 08:17:04 -0500 Subject: [PATCH 243/349] Added map-entry? predicate --- pixie/stdlib.pxi | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index f019e838..6720693c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -871,6 +871,8 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn indexed? [v] (satisfies? IIndexed v)) (defn counted? [v] (satisfies? ICounted v)) +(defn map-entry? [v] (satisfies? IMapEntry v)) + (defn last {:doc "Returns the last element of the collection, or nil if none." :signatures [[coll]] @@ -2320,7 +2322,7 @@ Expands to calls to `extend-type`." (defn float {:doc "Converts a number to a float." - :since "0.1"} + :since "0.1"} [x] (-float x)) @@ -2348,7 +2350,7 @@ Expands to calls to `extend-type`." (defn int {:doc "Converts a number to an integer." - :since "0.1"} + :since "0.1"} [x] (-int x)) From ad286c674817f58841753518fbbb0a8a383945bd Mon Sep 17 00:00:00 2001 From: Brandon Adams Date: Thu, 24 Sep 2015 08:19:20 -0500 Subject: [PATCH 244/349] Extend map-entry's -eq to vectors, add -seq for MapEntry This enables (= (map-entry :a 1) [:a 1]) and the reverse (= [:a 1] (map-entry :a 1)). Tests are included. MapEntry falls back to seq equality if not compared to another MapEntry or Vector --- pixie/stdlib.pxi | 16 ++++++++++++---- tests/pixie/tests/test-stdlib.pxi | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6720693c..cf38d04f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -919,10 +919,14 @@ If further arguments are passed, invokes the method named by symbol, passing the (= idx 1) (-val self) :else not-found))) (extend -eq MapEntry (fn [self other] - (and (= (-key self) - (-key other)) - (= (-val self) - (-val other))))) + (cond + (map-entry? other) (and (= (-key self) + (-key other)) + (= (-val self) + (-val other))) + (vector? other) (= [(-key self) (-val self)] + other) + :else (= (seq self) other)))) (extend -reduce MapEntry indexed-reduce) @@ -937,6 +941,10 @@ If further arguments are passed, invokes the method named by symbol, passing the (fn [v] (transduce ordered-hash-reducing-fn v))) +(extend -seq MapEntry + (fn [self] + (list (-key self) (-val self)))) + (defn select-keys {:doc "Produces a map with only the values in m contained in key-seq"} [m key-seq] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index a4cb9c38..8334d9e0 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -675,3 +675,19 @@ (t/deftest test-lazyseq-conj (t/assert= '(1 2 3) (conj (lazy-seq '(2 3)) 1))) + +(t/deftest map-entry-seq + (let [m (map-entry :a 1)] + (t/assert= (seq m) '(:a 1)) + ;; vectors are equal to seqs if their indexed values are equal + ;; thus, a vector of length 2 is equal to a map-entry's seq IFoo + ;; their values are equal + (t/assert= [:a 1] m) + (t/assert= '(:a 1) m))) + +(t/deftest map-entry-equals + (let [m (map-entry :a 1)] + (t/assert= m m) + (t/assert= m (map-entry :a 1)) + (t/assert= m [:a 1]) + (t/assert= m '(:a 1)))) From ab2eb8aa287c0b5603738de84222a661d9621c46 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Fri, 2 Oct 2015 14:40:27 -0500 Subject: [PATCH 245/349] Adding a pixie.string/trim-newline function based off the one in Clojure. --- pixie/string.pxi | 1 + pixie/vm/libs/string.py | 10 ++++++++++ tests/pixie/tests/test-strings.pxi | 10 ++++++++++ 3 files changed, 21 insertions(+) diff --git a/pixie/string.pxi b/pixie/string.pxi index dc0fc7b7..73716df4 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -18,6 +18,7 @@ (def trim si/trim) (def triml si/triml) (def trimr si/trimr) +(def trim-newline si/trim-newline) (def capitalize si/capitalize) (def lower-case si/lower-case) diff --git a/pixie/vm/libs/string.py b/pixie/vm/libs/string.py index 967046c8..22403616 100644 --- a/pixie/vm/libs/string.py +++ b/pixie/vm/libs/string.py @@ -121,3 +121,13 @@ def trimr(a): if j <= 0: return rt.wrap(u"") return rt.wrap(a[0:j]) + +@as_var("pixie.string.internal", "trim-newline") +def trim_newline(a): + a = rt.name(a) + j = len(a) + while j > 0 and unicodedb.islinebreak(ord(a[j - 1])): + j -= 1 + if j <= 0: + return rt.wrap(u"") + return rt.wrap(a[0:j]) diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 129c5768..0013f6e2 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -110,6 +110,16 @@ (t/assert= (s/trimr " hey ") " hey") (t/assert= (s/trimr " h ey ") " h ey")) +(t/deftest test-trim-newline + (t/assert= (s/trim-newline "") "") + (t/assert= (s/trim-newline "\r\n") "") + (t/assert= (s/trim-newline "hey\r\n") "hey") + (t/assert= (s/trim-newline "hey\n\r") "hey") + (t/assert= (s/trim-newline "hey\r") "hey") + (t/assert= (s/trim-newline "hey\n") "hey") + (t/assert= (s/trim-newline "hey\r\nthere\r\n") "hey\r\nthere") + (t/assert= (s/trim-newline "\r\nhey\r\n") "\r\nhey")) + (t/deftest test-replace (t/assert= (s/replace "hey,you,there" "," ", ") "hey, you, there") (t/assert= (s/replace "hey,you,there" "," "") "heyyouthere") From 20a442bae69ce4bb16d5c965a9b4c7d99085cee4 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Fri, 2 Oct 2015 16:07:34 -0500 Subject: [PATCH 246/349] Adding a set union function. --- pixie/set.pxi | 16 ++++++++++++++++ tests/pixie/tests/test-sets.pxi | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 pixie/set.pxi create mode 100644 tests/pixie/tests/test-sets.pxi diff --git a/pixie/set.pxi b/pixie/set.pxi new file mode 100644 index 00000000..4479d2f8 --- /dev/null +++ b/pixie/set.pxi @@ -0,0 +1,16 @@ +(ns pixie.set + (:require [pixie.stdlib :as std])) + +(defn- -union [s t] + (if (< (count s) (count t)) + (reduce conj t s) + (reduce conj s t))) + +(defn union + "Returns a set that is the union of the input sets." + ([] #{}) + ([s] s) + ([s t] + (-union s t)) + ([s t & sets] + (reduce -union (-union s t) sets))) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi new file mode 100644 index 00000000..1e182c1e --- /dev/null +++ b/tests/pixie/tests/test-sets.pxi @@ -0,0 +1,20 @@ +(ns pixie.test.test-sets + (require pixie.test :as t) + (require pixie.set :as s)) + +(t/deftest test-union + (let [magic #{:bibbidi :bobbidi :boo} + work #{:got :no :time :to :dilly-dally} + dreams #{:the :dreams :that :i :wish} + magical-work #{:bibbidi :bobbidi :boo + :got :no :time :to :dilly-dally} + dream-of-magical-work #{:bibbidi :bobbidi :boo + :got :no :time :to :dilly-dally + :the :dreams :that :i :wish}] + (t/assert= (s/union) #{}) + (t/assert= (s/union magic) magic) + (t/assert= (s/union magic magic) magic) + (t/assert= (s/union magic magic magic) magic) + (t/assert= (s/union magic work) magical-work) + (t/assert= (s/union work magic) magical-work) + (t/assert= (s/union magic work dreams) dream-of-magical-work))) From e8206e7c119242a09ae7be963008ef094ad5089b Mon Sep 17 00:00:00 2001 From: Marcin Gasperowicz Date: Sat, 3 Oct 2015 15:48:39 +0200 Subject: [PATCH 247/349] Fix issue #203 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes issue #203 „Syntax quoting for maps is broken” Adds `map?` Adds tests for syntax quoting in maps --- pixie/vm/reader.py | 12 ++++++++++++ pixie/vm/stdlib.py | 4 ++++ tests/pixie/tests/test-macros.pxi | 8 ++++++++ 3 files changed, 24 insertions(+) create mode 100644 tests/pixie/tests/test-macros.pxi diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index a6ae64cd..84dccfba 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -430,6 +430,7 @@ def invoke(self, rdr, ch): CONCAT = symbol(u"concat") SEQ = symbol(u"seq") LIST = symbol(u"list") +HASHMAP = symbol(u"hashmap") def is_unquote(form): return True if rt._satisfies_QMARK_(rt.ISeq.deref(), form) \ @@ -477,16 +478,27 @@ def syntax_quote(form): return runtime_error(u"Unquote splicing not used inside list") elif rt.vector_QMARK_(form) is true: ret = rt.list(APPLY, CONCAT, SyntaxQuoteReader.expand_list(form)) + elif rt.map_QMARK_(form) is true: + mes = SyntaxQuoteReader.flatten_map(form) + ret = rt.list(APPLY, HASHMAP, rt.list(APPLY, CONCAT, SyntaxQuoteReader.expand_list(mes))) elif form is not nil and rt.seq_QMARK_(form) is true: ret = rt.list(APPLY, LIST, rt.cons(CONCAT, SyntaxQuoteReader.expand_list(rt.seq(form)))) else: ret = rt.list(QUOTE, form) return ret + @staticmethod + def flatten_map(form): + return rt.reduce(flatten_map_rfn, EMPTY_VECTOR, form) + @staticmethod def expand_list(form): return rt.reduce(expand_list_rfn, EMPTY_VECTOR, form) +@wrap_fn +def flatten_map_rfn(ret, item): + return rt.conj(rt.conj(ret, rt.first(item)), rt.first(rt.next(item))) + @wrap_fn def expand_list_rfn(ret, item): if is_unquote(item): diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 45287c85..79a9061c 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -667,6 +667,10 @@ def identical(a, b): def vector_QMARK_(a): return true if rt._satisfies_QMARK_(rt.IVector.deref(), a) else false +@as_var("map?") +def map_QMARK_(a): + return true if rt._satisfies_QMARK_(rt.IMap.deref(), a) else false + @returns(bool) @as_var("eq") def eq(a, b): diff --git a/tests/pixie/tests/test-macros.pxi b/tests/pixie/tests/test-macros.pxi new file mode 100644 index 00000000..5678a1ee --- /dev/null +++ b/tests/pixie/tests/test-macros.pxi @@ -0,0 +1,8 @@ +(ns collections.test-macros + (require pixie.test :as t)) + +(t/deftest hashmap-unquote + (let [x 10 k :boop] + (t/assert= (-eq `{:x ~x} {:x 10}) true) + (t/assert= (-eq `{~k ~x} {:boop 10}) true) + (t/assert= (-eq `{:x {:y ~x}} {:x {:y 10}}) true))) \ No newline at end of file From 7049c2bf6e9de8d2a03b38a43fcb7d682d44dbf6 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Tue, 6 Oct 2015 14:50:49 -0500 Subject: [PATCH 248/349] Set union asserts the arguments must be sets. --- pixie/set.pxi | 22 +++++++++++++++------- tests/pixie/tests/test-sets.pxi | 3 ++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 4479d2f8..0fd73cdb 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -1,16 +1,24 @@ (ns pixie.set (:require [pixie.stdlib :as std])) +(defn- -must-be-set [s] + (if (set? s) + s + (throw [:pixie.stdlib/InvalidArgumentException + (str "Not a set: " s)]))) + (defn- -union [s t] + (-must-be-set s) + (-must-be-set t) (if (< (count s) (count t)) (reduce conj t s) (reduce conj s t))) (defn union - "Returns a set that is the union of the input sets." - ([] #{}) - ([s] s) - ([s t] - (-union s t)) - ([s t & sets] - (reduce -union (-union s t) sets))) + "Returns a set that is the union of the input sets." + ([] #{}) + ([s] (-must-be-set s)) + ([s t] + (-union s t)) + ([s t & sets] + (reduce -union (-union s t) sets))) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi index 1e182c1e..e65ae454 100644 --- a/tests/pixie/tests/test-sets.pxi +++ b/tests/pixie/tests/test-sets.pxi @@ -17,4 +17,5 @@ (t/assert= (s/union magic magic magic) magic) (t/assert= (s/union magic work) magical-work) (t/assert= (s/union work magic) magical-work) - (t/assert= (s/union magic work dreams) dream-of-magical-work))) + (t/assert= (s/union magic work dreams) dream-of-magical-work) + (t/assert-throws? (s/union [:i :only] [:love :sets])))) From ae1fa4a1a7d717902726bb03ae83b2d003b4acc0 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Tue, 6 Oct 2015 16:40:37 -0500 Subject: [PATCH 249/349] Rewriting trim-newline as pure Pixie. --- pixie/string.pxi | 12 +++++++++++- pixie/vm/libs/string.py | 10 ---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pixie/string.pxi b/pixie/string.pxi index 73716df4..cc72b96f 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -18,7 +18,6 @@ (def trim si/trim) (def triml si/triml) (def trimr si/trimr) -(def trim-newline si/trim-newline) (def capitalize si/capitalize) (def lower-case si/lower-case) @@ -35,6 +34,17 @@ (def hexdigits "0123456789abcdefABCDEF") (def octdigits "012345678") +(defn trim-newline + "Replace all trailing newline characters (\\r and \\n) from the end of a string." + [s] + (loop [index (count s)] + (if (zero? index) + "" + (let [ch (nth s (dec index))] + (if (or (= ch \newline) (= ch \return)) + (recur (dec index)) + (substring s 0 index)))))) + (defn replace "Replace all occurrences of x in s with r." [s x r] diff --git a/pixie/vm/libs/string.py b/pixie/vm/libs/string.py index 22403616..967046c8 100644 --- a/pixie/vm/libs/string.py +++ b/pixie/vm/libs/string.py @@ -121,13 +121,3 @@ def trimr(a): if j <= 0: return rt.wrap(u"") return rt.wrap(a[0:j]) - -@as_var("pixie.string.internal", "trim-newline") -def trim_newline(a): - a = rt.name(a) - j = len(a) - while j > 0 and unicodedb.islinebreak(ord(a[j - 1])): - j -= 1 - if j <= 0: - return rt.wrap(u"") - return rt.wrap(a[0:j]) From e37f888a3d26102321ed4ce4fc3c45d0d6acff1e Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Wed, 7 Oct 2015 14:08:43 -0500 Subject: [PATCH 250/349] Adding an implementation of set intersection. --- pixie/set.pxi | 18 ++++++++++++++++++ tests/pixie/tests/test-sets.pxi | 13 +++++++++++++ 2 files changed, 31 insertions(+) diff --git a/pixie/set.pxi b/pixie/set.pxi index 0fd73cdb..8d1792ba 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -22,3 +22,21 @@ (-union s t)) ([s t & sets] (reduce -union (-union s t) sets))) + +(defn- -intersection [s t] + (-must-be-set s) + (-must-be-set t) + (let [result (atom #{})] + (doseq [i s] + (when (contains? t i) + (swap! result conj i))) + @result)) + +(defn intersection + "Returns a set that is the intersection of the input sets." + ([] #{}) + ([s] (-must-be-set s)) + ([s t] + (-intersection s t)) + ([s t & sets] + (reduce -intersection (-intersection s t) sets))) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi index e65ae454..90d91c2a 100644 --- a/tests/pixie/tests/test-sets.pxi +++ b/tests/pixie/tests/test-sets.pxi @@ -19,3 +19,16 @@ (t/assert= (s/union work magic) magical-work) (t/assert= (s/union magic work dreams) dream-of-magical-work) (t/assert-throws? (s/union [:i :only] [:love :sets])))) + +(t/deftest test-intersection + (let [magic #{:bibbidi :bobbidi :boo} + work #{:got :no :time :to :dilly-dally}] + (t/assert= (s/intersection) #{}) + (t/assert= (s/intersection magic) magic) + (t/assert= (s/intersection magic magic) magic) + (t/assert= (s/intersection magic work) #{}) + (t/assert= (s/intersection magic #{:boo}) #{:boo}) + (t/assert= (s/intersection #{:boo} magic) #{:boo}) + (t/assert= (s/intersection magic #{:bobbidi :boo}) #{:bobbidi :boo}) + (t/assert= (s/intersection magic #{:bibbidi :boo} #{:bobbidi :boo}) #{:boo}) + (t/assert-throws? (s/intersection [:i :only] [:love :sets])))) From c917853505a569e1d95cf63a1c3ef1cdbab4b1bd Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Wed, 7 Oct 2015 16:08:50 -0500 Subject: [PATCH 251/349] Using into instead of an atom to build the intersection. --- pixie/set.pxi | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 8d1792ba..8760093e 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -26,11 +26,7 @@ (defn- -intersection [s t] (-must-be-set s) (-must-be-set t) - (let [result (atom #{})] - (doseq [i s] - (when (contains? t i) - (swap! result conj i))) - @result)) + (into #{} (filter #(contains? s %)) t)) (defn intersection "Returns a set that is the intersection of the input sets." From 7a5b3e3897218e3c78d7933a4e8e988e1453fde1 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Wed, 7 Oct 2015 18:07:42 -0500 Subject: [PATCH 252/349] Adding a set difference function. --- pixie/set.pxi | 14 ++++++++++ tests/pixie/tests/test-sets.pxi | 47 +++++++++++++++++++-------------- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 8760093e..483dc26d 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -23,6 +23,20 @@ ([s t & sets] (reduce -union (-union s t) sets))) +(defn- -difference [s t] + (-must-be-set s) + (-must-be-set t) + (into #{} (filter #(not (contains? t %))) s)) + +(defn difference + "Returns a set that is the difference of the input sets." + ([] #{}) + ([s] (-must-be-set s)) + ([s t] + (-difference s t)) + ([s t & sets] + (reduce -difference (-difference s t) sets))) + (defn- -intersection [s t] (-must-be-set s) (-must-be-set t) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi index 90d91c2a..e9212496 100644 --- a/tests/pixie/tests/test-sets.pxi +++ b/tests/pixie/tests/test-sets.pxi @@ -2,27 +2,34 @@ (require pixie.test :as t) (require pixie.set :as s)) -(t/deftest test-union - (let [magic #{:bibbidi :bobbidi :boo} - work #{:got :no :time :to :dilly-dally} - dreams #{:the :dreams :that :i :wish} - magical-work #{:bibbidi :bobbidi :boo - :got :no :time :to :dilly-dally} - dream-of-magical-work #{:bibbidi :bobbidi :boo - :got :no :time :to :dilly-dally - :the :dreams :that :i :wish}] - (t/assert= (s/union) #{}) - (t/assert= (s/union magic) magic) - (t/assert= (s/union magic magic) magic) - (t/assert= (s/union magic magic magic) magic) - (t/assert= (s/union magic work) magical-work) - (t/assert= (s/union work magic) magical-work) - (t/assert= (s/union magic work dreams) dream-of-magical-work) - (t/assert-throws? (s/union [:i :only] [:love :sets])))) +(let [magic #{:bibbidi :bobbidi :boo} + work #{:got :no :time :to :dilly-dally}] -(t/deftest test-intersection - (let [magic #{:bibbidi :bobbidi :boo} - work #{:got :no :time :to :dilly-dally}] + (t/deftest test-union + (let [dreams #{:the :dreams :that :i :wish} + magical-work #{:bibbidi :bobbidi :boo + :got :no :time :to :dilly-dally} + dream-of-magical-work #{:bibbidi :bobbidi :boo + :got :no :time :to :dilly-dally + :the :dreams :that :i :wish}] + (t/assert= (s/union) #{}) + (t/assert= (s/union magic) magic) + (t/assert= (s/union magic magic) magic) + (t/assert= (s/union magic magic magic) magic) + (t/assert= (s/union magic work) magical-work) + (t/assert= (s/union work magic) magical-work) + (t/assert= (s/union magic work dreams) dream-of-magical-work) + (t/assert-throws? (s/union [:i :only] [:love :sets])))) + + (t/deftest test-difference + (t/assert= (s/difference) #{}) + (t/assert= (s/difference magic) magic) + (t/assert= (s/difference magic #{:boo}) #{:bibbidi :bobbidi}) + (t/assert= (s/difference magic work) magic) + (t/assert= (s/difference magic #{:bibbidi} #{:bobbidi}) #{:boo}) + (t/assert-throws? (s/difference [:i :only] [:love :sets]))) + + (t/deftest test-intersection (t/assert= (s/intersection) #{}) (t/assert= (s/intersection magic) magic) (t/assert= (s/intersection magic magic) magic) From a524fa3122aa49b1140dde8fe9f1cfa851a02195 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 8 Oct 2015 11:57:29 -0500 Subject: [PATCH 253/349] Adding several set relational predicates. --- pixie/set.pxi | 39 +++++++++++++++++++++++++++------ tests/pixie/tests/test-sets.pxi | 30 ++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 483dc26d..2a113e5e 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -7,12 +7,15 @@ (throw [:pixie.stdlib/InvalidArgumentException (str "Not a set: " s)]))) +(defn- -must-be-sets [& sets] + (doseq [set sets] + (-must-be-set set))) + (defn- -union [s t] - (-must-be-set s) - (-must-be-set t) - (if (< (count s) (count t)) - (reduce conj t s) - (reduce conj s t))) + (-must-be-sets s t) + (if (< (count s) (count t)) + (reduce conj t s) + (reduce conj s t))) (defn union "Returns a set that is the union of the input sets." @@ -24,8 +27,7 @@ (reduce -union (-union s t) sets))) (defn- -difference [s t] - (-must-be-set s) - (-must-be-set t) + (-must-be-sets s t) (into #{} (filter #(not (contains? t %))) s)) (defn difference @@ -50,3 +52,26 @@ (-intersection s t)) ([s t & sets] (reduce -intersection (-intersection s t) sets))) + +(defn subset? + "Returns true if the first set is a subset of the second." + [s t] + (-must-be-sets s t) + (and (<= (count s) (count t)) + (every? #(contains? t %) (vec s)))) + +(defn strict-subset? + "Returns true if the first set is a subset of the second." + [s t] + (and (subset? s t) + (< (count s) (count t)))) + +(defn superset? + "Returns true if the first set is a superset of the second." + [s t] + (subset? t s)) + +(defn strict-superset? + "Returns true if the first set is a strict superset of the second." + [s t] + (strict-subset? t s)) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi index e9212496..bccc8041 100644 --- a/tests/pixie/tests/test-sets.pxi +++ b/tests/pixie/tests/test-sets.pxi @@ -38,4 +38,32 @@ (t/assert= (s/intersection #{:boo} magic) #{:boo}) (t/assert= (s/intersection magic #{:bobbidi :boo}) #{:bobbidi :boo}) (t/assert= (s/intersection magic #{:bibbidi :boo} #{:bobbidi :boo}) #{:boo}) - (t/assert-throws? (s/intersection [:i :only] [:love :sets])))) + (t/assert-throws? (s/intersection [:i :only] [:love :sets]))) + + (t/deftest test-subset? + (t/assert (not (s/subset? magic work))) + (t/assert (s/subset? magic magic)) + (t/assert (not (s/subset? magic #{:foo}))) + (t/assert (s/subset? #{:boo} magic)) + (t/assert-throws? (s/subset? [:i :only] [:love :sets]))) + + (t/deftest test-strict-subset? + (t/assert (not (s/strict-subset? magic work))) + (t/assert (not (s/strict-subset? magic magic))) + (t/assert (not (s/strict-subset? magic #{:foo}))) + (t/assert (s/strict-subset? #{:boo} magic)) + (t/assert-throws? (s/strict-subset? [:i :only] [:love :sets]))) + + (t/deftest test-superset? + (t/assert (not (s/superset? magic work))) + (t/assert (s/superset? magic magic)) + (t/assert (not (s/superset? #{:foo} magic))) + (t/assert (s/superset? magic #{:boo})) + (t/assert-throws? (s/superset? [:i :only] [:love :sets]))) + + (t/deftest test-strict-superset? + (t/assert (not (s/strict-superset? magic work))) + (t/assert (not (s/strict-superset? magic magic))) + (t/assert (not (s/strict-superset? #{:foo} magic))) + (t/assert (s/strict-superset? magic #{:boo})) + (t/assert-throws? (s/strict-superset? [:i :only] [:love :sets])))) From e19d9a895f3d3436fab6f084e5524ec57a3b299d Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 8 Oct 2015 12:05:07 -0500 Subject: [PATCH 254/349] It'll probably be faster to do the count check first. --- pixie/set.pxi | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 2a113e5e..18060759 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -63,8 +63,9 @@ (defn strict-subset? "Returns true if the first set is a subset of the second." [s t] - (and (subset? s t) - (< (count s) (count t)))) + (-must-be-sets s t) + (and (< (count s) (count t)) + (subset? s t))) (defn superset? "Returns true if the first set is a superset of the second." From 97154127ac4075009b382f3532d638a36e65b035 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 8 Oct 2015 18:48:50 -0500 Subject: [PATCH 255/349] Faster set union. --- pixie/set.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pixie/set.pxi b/pixie/set.pxi index 18060759..23c4b425 100644 --- a/pixie/set.pxi +++ b/pixie/set.pxi @@ -14,8 +14,8 @@ (defn- -union [s t] (-must-be-sets s t) (if (< (count s) (count t)) - (reduce conj t s) - (reduce conj s t))) + (into t s) + (into s t))) (defn union "Returns a set that is the union of the input sets." From e971bcf1735394e14e88abd912055ad780d662a5 Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Sat, 10 Oct 2015 09:38:52 +0200 Subject: [PATCH 256/349] Use python2 as the default python executable This should make building on systems with python3 as default easier, and also make it clear that we need python2. Fixes #337. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f857a332..eae4c76b 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ all: help EXTERNALS=externals -PYTHON ?= python +PYTHON ?= python2 PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy From 4c5d3ee0f35a1d50d5ad245bcb9ab0eecb77ac9a Mon Sep 17 00:00:00 2001 From: puffybsd Date: Sun, 11 Oct 2015 00:27:18 -0400 Subject: [PATCH 257/349] Fix make clean_pxic 'rm: missing operand' error make clean_pxic fails if no files are found due to invalid rm command 'rm: missing operand'. Add --no-run-if-empty to xarg to fix. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index eae4c76b..cbe6086c 100644 --- a/Makefile +++ b/Makefile @@ -87,7 +87,7 @@ compile_src: find * -name "*.pxi" | grep "^pixie/" | xargs -L1 ./pixie-vm $(EXTERNALS_FLAGS) -c clean_pxic: - find * -name "*.pxic" | xargs rm + find * -name "*.pxic" | xargs --no-run-if-empty rm clean: clean_pxic rm -rf ./lib From 83e2ca7781bcfa2e943035c3bdd6e9dc97cc89df Mon Sep 17 00:00:00 2001 From: Philipp Rustemeier Date: Thu, 15 Oct 2015 12:37:07 +0200 Subject: [PATCH 258/349] FFI: coerce numbers to double if required and possible If a function invoked over FFI requires a double and a (Big)Integer or a Ratio is supplied, automatically coerce to double. Should help with the rest of #377. --- pixie/vm/libs/ffi.py | 8 +++++++- pixie/vm/numbers.py | 2 ++ tests/pixie/tests/test-ffi.pxi | 7 +++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 86fdc840..eb24e44d 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -8,7 +8,7 @@ import pixie.vm.rt as rt from rpython.rtyper.lltypesystem import rffi, lltype, llmemory from pixie.vm.primitives import nil, true, false -from pixie.vm.numbers import Integer, Float +from pixie.vm.numbers import Integer, Float, BigInteger, Ratio from pixie.vm.string import String from pixie.vm.keyword import Keyword from pixie.vm.util import unicode_to_utf8 @@ -359,6 +359,12 @@ def ffi_get_value(self, ptr): return Float(casted[0]) def ffi_set_value(self, ptr, val): + if isinstance(val, Integer): + val = Float(float(val.int_val())) + elif isinstance(val, BigInteger): + val = Float(val.bigint_val().tofloat()) + elif isinstance(val, Ratio): + val = Float(val.numerator() / float(val.denominator())) casted = rffi.cast(rffi.DOUBLEP, ptr) casted[0] = rffi.cast(rffi.DOUBLE, val.float_val()) diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index eac2878f..4505840a 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -302,6 +302,8 @@ def to_float(x): return x if isinstance(x, Ratio): return rt.wrap(x.numerator() / float(x.denominator())) + if isinstance(x, Integer): + return rt.wrap(float(x.int_val())) if isinstance(x, BigInteger): return rt.wrap(x.bigint_val().tofloat()) assert False diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index beaaa079..f2d997c7 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -58,3 +58,10 @@ (t/deftest test-size (t/assert= (pixie.ffi/struct-size (pixie.ffi/c-struct "struct" 1234 [])) 1234)) + + +(t/deftest test-double-coercion + (t/assert= (m/sin 1) (m/sin 1.0)) + (let [big (reduce * 1 (range 1 100))] + (t/assert= (m/sin big) (m/sin (float big)))) + (t/assert= (m/sin (/ 1 2)) (m/sin (float (/ 1 2))))) From a007eee58a488f3abe806c28ef9b93b7309bf194 Mon Sep 17 00:00:00 2001 From: Philipp Rustemeier Date: Thu, 15 Oct 2015 13:14:08 +0200 Subject: [PATCH 259/349] Use numbers.to_float to do the coercion --- pixie/vm/libs/ffi.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index eb24e44d..57b53184 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -8,7 +8,7 @@ import pixie.vm.rt as rt from rpython.rtyper.lltypesystem import rffi, lltype, llmemory from pixie.vm.primitives import nil, true, false -from pixie.vm.numbers import Integer, Float, BigInteger, Ratio +from pixie.vm.numbers import to_float, Integer, Float, BigInteger, Ratio from pixie.vm.string import String from pixie.vm.keyword import Keyword from pixie.vm.util import unicode_to_utf8 @@ -359,12 +359,8 @@ def ffi_get_value(self, ptr): return Float(casted[0]) def ffi_set_value(self, ptr, val): - if isinstance(val, Integer): - val = Float(float(val.int_val())) - elif isinstance(val, BigInteger): - val = Float(val.bigint_val().tofloat()) - elif isinstance(val, Ratio): - val = Float(val.numerator() / float(val.denominator())) + if isinstance(val, Integer) or isinstance(val, BigInteger) or isinstance(val, Ratio): + val = to_float(val) casted = rffi.cast(rffi.DOUBLEP, ptr) casted[0] = rffi.cast(rffi.DOUBLE, val.float_val()) From f0faaabb58027a3ca05ed527598d11c42f31b091 Mon Sep 17 00:00:00 2001 From: Philipp Rustemeier Date: Thu, 15 Oct 2015 13:49:01 +0200 Subject: [PATCH 260/349] Drop explicit type check (to_float covers this already). --- pixie/vm/libs/ffi.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 57b53184..193b56ce 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -359,8 +359,7 @@ def ffi_get_value(self, ptr): return Float(casted[0]) def ffi_set_value(self, ptr, val): - if isinstance(val, Integer) or isinstance(val, BigInteger) or isinstance(val, Ratio): - val = to_float(val) + val = to_float(val) casted = rffi.cast(rffi.DOUBLEP, ptr) casted[0] = rffi.cast(rffi.DOUBLE, val.float_val()) From 13b7c2d350466138820cc3d3cdff311a78958a7f Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 15 Oct 2015 14:36:15 +0100 Subject: [PATCH 261/349] this should make our builds faster enables the new infrastructure for travis builds --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 28ac48e9..490d9e48 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +sudo: false env: - JIT_OPTS='--opt=jit' TARGET_OPTS='target.py' - JIT_OPTS='' TARGET_OPTS='target.py' From fc04fba3567f8741e7e09ce4312e9bdc9df55d73 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Thu, 15 Oct 2015 15:00:48 +0100 Subject: [PATCH 262/349] use travis apt replacement --- .travis.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 490d9e48..7176dc4b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,8 +17,14 @@ script: - make compile_tests - make run_built_tests -before_install: - - sudo apt-get install libffi-dev libedit-dev libboost-all-dev zlib1g-dev zlib-bin +addons: + apt: + packages: + - libffi-dev + - libedit-dev + - libboost-all-dev + - zlib1g-dev + - zlib-bin notifications: irc: "chat.freenode.net#pixie-lang" From 15aa7f8f1748f1014d9ffe53e6ef00b095212970 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 16 Oct 2015 16:16:20 +0100 Subject: [PATCH 263/349] fixes getting docs from aliased ns --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 434206a0..7d16a0c6 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1371,7 +1371,7 @@ and implements IAssociative, ILookup and IObject." :added "0.1"} [v] - (let [vr (resolve v) + (let [vr (resolve-in *ns* v) x (if vr @vr) doc (get (meta x) :doc) has-doc? (if doc true (get (meta x) :signatures))] From e4f4bf666b45da559aa4a88056cf2a9abfd3e184 Mon Sep 17 00:00:00 2001 From: alejandrodob Date: Mon, 19 Oct 2015 17:28:54 +0200 Subject: [PATCH 264/349] Add coll? function and tests --- pixie/stdlib.pxi | 1 + tests/pixie/tests/test-stdlib.pxi | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 434206a0..5a0b0729 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -867,6 +867,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn set? [v] (instance? PersistentHashSet v)) (defn map? [v] (satisfies? IMap v)) (defn fn? [v] (satisfies? IFn v)) +(defn coll? [v] (satisfies? IPersistentCollection v)) (defn indexed? [v] (satisfies? IIndexed v)) (defn counted? [v] (satisfies? ICounted v)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 8334d9e0..3e77b9b8 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -304,6 +304,16 @@ (t/assert= (fn? "foo") false) (t/assert= (fn? (let [x 8] (fn [y] (+ x y)))) true)) +(t/deftest test-coll? + (t/assert= (coll? '()) true) + (t/assert= (coll? []) true) + (t/assert= (coll? {:foo "bar"}) true) + (t/assert= (coll? #{:foo :bar}) true) + (t/assert= (coll? #(%)) false) + (t/assert= (coll? :foo) false) + (t/assert= (coll? "foo") false) + (t/assert= (coll? 1) false)) + (t/deftest test-macro? (t/assert= (macro? and) true) (t/assert= (macro? or) true) From ca9150b8e02a849245bdaa8d9ff2f689f9afec2e Mon Sep 17 00:00:00 2001 From: Max Penet Date: Tue, 27 Oct 2015 22:54:57 +0100 Subject: [PATCH 265/349] add vary-meta --- pixie/stdlib.pxi | 6 ++++++ tests/pixie/tests/test-stdlib.pxi | 3 +++ 2 files changed, 9 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 7d16a0c6..a9759630 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2717,3 +2717,9 @@ Calling this function on something that is not ISeqable returns a seq with that (if (satisfies? IComparable x) (-compare x y) (throw [::ComparisonError (str x " does not satisfy IComparable")]))) + +(defn vary-meta + [x f & args] + "Returns x with meta data updated with the application of f and args to it. +ex: (vary-meta x assoc :foo 42)" + (with-meta x (apply f (meta x) args))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 8334d9e0..167177e1 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -691,3 +691,6 @@ (t/assert= m (map-entry :a 1)) (t/assert= m [:a 1]) (t/assert= m '(:a 1)))) + +(t/deftest vary-meta + (t/assert= 42 (-> {} (vary-meta assoc :foo 42) meta :foo))) From 0e9d3e0f0aee9436daabf87691d7e32a2c5f0d0d Mon Sep 17 00:00:00 2001 From: Max Penet Date: Tue, 27 Oct 2015 23:39:56 +0100 Subject: [PATCH 266/349] add IRecord marker protocol and record? predicate --- pixie/stdlib.pxi | 19 ++++++++++++------- tests/pixie/tests/test-defrecord.pxi | 4 ++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 7d16a0c6..e65055e7 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -339,6 +339,11 @@ ([state] (finish-hash-state state)) ([state itm] (update-hash-unordered! state itm)))) +(def string-builder + (fn ^{:doc "Creates a reducing function that builds a string based on calling str on the transduced collection"} + ([] (-string-builder)) + ([sb] (str sb)) + ([sb item] (conj! sb item)))) (extend -str PersistentVector (fn [v] @@ -1303,7 +1308,8 @@ and implements IAssociative, ILookup and IObject." `(= (~field self) (~field other))) fields))) `(-hash [self] - (hash [~@field-syms]))] + (hash [~@field-syms])) + `IRecord] deftype-decl `(deftype ~nm ~fields ~@default-bodies ~@body)] `(do ~type-from-map ~deftype-decl))) @@ -2362,6 +2368,11 @@ Expands to calls to `extend-type`." [x] (-int x)) +(defprotocol IRecord) + +(defn record? + [x] + (satisfies? IRecord x)) (defmacro for {:doc "A list comprehension for the bindings." @@ -2418,12 +2429,6 @@ Expands to calls to `extend-type`." ([result] result) ([result _] (inc result))) -(defn string-builder - "Creates a reducing function that builds a string based on calling str on the transduced collection" - ([] (-string-builder)) - ([sb] (str sb)) - ([sb item] (conj! sb item))) - (defn dispose! "Finalizes use of the object by cleaning up resources used by the object" [x] diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index bc63724a..29844e6e 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -12,9 +12,13 @@ (t/deftest test-satisfies (foreach [t [t1 t2 t3 t4 t5]] (t/assert= t t) + (t/assert (satisfies? IRecord t)) (t/assert (satisfies? IAssociative t)) (t/assert (satisfies? ILookup t)))) +(t/deftest test-record-pred + (t/assert (record? t1))) + (t/deftest test-eq (t/assert= t1 t2) (t/assert= t2 t3) From 93d8426a763dcf1e6c81ba23231cd069679b33b0 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 28 Oct 2015 09:10:45 +0100 Subject: [PATCH 267/349] docstring --- pixie/stdlib.pxi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index e65055e7..0c7fa28e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2371,6 +2371,8 @@ Expands to calls to `extend-type`." (defprotocol IRecord) (defn record? + {:doc "Returns true if x implements IRecord" + :since "0.1"} [x] (satisfies? IRecord x)) From 854d838c6b51e4a5ad994ddc871872810a65739e Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 28 Oct 2015 09:14:15 +0100 Subject: [PATCH 268/349] improve metadata --- pixie/stdlib.pxi | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a9759630..614befd6 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2719,7 +2719,9 @@ Calling this function on something that is not ISeqable returns a seq with that (throw [::ComparisonError (str x " does not satisfy IComparable")]))) (defn vary-meta - [x f & args] - "Returns x with meta data updated with the application of f and args to it. + {:doc "Returns x with meta data updated with the application of f and args to it. ex: (vary-meta x assoc :foo 42)" + :signatures [[x f & args]] + :added "0.1"} + [x f & args] (with-meta x (apply f (meta x) args))) From 499430529b04f6375d9406dfa3be630cee459eec Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 28 Oct 2015 10:12:34 +0100 Subject: [PATCH 269/349] deftest compile down to a function with the same name, so it clashes with the stdlib var --- tests/pixie/tests/test-stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 167177e1..217784d1 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -692,5 +692,5 @@ (t/assert= m [:a 1]) (t/assert= m '(:a 1)))) -(t/deftest vary-meta +(t/deftest test-vary-meta (t/assert= 42 (-> {} (vary-meta assoc :foo 42) meta :foo))) From d613d130f321548341bc0cfa93863a3b654ea57f Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 28 Oct 2015 15:08:52 +0100 Subject: [PATCH 270/349] add metadata support to records --- pixie/stdlib.pxi | 16 ++++++++++++++-- tests/pixie/tests/test-defrecord.pxi | 4 ++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 00cbf29e..ab0cdc3d 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1281,6 +1281,7 @@ and implements IAssociative, ILookup and IObject." fields (transduce (map (comp keyword name)) conj field-syms) type-from-map `(defn ~map-ctor-name [m] (apply ~ctor-name (map #(get m %) ~fields))) + meta-gs (gensym "meta") default-bodies ['IAssociative (-make-record-assoc-body ctor-name fields) @@ -1299,6 +1300,13 @@ and implements IAssociative, ILookup and IObject." [k `(get-field ~self-nm ~k-nm)]) fields) not-found#))) + + 'IMeta + `(-with-meta [self# ~meta-gs] + (new ~nm + ~@(conj field-syms meta-gs))) + `(-meta [self#] __meta) + 'IObject `(-str [self#] (str "<" ~(name nm) " " (reduce #(assoc %1 %2 (%2 self#)) {} ~fields) ">")) @@ -1310,9 +1318,13 @@ and implements IAssociative, ILookup and IObject." `(-hash [self] (hash [~@field-syms])) `IRecord] - deftype-decl `(deftype ~nm ~fields ~@default-bodies ~@body)] + deftype-decl `(deftype ~nm ~(conj fields '__meta) ~@default-bodies ~@body) + ctor `(defn ~ctor-name ~field-syms + (new ~nm + ~@(conj field-syms nil)))] `(do ~type-from-map - ~deftype-decl))) + ~deftype-decl + ~ctor))) (defn print {:doc "Prints the arguments, seperated by spaces." diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index 29844e6e..46a48d99 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -53,3 +53,7 @@ (t/assert (contains? t :one)) (t/assert (contains? t :two)) (t/assert (contains? t :three)))) + +(t/deftest test-record-metadata + (t/assert= nil (meta t1)) + (t/assert= :foo (-> t1 (with-meta :foo) meta))) From 62cacaca12be3005f722d427161d5a4933ce8798 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Thu, 29 Oct 2015 08:42:56 +0100 Subject: [PATCH 271/349] add *-> threading macros --- pixie/stdlib.pxi | 144 +++++++++++++++++++++++------- tests/pixie/tests/test-macros.pxi | 46 +++++++++- 2 files changed, 156 insertions(+), 34 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ab0cdc3d..3cd4f707 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -226,7 +226,6 @@ ([val coll] (transduce (interpose val) conj coll)))) - (def preserving-reduced (fn preserving-reduced [rf] (fn pr-inner [a b] @@ -480,38 +479,6 @@ (let [nm (with-meta nm (assoc (meta nm) :private true))] (cons `defn (cons nm rest)))) -(defmacro -> - {:doc "Threads `x` through `forms`, passing the result of one step as the first argument of the next." - :examples [["(-> 3 inc inc)" nil 5] - ["(-> \"James\" (str \" is \" \"awesome \") (str \"(and stuff)\" \"!\"))" nil "James is awesome (and stuff)!"]] - :signatures [[x & forms]] - :added "0.1"} - [x & forms] - (loop [x x, forms forms] - (if forms - (let [form (first forms) - threaded (if (seq? form) - (with-meta `(~(first form) ~x ~@(next form)) (meta form)) - (list form x))] - (recur threaded (next forms))) - x))) - -(defmacro ->> - {:doc "Threads `x` through `forms`, passing the result of one step as the last argument of the next." - :examples [["(->> \"James\" (str \"we \" \"like \") (str \"you \" \"know \" \"what? \"))" nil "you know what? we like James"] - ["(->> 5 (range) (map inc) seq)" nil (1 2 3 4 5)]] - :signatures [[x & forms]] - :added "0.1"} - [x & forms] - (loop [x x, forms forms] - (if forms - (let [form (first forms) - threaded (if (seq? form) - (with-meta `(~(first form) ~@(next form) ~x) (meta form)) - (list form x))] - (recur threaded (next forms))) - x))) - (defn not {:doc "Inverts the input, if a truthy value is supplied, returns false, otherwise returns true" @@ -2640,6 +2607,117 @@ Calling this function on something that is not ISeqable returns a seq with that [x] (instance? Bool x)) +(defmacro -> + {:doc "Threads `x` through `forms`, passing the result of one step as the first argument of the next." + :examples [["(-> 3 inc inc)" nil 5] + ["(-> \"James\" (str \" is \" \"awesome \") (str \"(and stuff)\" \"!\"))" nil "James is awesome (and stuff)!"]] + :signatures [[x & forms]] + :added "0.1"} + [x & forms] + (loop [x x, forms forms] + (if forms + (let [form (first forms) + threaded (if (seq? form) + (with-meta `(~(first form) ~x ~@(next form)) (meta form)) + (list form x))] + (recur threaded (next forms))) + x))) + +(defmacro ->> + {:doc "Threads `x` through `forms`, passing the result of one step as the last argument of the next." + :examples [["(->> \"James\" (str \"we \" \"like \") (str \"you \" \"know \" \"what? \"))" nil "you know what? we like James"] + ["(->> 5 (range) (map inc) seq)" nil (1 2 3 4 5)]] + :signatures [[x & forms]] + :added "0.1"} + [x & forms] + (loop [x x, forms forms] + (if forms + (let [form (first forms) + threaded (if (seq? form) + (with-meta `(~(first form) ~@(next form) ~x) (meta form)) + (list form x))] + (recur threaded (next forms))) + x))) + +(defmacro some-> + {:doc "When expr is not nil, threads it into the first form (via ->), + and when that result is not nil, through the next etc" + :signatures [[expr & forms]] + :added "0.1"} + [expr & forms] + (let [g (gensym) + steps (map (fn [step] `(if (nil? ~g) nil (-> ~g ~step))) + forms)] + `(let [~g ~expr + ~@(interleave (repeat g) (butlast steps))] + ~(if (empty? steps) + g + (last steps))))) + +(defmacro some->> + {:doc "When expr is not nil, threads it into the first form (via ->>), + and when that result is not nil, through the next etc" + :signatures [[x & forms]] + :added "0,1"} + [expr & forms] + (let [g (gensym) + steps (map (fn [step] `(if (nil? ~g) nil (->> ~g ~step))) + forms)] + `(let [~g ~expr + ~@(interleave (repeat g) (butlast steps))] + ~(if (empty? steps) + g + (last steps))))) + +(defmacro cond-> + {:added "0.1" + :signatures [[expr & clauses]] + :doc "Takes an expression and a set of test/form pairs. Threads expr (via ->) + through each form for which the corresponding test + expression is true. Note that, unlike cond branching, cond-> threading does + not short circuit after the first true test expression."} + [expr & clauses] + (assert (even? (count clauses))) + (let [g (gensym) + steps (map (fn [[test step]] `(if ~test (-> ~g ~step) ~g)) + (partition 2 clauses))] + `(let [~g ~expr + ~@(interleave (repeat g) (butlast steps))] + ~(if (empty? steps) + g + (last steps))))) + +(defmacro cond->> + {:doc "Takes an expression and a set of test/form pairs. Threads expr (via ->>) + through each form for which the corresponding test expression + is true. Note that, unlike cond branching, cond->> threading does not short circuit + after the first true test expression." + :signatures [[expr & clauses]] + :added "0.1"} + [expr & clauses] + (assert (even? (count clauses))) + (let [g (gensym) + steps (map (fn [[test step]] `(if ~test (->> ~g ~step) ~g)) + (partition 2 clauses))] + `(let [~g ~expr + ~@(interleave (repeat g) (butlast steps))] + ~(if (empty? steps) + g + (last steps))))) + +(defmacro as-> + {:doc "Binds name to expr, evaluates the first form in the lexical context + of that binding, then binds name to that result, repeating for each + successive form, returning the result of the last form." + :signatures [[expr name & forms]] + :added "0,1"} + [expr name & forms] + `(let [~name ~expr + ~@(interleave (repeat name) (butlast forms))] + ~(if (empty? forms) + name + (last forms)))) + (defprotocol IComparable (-compare [x y] "Compare to objects returing 0 if the same -1 with x is logically smaller than y and 1 if x is logically larger")) diff --git a/tests/pixie/tests/test-macros.pxi b/tests/pixie/tests/test-macros.pxi index 5678a1ee..238408d3 100644 --- a/tests/pixie/tests/test-macros.pxi +++ b/tests/pixie/tests/test-macros.pxi @@ -5,4 +5,48 @@ (let [x 10 k :boop] (t/assert= (-eq `{:x ~x} {:x 10}) true) (t/assert= (-eq `{~k ~x} {:boop 10}) true) - (t/assert= (-eq `{:x {:y ~x}} {:x {:y 10}}) true))) \ No newline at end of file + (t/assert= (-eq `{:x {:y ~x}} {:x {:y 10}}) true))) + +(def constantly-nil (constantly nil)) + +(t/deftest some->test + (t/assert (nil? (some-> nil))) + (t/assert (= 0 (some-> 0))) + (t/assert (= -1 (some-> 1 (- 2)))) + (t/assert (nil? (some-> 1 constantly-nil (- 2))))) + +(t/deftest some->>test + (t/assert (nil? (some->> nil))) + (t/assert (= 0 (some->> 0))) + (t/assert (= 1 (some->> 1 (- 2)))) + (t/assert (nil? (some->> 1 constantly-nil (- 2))))) + +(t/deftest cond->test + (t/assert (= 0 (cond-> 0))) + (t/assert (= -1 (cond-> 0 true inc true (- 2)))) + (t/assert (= 0 (cond-> 0 false inc))) + (t/assert (= -1 (cond-> 1 true (- 2) false inc)))) + +(t/deftest cond->>test + (t/assert (= 0 (cond->> 0))) + (t/assert (= 1 (cond->> 0 true inc true (- 2)))) + (t/assert (= 0 (cond->> 0 false inc))) + (t/assert (= 1 (cond->> 1 true (- 2) false inc)))) + +(t/deftest as->test + (t/assert (= 0 (as-> 0 x))) + (t/assert (= 1 (as-> 0 x (inc x)))) + (t/assert (= 2 (as-> [0 1] x + (map inc x) + (reverse x) + (first x))))) + +(t/deftest threading-loop-recur + (t/assert (nil? (loop [] + (as-> 0 x + (when-not (zero? x) + (recur)))))) + (t/assert (nil? (loop [x nil] (some-> x recur)))) + (t/assert (nil? (loop [x nil] (some->> x recur)))) + (t/assert (= 0 (loop [x 0] (cond-> x false recur)))) + (t/assert (= 0 (loop [x 0] (cond->> x false recur))))) From 7414496afbc2cf497bb3422851174b05cc648af3 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Fri, 30 Oct 2015 11:59:45 +0100 Subject: [PATCH 272/349] Implement IReduce on Records --- pixie/stdlib.pxi | 13 +++++++++++++ tests/pixie/tests/test-defrecord.pxi | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 3cd4f707..cd94876a 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1268,6 +1268,19 @@ and implements IAssociative, ILookup and IObject." fields) not-found#))) + 'IReduce + `(-reduce [self# f# init#] + (loop [fields# ~fields + acc# init#] + (if-let [field# (first fields#)] + (let [acc# (f# acc# (map-entry field# + (get-field self# + field#)))] + (if (reduced? acc#) + @acc# + (recur (next fields#) acc#))) + acc#))) + 'IMeta `(-with-meta [self# ~meta-gs] (new ~nm diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index 46a48d99..e45788ea 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -57,3 +57,9 @@ (t/deftest test-record-metadata (t/assert= nil (meta t1)) (t/assert= :foo (-> t1 (with-meta :foo) meta))) + + +(t/deftest ireduce [] + (t/assert= [[:one 1] [:two 2] [:three 3]] (reduce conj [] t1)) + (t/assert= [1 2 3] (vals t1)) + (t/assert= [:one :two :three] (keys t1))) From 81cdc2df08ab710630136391e6bb461c33c553c3 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Fri, 30 Oct 2015 12:35:24 +0100 Subject: [PATCH 273/349] allows kw/map/set invocations with default value --- pixie/stdlib.pxi | 15 ++++++++++----- tests/pixie/tests/collections/test-maps.pxi | 5 +++-- tests/pixie/tests/collections/test-sets.pxi | 4 +++- tests/pixie/tests/test-keywords.pxi | 3 ++- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ab0cdc3d..e47f7498 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1061,17 +1061,22 @@ If further arguments are passed, invokes the method named by symbol, passing the (extend -repr Symbol -str) -(extend -invoke Keyword (fn [k m] (-val-at m k nil))) -(extend -invoke PersistentHashMap (fn [m k] (-val-at m k nil))) -(extend -invoke PersistentHashSet (fn [m k] (-val-at m k nil))) - (defn get {:doc "Get an element from a collection implementing ILookup, return nil or the default value if not found." :added "0.1"} ([mp k] (get mp k nil)) ([mp k not-found] - (-val-at mp k not-found))) + (-val-at mp k not-found))) + +(extend -invoke Keyword (fn + ([k m not-found] + (-val-at m k not-found)) + ([k m] + (-val-at m k nil)))) +(extend -invoke PersistentHashMap get) +(extend -invoke PersistentHashSet get) + (defn get-in {:doc "Get a value from a nested collection at the \"path\" given by the keys." diff --git a/tests/pixie/tests/collections/test-maps.pxi b/tests/pixie/tests/collections/test-maps.pxi index a4072fe1..246e4af5 100644 --- a/tests/pixie/tests/collections/test-maps.pxi +++ b/tests/pixie/tests/collections/test-maps.pxi @@ -25,14 +25,15 @@ (t/assert= (-eq m {:a 1, :b 2, :c 4}) false) (t/assert= (-eq m {:a 3, :b 2, :c 1}) false))) - (t/deftest map-val-at-and-invoke (let [m {:a 1, :b 2, :c 3}] (foreach [e m] (t/assert= (get m (key e)) (val e)) (t/assert= (m (key e)) (val e))) (t/assert= (get m :d) nil) - (t/assert= (m :d) nil))) + (t/assert= (m :d) nil) + (t/assert= (m :d :foo) :foo) + (t/assert= (:d m :foo) :foo))) (t/deftest map-without (let [m {:a 1 :b 2}] diff --git a/tests/pixie/tests/collections/test-sets.pxi b/tests/pixie/tests/collections/test-sets.pxi index 376f95bf..7b91c342 100644 --- a/tests/pixie/tests/collections/test-sets.pxi +++ b/tests/pixie/tests/collections/test-sets.pxi @@ -58,7 +58,9 @@ (t/assert= (s 3) 3) (t/assert= (s -1) nil) - (t/assert= (s 4) nil))) + (t/assert= (s 4) nil) + (t/assert= (s :d :foo) :foo) + (t/assert= (:d s :foo) :foo))) (t/deftest test-has-meta (let [m {:has-meta true} diff --git a/tests/pixie/tests/test-keywords.pxi b/tests/pixie/tests/test-keywords.pxi index 9b4357e7..06e2deb7 100644 --- a/tests/pixie/tests/test-keywords.pxi +++ b/tests/pixie/tests/test-keywords.pxi @@ -7,7 +7,8 @@ (t/assert= (:b m) 2) (t/assert= (:c m) 3) - (t/assert= (:d m) nil))) + (t/assert= (:d m) nil) + (t/assert= (:d m :foo) :foo))) (t/deftest keyword-namespace (t/assert= (namespace :foo/bar) "foo") From d92c6f88ab9afa150091adb6db4fd810a761afc3 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 2 Nov 2015 09:51:07 +0100 Subject: [PATCH 274/349] adds keep-indexed, map-indexed and reductions functions --- pixie/stdlib.pxi | 73 +++++++++++++++++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 13 ++++++ 2 files changed, 86 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 3023ce0e..19c20a00 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1727,6 +1727,79 @@ not enough elements were present." (cons (take n s) (partitionf f (drop n s))))))) +(defn map-indexed + {:doc "Returns a lazy sequence consisting of the + result of applying f to 0 and the first item of coll, followed by + applying f to 1 and the second item in coll, etc, until coll is + exhausted. Thus function f should accept 2 arguments, index and + item. Returns a stateful transducer when no collection is provided." + :added "0.1" + :signatures [[f] [f coll]]} + ([f] + (fn [rf] + (let [i (atom -1) + rrf (preserving-reduced rf)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (rrf result (f (swap! i inc) input))))))) + ([f coll] + (let [mapi (fn mapi [i coll] + (lazy-seq + (when-let [s (seq coll)] + (cons (f i (first s)) + (mapi (inc i) (rest s))))))] + (mapi 0 coll)))) + +(defn keep-indexed + {:doc "Returns a lazy sequence of the non-nil + results of (f index item). Note, this means false return values will + be included. f must be free of side-effects. Returns a stateful + transducer when no collection is provided." + :signatures [[f] [f coll]] + :added "0.1"} + ([f] + (fn [rf] + (let [iv (atom -1) + rrf (preserving-reduced)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (let [i (swap! iv inc) + v (f i input)] + (if (nil? v) + result + (rrf result v)))))))) + ([f coll] + (let [keepi (fn keepi [i coll] + (lazy-seq + (when-let [s (seq coll)] + (let [x (f i (first s))] + (if (nil? x) + (keepi (inc i) (rest s)) + (cons x (keepi (inc i) (rest s))))))))] + (keepi 0 coll)))) + +(defn reductions + {:doc "Returns a lazy seq of the intermediate values of the + reduction (as per reduce) of coll by f, starting with init." + :added "0.1" + :signatures [[f coll] [f init coll]]} + ([f coll] + (lazy-seq + (if-let [s (seq coll)] + (reductions f (first s) (rest s)) + (list (f))))) + ([f init coll] + (if (reduced? init) + (list @init) + (cons init + (lazy-seq + (when-let [s (seq coll)] + (reductions f (f init (first s)) (rest s)))))))) + (defn destructure [binding expr] (cond (symbol? binding) [binding expr] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index f3dc0a0a..ca71c2a4 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -19,6 +19,19 @@ (t/assert= (mapcat identity []) []) (t/assert= (mapcat first [[[1 2]] [[3] [:not :present]] [[4 5 6]]]) [1 2 3 4 5 6])) +(t/deftest test-indexed + (t/assert= (map-indexed (fn [& xs] xs) []) []) + (t/assert= (map-indexed (fn [& xs] xs) [:a :b]) [[0 :a] [1 :b]]) + (t/assert= (transduce (map-indexed (fn [& xs] xs)) conj [:a :b]) [[0 :a] [1 :b]])) + +(t/deftest test-reductions + (t/assert= (reductions + nil) + [0]) + (t/assert= (reductions + [1 2 3 4 5]) + [1 3 6 10 15]) + (t/assert= (reductions + 10 [1 2 3 4 5]) + [10 11 13 16 20 25])) + (t/deftest test-str (t/assert= (str nil) "nil") (t/assert= (str true) "true") From 1d76fc3b743e6b4f362e01d25eadadf4c6750b18 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 2 Nov 2015 10:26:25 +0100 Subject: [PATCH 275/349] fix keep-indexed transducer and add tests --- pixie/stdlib.pxi | 2 +- tests/pixie/tests/test-stdlib.pxi | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 19c20a00..285ecad8 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1762,7 +1762,7 @@ not enough elements were present." ([f] (fn [rf] (let [iv (atom -1) - rrf (preserving-reduced)] + rrf (preserving-reduced rf)] (fn ([] (rf)) ([result] (rf result)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index ca71c2a4..36b6d09f 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -22,7 +22,15 @@ (t/deftest test-indexed (t/assert= (map-indexed (fn [& xs] xs) []) []) (t/assert= (map-indexed (fn [& xs] xs) [:a :b]) [[0 :a] [1 :b]]) - (t/assert= (transduce (map-indexed (fn [& xs] xs)) conj [:a :b]) [[0 :a] [1 :b]])) + (t/assert= (transduce (map-indexed (fn [& xs] xs)) conj [:a :b]) [[0 :a] [1 :b]]) + + (t/assert= (keep-indexed (constantly true) []) []) + (t/assert= (keep-indexed (constantly nil) []) []) + (t/assert= (keep-indexed (fn [i x] [i x]) [:a :b]) [[0 :a] [1 :b]]) + + (t/assert= (transduce (keep-indexed (constantly true)) conj []) []) + (t/assert= (transduce (keep-indexed (constantly nil)) conj []) []) + (t/assert= (transduce (keep-indexed (fn [i x] [i x])) conj [:a :b]) [[0 :a] [1 :b]])) (t/deftest test-reductions (t/assert= (reductions + nil) From 373a44da19e67ca96a90ead02a84d5372b1f3b0e Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 2 Nov 2015 13:10:45 +0100 Subject: [PATCH 276/349] implement ICounted and ISeqable on records --- pixie/stdlib.pxi | 8 +++++++- tests/pixie/tests/test-defrecord.pxi | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 285ecad8..23ac2e67 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -11,7 +11,6 @@ (def printf (ffi-fn libc "printf" [CCharP] CInt :variadic? true)) (def getenv (ffi-fn libc "getenv" [CCharP] CCharP)) - (def libedit (ffi-library (str "libedit." pixie.platform/so-ext))) (def readline (ffi-fn libedit "readline" [CCharP] CCharP)) (def rand (ffi-fn libc "rand" [] CInt)) @@ -1286,6 +1285,13 @@ and implements IAssociative, ILookup and IObject." @acc# (recur (next fields#) acc#))) acc#))) + 'ICounted + `(-count [self] ~(count fields)) + + 'ISeqable + `(-seq [self#] + (map #(map-entry % (get-field self# %)) + ~fields)) 'IMeta `(-with-meta [self# ~meta-gs] diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index e45788ea..6c404bf5 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -63,3 +63,11 @@ (t/assert= [[:one 1] [:two 2] [:three 3]] (reduce conj [] t1)) (t/assert= [1 2 3] (vals t1)) (t/assert= [:one :two :three] (keys t1))) + +(t/deftest icounted [] + (t/assert= (count t1) 3)) + +(t/deftest seqable [] + (t/assert= (key (first (seq t1))) :one) + (t/assert= (val (first (seq t1))) 1) + (t/assert (instance? LazySeq (seq t1)))) From 3cbcec4dec200e9053dfafd9da39744ca9b1ec6e Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 2 Nov 2015 13:35:24 +0100 Subject: [PATCH 277/349] check for correct EOF value - fix #413 --- pixie/io-blocking.pxi | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index 4ac84eb3..c6547486 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -13,6 +13,7 @@ (def fclose (ffi-fn libc "fclose" [CVoidP] CInt)) (def popen (ffi-fn libc "popen" [CCharP CCharP] CVoidP)) (def pclose (ffi-fn libc "pclose" [CVoidP] CInt)) +(def EOF -1) (deftype FileStream [fp] IInputStream @@ -85,7 +86,7 @@ ([cnt chr] (assert (integer? chr)) (let [written (write-byte fp chr)] - (if (= written 0) + (if (= written EOF) (reduced cnt) (+ cnt written))))))) From 2d8b2a18229b38e4125101d66c8515e49fa2add5 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 2 Nov 2015 15:32:45 +0100 Subject: [PATCH 278/349] add meta data support to atoms --- pixie/vm/atom.py | 18 +++++++++++++++++- tests/pixie/tests/test-stdlib.pxi | 5 +++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/pixie/vm/atom.py b/pixie/vm/atom.py index ae42ab2d..77ecd50d 100644 --- a/pixie/vm/atom.py +++ b/pixie/vm/atom.py @@ -10,8 +10,15 @@ class Atom(object.Object): def type(self): return Atom._type - def __init__(self, boxed_value): + def with_meta(self, meta): + return Atom(self._boxed_value, meta) + + def meta(self): + return self._meta + + def __init__(self, boxed_value, meta=nil): self._boxed_value = boxed_value + self._meta = meta @extend(proto._reset_BANG_, Atom) @@ -26,6 +33,15 @@ def _deref(self): assert isinstance(self, Atom) return self._boxed_value +@extend(proto._meta, Atom) +def _meta(self): + assert isinstance(self, Atom) + return self.meta() + +@extend(proto._with_meta, Atom) +def _with_meta(self, meta): + assert isinstance(self, Atom) + return self.with_meta(meta) @as_var("atom") def atom(val=nil): diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 36b6d09f..bf7f9323 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -683,11 +683,12 @@ (t/assert= 5 ((comp inc inc inc inc) 1)) (t/assert= :xyz ((comp) :xyz))) -(t/deftest test-swap-reset +(t/deftest test-atom (let [a (atom 0)] (t/assert= 1 (swap! a inc)) (t/assert= 2 (swap! a inc)) - (t/assert= 3 (reset! a 3)))) + (t/assert= 3 (reset! a 3)) + (t/assert= :bar (-> a (with-meta {:foo :bar}) meta :foo)))) (t/deftest pre-post-conds (let [f (fn ([a] {:pre [(even? a)] :post [(= % 6)]} (/ a 2)) From 215c90db9703b439ce57c2455daf790d058c074f Mon Sep 17 00:00:00 2001 From: Max Penet Date: Tue, 3 Nov 2015 11:07:09 +0100 Subject: [PATCH 279/349] add conj support to records (implements IPersistentCollection) --- pixie/stdlib.pxi | 16 ++++++++++++++++ tests/pixie/tests/test-defrecord.pxi | 7 ++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 23ac2e67..acf7ca7e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1293,6 +1293,22 @@ and implements IAssociative, ILookup and IObject." (map #(map-entry % (get-field self# %)) ~fields)) + 'IPersistentCollection + `(-conj [self# x] + (cond + (instance? MapEntry x) + (assoc self# (key x) (val x)) + (instance? PersistentVector x) + (if (= (count x) 2) + (assoc self# (first x) (second x)) + (throw + [:pixie.stdlib/InvalidArgumentException + "Vector arg to record conj must be a pair"])))) + + `(-disj [self# x] + (throw [:pixie.stdlib/NotImplementedException + "disj is not supported on defrecords"])) + 'IMeta `(-with-meta [self# ~meta-gs] (new ~nm diff --git a/tests/pixie/tests/test-defrecord.pxi b/tests/pixie/tests/test-defrecord.pxi index 6c404bf5..c2ae7a8c 100644 --- a/tests/pixie/tests/test-defrecord.pxi +++ b/tests/pixie/tests/test-defrecord.pxi @@ -14,7 +14,8 @@ (t/assert= t t) (t/assert (satisfies? IRecord t)) (t/assert (satisfies? IAssociative t)) - (t/assert (satisfies? ILookup t)))) + (t/assert (satisfies? ILookup t)) + (t/assert (satisfies? IPersistentCollection t)))) (t/deftest test-record-pred (t/assert (record? t1))) @@ -54,6 +55,10 @@ (t/assert (contains? t :two)) (t/assert (contains? t :three)))) +(t/deftest test-ipersistentcoll + (t/assert= 11 (-> t1 (conj [:one 11]) :one)) + (t/assert= 11 (-> t1 (conj (map-entry :one 11)) :one))) + (t/deftest test-record-metadata (t/assert= nil (meta t1)) (t/assert= :foo (-> t1 (with-meta :foo) meta))) From a9c0f667bb1891c7596cf589917e9c14608043f7 Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Wed, 4 Nov 2015 11:58:11 -0500 Subject: [PATCH 280/349] fix typo in metadata --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index acf7ca7e..a64a2046 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -701,7 +701,7 @@ returns true" (defn dissoc {:doc "Removes the value associated with the keys from the collection" :signatures [[m] [m & ks]] - :addded "0.1"} + :added "0.1"} ([m] m) ([m & ks] (reduce -dissoc m ks))) From 89cc9e849d679e92747ef7b809a3d828962d09ec Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Wed, 4 Nov 2015 12:59:49 -0500 Subject: [PATCH 281/349] My attempt to improve docstring for `select-keys`. --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a64a2046..b55667bb 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -918,7 +918,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (list (-key self) (-val self)))) (defn select-keys - {:doc "Produces a map with only the values in m contained in key-seq"} + {:doc "Returns a map containing only the entries of `m` where the entry's key is in `key-seq`."} [m key-seq] (with-meta (transduce From 6bf2e36e7d89e4fa7c09124f86346d229901636f Mon Sep 17 00:00:00 2001 From: Mark Reuter Date: Mon, 2 Nov 2015 13:18:49 -0600 Subject: [PATCH 282/349] Added Unchecked Math Operations Added Tests for Unchecked Math Operations Adjustments to unchecked math Made changes to the implementation of unchecked math in regards to: implementing them under their own protocol, mirrored the api of clojure, reduced implementations of the protocol to just integer and float Fixed errors in the tests that caused the build to fail --- pixie/stdlib.pxi | 38 ++++++++++++++++++++++++++++++ pixie/vm/numbers.py | 16 ++++++++++++- tests/pixie/tests/test-numbers.pxi | 4 ++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a64a2046..b0d5ec96 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -510,6 +510,30 @@ returns true" ([x y & args] (reduce -mul (-mul x y) args))) +(defn unchecked-add + {:doc "Adds the arguments, returning 0 if no arguments" + :signatures [[& args]] + :added "0.1"} + ([] 0) + ([x] x) + ([x y] (-unchecked-add x y)) + ([x y & args] + (reduce -unchecked-add (-unchecked-add x y) args))) + +(defn unchecked-subtract + ([] 0) + ([x] (-unchecked-subtract 0 x)) + ([x y] (-unchecked-subtract x y)) + ([x y & args] + (reduce -unchecked-subtract (-unchecked-subtract x y) args))) + +(defn unchecked-multiply + ([] 1) + ([x] x) + ([x y] (-unchecked-multiply x y)) + ([x y & args] + (reduce -unchecked-multiply (-unchecked-multiply x y) args))) + (defn / ([x] (-div 1 x)) ([x y] (-div x y)) @@ -610,6 +634,20 @@ returns true" [x] (- x 1)) +(defn unchecked-inc + {:doc "Increments x by one" + :signatures [[x]] + :added "0.1"} + [x] + (unchecked-add x 1)) + +(defn unchecked-dec + {:doc "Decrements x by one" + :signatures [[x]] + :added "0.1"} + [x] + (unchecked-subtract x 1)) + (defn empty? {:doc "returns true if the collection has no items, otherwise false" :signatures [[coll]] diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index 4505840a..ab80edbe 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -107,8 +107,12 @@ def ratio_read(obj): _num_eq = as_var("-num-eq")(DoublePolymorphicFn(u"-num-eq", IMath)) _num_eq.set_default_fn(wrap_fn(lambda a, b: false)) -as_var("MAX-NUMBER")(Integer(100000)) # TODO: set this to a real max number +IUncheckedMath = as_var("IUncheckedMath")(Protocol(u"IUncheckedMath")) +_unchecked_add = as_var("-unchecked-add")(DoublePolymorphicFn(u"-unchecked-add", IUncheckedMath)) +_unchecked_subtract = as_var("-unchecked-subtract")(DoublePolymorphicFn(u"-unchecked-subtract", IUncheckedMath)) +_unchecked_multiply = as_var("-unchecked-multiply")(DoublePolymorphicFn(u"-unchecked-multiply", IUncheckedMath)) +as_var("MAX-NUMBER")(Integer(100000)) # TODO: set this to a real max number num_op_template = """@extend({pfn}, {ty1}._type, {ty2}._type) def {pfn}_{ty1}_{ty2}(a, b): @@ -167,6 +171,16 @@ def define_num_ops(): define_num_ops() +def define_unchecked_num_ops(): + # maybe define get_val() instead of using tuples? + num_classes = [(Integer, "int_val"), (Float, "float_val")] + for (c1, conv1) in num_classes: + for (c2, conv2) in num_classes: + for (op, sym) in [("_unchecked_add", "+"), ("_unchecked_subtract", "-"), ("_unchecked_multiply", "*")]: + extend_num_op(op, c1, c2, conv1, sym, conv2) + +define_unchecked_num_ops() + bigint_ops_tmpl = """@extend({pfn}, {ty1}._type, {ty2}._type) def _{pfn}_{ty1}_{ty2}(a, b): assert isinstance(a, {ty1}) and isinstance(b, {ty2}) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 28ab8b92..270ba742 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -73,3 +73,7 @@ (t/assert (-num-eq 1000000000000000000000N (* 10000000 10000000 10000000)))) + +(t/deftest test-wrap-around + (t/assert= Integer (type (unchecked-add 9223372036854775807 1))) + (t/assert (-num-eq -9223372036854775808 (unchecked-add 9223372036854775807 1)))) From b7db173bf3eeefa8c6e43eab8390c66c0293e168 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Fri, 6 Nov 2015 16:40:56 +0100 Subject: [PATCH 283/349] add pixie.walk --- pixie/walk.pxi | 113 ++++++++++++++++++++++++++++++++ tests/pixie/tests/test-walk.pxi | 59 +++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 pixie/walk.pxi create mode 100644 tests/pixie/tests/test-walk.pxi diff --git a/pixie/walk.pxi b/pixie/walk.pxi new file mode 100644 index 00000000..cef60c93 --- /dev/null +++ b/pixie/walk.pxi @@ -0,0 +1,113 @@ +(ns pixie.walk) + +(defprotocol IWalk + (-walk [x f])) + +(extend-protocol IWalk + PersistentList + (-walk [x f] + (apply list (map f x))) + + Cons + (-walk [x f] + (cons (f (first x)) (map f (next x)))) + + IMapEntry + (-walk [x f] + (map-entry (f (key x)) (f (val x)))) + + PersistentVector + (-walk [x f] + (into [] (map f) x)) + + PersistentHashSet + (-walk [x f] + (into #{} (map f) x)) + + PersistentHashMap + (-walk [x f] + (into {} (map f) x)) + + IRecord + (-walk [x f] + (into x (map f) x)) + + ISeqable + (-walk [x f] + (map f x)) + + IObject + (-walk [x f] x) + + Nil + (-walk [x f] nil)) + +(defn walk + {:doc "Traverses form, an arbitrary data structure. f is a + function. Applies f to each element of form, building up a data + structure of the same type. Recognizes all Pixie data + structures. Consumes seqs." + :signatures [[f x]] + :added "0.1"} + [f x] + (-walk x f)) + +(defn postwalk + {:doc "Performs a depth-first, post-order traversal of form. Calls f on + each sub-form, uses f's return value in place of the original. + Recognizes all Pixie data structures." + :signatures [[f x]] + :added "0.1"} + [f x] + (f (walk (partial postwalk f) x))) + +(defn prewalk + {:doc "Like postwalk, but does pre-order traversal." + :added "0.1"} + [f x] + (walk (partial prewalk f) (f x))) + +(defn prewalk-replace + {:doc "Recursively transforms form by replacing + keys in smap with their values. Like `replace` but works on + any data structure. Does replacement at the root of the tree + first." + :signatures [[f x]] + :added "0.1"} + [smap x] + (prewalk (fn [x] (if (contains? smap x) (smap x) x)) x)) + +(defn postwalk-replace + {:doc "Recursively transforms form by replacing keys in smap with + their values. Like `replace` but works on any data structure. + Does replacement at the leaves of the tree first." + :signatures [[smap x]] + :added "0.1"} + [smap x] + (postwalk (fn [x] (if (contains? smap x) (smap x) x)) x)) + +(defn keywordize-keys + {:doc "Recursively transforms all map keys from strings to keywords." + :signatures [[m]] + :added "0.1"} + [m] + (let [f (fn [[k v]] (if (string? k) [(keyword k) v] [k v]))] + ;; only apply to maps + (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) + +(defn stringify-keys + {:doc "Recursively transforms all map keys from keywords to strings." + :signatures [[m]] + :added "0.1"} + [m] + (let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))] + ;; only apply to maps + (postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) + +(defn macroexpand-all + {:doc "Recursively performs all possible macroexpansions in + form. For development use only." + :added "0.1" + :signatures [[x]]} + [x] + (prewalk (fn [x] (if (seq? x) (macroexpand-1 x) x)) x)) diff --git a/tests/pixie/tests/test-walk.pxi b/tests/pixie/tests/test-walk.pxi new file mode 100644 index 00000000..d7a0aa1a --- /dev/null +++ b/tests/pixie/tests/test-walk.pxi @@ -0,0 +1,59 @@ +(ns pixie.tests.test-walk + (:require [pixie.walk :as w] + [pixie.test :as t])) + +(t/deftest t-prewalk-replace + (t/assert (= (w/prewalk-replace {:a :b} [:a {:a :a} (list 3 :c :a)]) + [:b {:b :b} (list 3 :c :b)]))) + +(t/deftest t-postwalk-replace + (t/assert (= (w/postwalk-replace {:a :b} [:a {:a :a} (list 3 :c :a)]) + [:b {:b :b} (list 3 :c :b)]))) + +(t/deftest t-prewalk-order + (t/assert (= (let [a (atom [])] + (w/prewalk (fn [form] (swap! a conj form) form) + [1 2 {:a 3} (list 4 [5])]) + @a) + [[1 2 {:a 3} (list 4 [5])] + 1 2 {:a 3} [:a 3] :a 3 (list 4 [5]) + 4 [5] 5]))) + +(t/deftest t-postwalk-order + (t/assert (= (let [a (atom [])] + (w/postwalk (fn [form] (swap! a conj form) form) + [1 2 {:a 3} (list 4 [5])]) + @a) + [1 2 + :a 3 [:a 3] {:a 3} + 4 5 [5] (list 4 [5]) + [1 2 {:a 3} (list 4 [5])]]))) + +(defrecord Foo [a b c]) + +(t/deftest walk + "Checks that walk returns the correct result and type of collection" + (let [colls ['(1 2 3) + [1 2 3] + #{1 2 3} + {:a 1, :b 2, :c 3} + (->Foo 1 2 3)]] + (doseq [c colls] + (let [walked (w/walk identity c)] + (t/assert (= c walked)) + (t/assert (= (type c) (type walked))) + (if (or (map? c) + (record? c)) + (do + (t/assert (= (reduce + (vals (w/walk + #(map-entry + (key %) + (inc (val %))) + c))) + (reduce + (map (comp inc val) c))))) + (t/assert (= (reduce + (w/walk inc c)) + (reduce + (map inc c))))))))) + +(t/deftest t-stringify-keys + (t/assert (= (w/stringify-keys {:a 1, nil {:b 2 :c 3}, :d 4}) + {"a" 1, nil {"b" 2 "c" 3}, "d" 4}))) From 7c09904cb9039f37ab836d9b663122ccaeba67a0 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 11 Nov 2015 14:08:47 +0100 Subject: [PATCH 284/349] add csp/timout channel --- pixie/channels.pxi | 20 ++++++++++++++++++++ pixie/csp.pxi | 1 + tests/pixie/tests/test-csp.pxi | 15 +++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/pixie/channels.pxi b/pixie/channels.pxi index f930bf17..1f8067df 100644 --- a/pixie/channels.pxi +++ b/pixie/channels.pxi @@ -1,5 +1,7 @@ (ns pixie.channels (:require [pixie.stacklets :as st] + [pixie.uv :as uv] + [pixie.ffi :as ffi] [pixie.buffers :as b])) (defprotocol ICancelable @@ -143,6 +145,24 @@ false 0))))) +(defn timeout + "Returns a channel that will close after given delay in ms" + [ms] + (let [ch (chan) + timer (uv/uv_timer_t) + cb (atom nil)] + (reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb + (fn [handle] + (try + (-close! ch) + (uv/uv_timer_stop timer) + (-dispose! @cb) + (catch ex + (println ex)))))) + (uv/uv_timer_init (uv/uv_default_loop) timer) + (uv/uv_timer_start timer @cb ms 0) + ch)) + (deftype AltHandler [atm f] ICancelable (-canceled? [this] diff --git a/pixie/csp.pxi b/pixie/csp.pxi index 94ca90d9..32c96c8c 100644 --- a/pixie/csp.pxi +++ b/pixie/csp.pxi @@ -4,6 +4,7 @@ [pixie.channels :as chans])) (def chan chans/chan) +(def timeout chans/timeout) (defn close! "Closes the channel, future writes will be rejected, future reads will diff --git a/tests/pixie/tests/test-csp.pxi b/tests/pixie/tests/test-csp.pxi index 0b4cc396..94a241bd 100644 --- a/tests/pixie/tests/test-csp.pxi +++ b/tests/pixie/tests/test-csp.pxi @@ -31,3 +31,18 @@ (assert= (alts! [c] :default 42) [:default 42]) (>! c 1) (assert= (alts! [c] :default 42) [c 1]))) + +(deftest test-timeout-channel + (let [ts [(timeout 300) + (timeout 200) + (timeout 100)]] + (-> (go + (loop [ts (set ts) + res []] + (if (empty? ts) + res + (let [[p _] (alts! ts)] + (recur (set (remove #{p} ts)) + (conj res p)))))) + Date: Thu, 12 Nov 2015 19:37:41 +0000 Subject: [PATCH 285/349] Improves the performance of range dramatically Calling seq on range produced a lazy sequence which has significant overhead. Now we give Range -first and -next properties, returning start and a new Range respectively. `last` is now more efficient on IIndexed collections --- pixie/stdlib.pxi | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 7d16a0c6..afd7b09e 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -878,9 +878,18 @@ If further arguments are passed, invokes the method named by symbol, passing the :signatures [[coll]] :added "0.1"} [coll] - (if (next coll) - (recur (next coll)) - (first coll))) + (cond + (satisfies? IIndexed coll) + (when (pos? (count coll)) + (nth coll (dec (count coll)))) + + (satisfies? ISeq coll) + (if (next coll) + (recur (next coll)) + (first coll)) + + (satisfies? ISeqable coll) + (recur (seq coll)))) (defn butlast {:doc "Returns all elements but the last from the collection." @@ -1911,18 +1920,26 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (if (cmp val stop) val not-found))) + ISeq + (-first [this] + (when (not= start stop) + start)) + (-next [this] + (let [i (+ step start)] + (when (or (and (> step 0) (< i stop)) + (and (< step 0) (> i stop)) + (and (= step 0))) + (range i stop step)))) ISeqable - (-seq [self] - (when (or (and (> step 0) (< start stop)) - (and (< step 0) (> start stop))) - (cons start (lazy-seq* #(range (+ start step) stop step)))))) + (-seq [self] self)) (extend -str Range (fn [v] - (-str (seq v)))) + (str "(" (transduce (interpose " ") string-builder v) ")"))) + (extend -repr Range (fn [v] - (-repr (seq v)))) + (str "(" (transduce (interpose " ") string-builder v) ")"))) (defn range {:doc "Returns a range of numbers." From b605646ca75cb43ea81f74970bca8a3ba8a4b9e8 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Fri, 13 Nov 2015 16:42:02 +0100 Subject: [PATCH 286/349] add memoize --- pixie/stdlib.pxi | 17 +++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 4 ++++ 2 files changed, 21 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index b0d5ec96..100fff2c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2974,3 +2974,20 @@ ex: (vary-meta x assoc :foo 42)" :added "0.1"} [x f & args] (with-meta x (apply f (meta x) args))) + +(defn memoize + {:doc "Returns a memoized version of function f. The first call will + realize the return value and subsequent calls get the same value + from its cache." + :signatures [[f]] + :added "0.1"} + [f] + (let [cache (atom {})] + (fn [& args] + (let [argsv (vec args) + val (get @cache argsv ::not-found)] + (if (= val ::not-found) + (let [ret (apply f args)] + (swap! cache assoc argsv ret) + ret) + val))))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index bf7f9323..cb10ebeb 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -726,3 +726,7 @@ (t/deftest test-vary-meta (t/assert= 42 (-> {} (vary-meta assoc :foo 42) meta :foo))) + +(t/deftest test-memoize + (let [f (memoize rand)] + (t/assert= (f) (f)))) From 721cdf19afae4eb62276a912f6764c63bc6302ac Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sat, 14 Nov 2015 00:42:40 +0000 Subject: [PATCH 287/349] fixes (rand-int 0) case --- pixie/stdlib.pxi | 4 +++- tests/pixie/tests/test-stdlib.pxi | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 7d16a0c6..a1604eb2 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -554,7 +554,9 @@ returns true" (defn rand-int {:doc "random integer between 0 (inclusive) and n (exclusive)"} [n] - (rem (rand) n)) + (if (zero? n) + 0 + (rem (rand) n))) (defn = {:doc "Returns true if all the arguments are equivalent. Otherwise, returns false. Uses diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 8334d9e0..968c7f1e 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -330,7 +330,9 @@ (t/deftest test-rand-int (let [vs (repeatedly 10 #(rand-int 4))] - (t/assert (every? #(and (>= % 0) (< % 4)) vs)))) + (t/assert (every? #(and (>= % 0) (< % 4)) vs))) + (let [vs (repeatedly 10 #(rand-int 0))] + (t/assert (every? zero? vs)))) (t/deftest test-some (t/assert= (some even? [2 4 6 8]) true) From a27d12cfdb2a3fe53eba8fa03c991afd500e5c8d Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Mon, 16 Nov 2015 10:38:16 -0500 Subject: [PATCH 288/349] signature was missing from `into` :signatures --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 71853016..eab2357f 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -197,7 +197,7 @@ (-satisfies? p x)))) (def into (fn ^{:doc "Add the elements of `from` to the collection `to`." - :signatures [[to from]] + :signatures [[to from] [to xform from]] :added "0.1"} ([to from] (if (satisfies? IToTransient to) From ad325efdabfe85b6d63871f2d4a3a68023f3b040 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 27 Nov 2015 10:17:28 +0000 Subject: [PATCH 289/349] line-reader accepts a non buffered stream We create a buffered stream with a buffer size of one. --- pixie/io.pxi | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pixie/io.pxi b/pixie/io.pxi index 4143386e..16ec14be 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -87,6 +87,10 @@ (instance? BufferedInputStream input-stream) (-> input-stream ->LineReader) + + (satisfies? IInputStream input-stream) + (-> input-stream (buffered-input-stream 1) ->LineReader) + :else (throw [::Exception "Expected a LineReader, UTF8InputStream, or BufferedInputStream"]))) From 3d0af3fd5e3eeb99801b5a60a65d315390caf2cc Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Mon, 30 Nov 2015 18:05:44 -0600 Subject: [PATCH 290/349] Adding a lot of math constants from math.h. --- pixie/math.pxi | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/pixie/math.pxi b/pixie/math.pxi index 47d45cd0..c6500c81 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -23,4 +23,19 @@ (i/defcfn ceil) (i/defcfn fabs) (i/defcfn floor) - (i/defcfn fmod)) + (i/defcfn fmod) + + (i/defconst M_E) ; base of natural logarithm, e + (i/defconst M_LOG2E) ; log2(e) + (i/defconst M_LOG10E) ; log10(e) + (i/defconst M_LN2) ; ln(2) + (i/defconst M_LN10) ; ln(10) + (i/defconst M_PI) ; pi + (i/defconst M_PI_2) ; pi / 2 + (i/defconst M_PI_4) ; pi / 4 + (i/defconst M_1_PI) ; 1 / pi + (i/defconst M_2_PI) ; 2 / pi + (i/defconst M_2_SQRTPI) ; 2 / sqrt(pi) + (i/defconst M_SQRT2) ; sqrt(2) + (i/defconst M_SQRT1_2)) ; sqrt(1/2) + From 2290fdb3c87802cbd263ee00602c2b6cde3d8d7b Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 3 Dec 2015 11:33:28 -0600 Subject: [PATCH 291/349] Adding tan. --- pixie/math.pxi | 1 + 1 file changed, 1 insertion(+) diff --git a/pixie/math.pxi b/pixie/math.pxi index c6500c81..644cf47c 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -12,6 +12,7 @@ (i/defcfn cosh) (i/defcfn sin) (i/defcfn sinh) + (i/defcfn tan) (i/defcfn tanh) (i/defcfn exp) (i/defcfn ldexp) From 11c5fee569cd2ea6301bb8c5e39f88528dcf46ed Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 3 Dec 2015 11:36:13 -0600 Subject: [PATCH 292/349] Grouping the trig functions more normally. --- pixie/math.pxi | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/pixie/math.pxi b/pixie/math.pxi index 644cf47c..7f7faf3b 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -4,16 +4,19 @@ (i/with-config {:library "m" :cxx-flags ["-lm"] :includes ["math.h"]} - (i/defcfn acos) + (i/defcfn sin) + (i/defcfn cos) + (i/defcfn tan) + (i/defcfn asin) + (i/defcfn acos) (i/defcfn atan) - (i/defcfn atan2) - (i/defcfn cos) - (i/defcfn cosh) - (i/defcfn sin) + (i/defcfn atan2) ; Arc tangent function of two variables. + (i/defcfn sinh) - (i/defcfn tan) + (i/defcfn cosh) (i/defcfn tanh) + (i/defcfn exp) (i/defcfn ldexp) (i/defcfn log) From 64cb0f3a8d88c210ed964077028bb7967ea762f5 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 3 Dec 2015 11:37:45 -0600 Subject: [PATCH 293/349] Adding asinh, acosh, and atanh. --- pixie/math.pxi | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pixie/math.pxi b/pixie/math.pxi index 7f7faf3b..313dd904 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -17,6 +17,10 @@ (i/defcfn cosh) (i/defcfn tanh) + (i/defcfn asinh) + (i/defcfn acosh) + (i/defcfn atanh) + (i/defcfn exp) (i/defcfn ldexp) (i/defcfn log) From f991686dae2dc8334b4215ac9df27970ca5ba647 Mon Sep 17 00:00:00 2001 From: Christopher Mark Gore Date: Thu, 3 Dec 2015 13:58:01 -0600 Subject: [PATCH 294/349] Adding log2, log1p, logb, and ilogb. --- pixie/math.pxi | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/pixie/math.pxi b/pixie/math.pxi index 313dd904..15a778c4 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -23,9 +23,15 @@ (i/defcfn exp) (i/defcfn ldexp) + (i/defcfn log) + (i/defcfn log2) (i/defcfn log10) - ;(i/defcfn modf) ;; Needs ffi support + (i/defcfn log1p) + (i/defcfn logb) + (i/defcfn ilogb) + + ;; (i/defcfn modf) ;; Needs ffi support (i/defcfn pow) (i/defcfn sqrt) (i/defcfn ceil) From b952476ac767f8aa9f6c45c9f58a916f43ecea67 Mon Sep 17 00:00:00 2001 From: Herwig Hochleitner Date: Fri, 4 Dec 2015 13:13:56 +0100 Subject: [PATCH 295/349] Improve tempdir usage in ffi-infer - Make use of mkdtemp to create unique temporary directories per call to run-infer - If $TMPDIR is set, use it instead of /tmp - Remove temp files after finishing --- pixie/ffi-infer.pxi | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 9f13ac74..51bfa34a 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -178,24 +178,35 @@ return 0; `(def ~(symbol name) ~(callback-type of-type false))) +(def mkdtemp (ffi-fn libc "mkdtemp" [CCharP] CCharP)) +(def unlink (ffi-fn libc "unlink" [CCharP] CInt)) +(def rmdir (ffi-fn libc "rmdir" [CCharP] CInt)) +(def tempdir-template (str (or (getenv "TMPDIR") "/tmp") + "/ffiXXXXXX")) (defn run-infer [config cmds] - (io/spit "/tmp/tmp.cpp" (str (start-string) - (apply str (map emit-infer-code - cmds)) - (end-string))) - (println @load-paths) - (let [cmd-str (str "c++ " - (apply str (interpose " " pixie.platform/c-flags)) - " /tmp/tmp.cpp " - (apply str (map (fn [x] ( str " -I " x " ")) - @load-paths)) - (apply str " " (interpose " " (:cxx-flags *config*))) - " -o /tmp/a.out && /tmp/a.out") - _ (println cmd-str) - result (read-string (io/run-command cmd-str)) - gen (vec (map generate-code cmds result))] - `(do ~@gen))) + (let [tempdir (mkdtemp tempdir-template) + infile (str tempdir "/ffi.cpp") + outfile (str tempdir "/ffi.out")] + (io/spit infile (str (start-string) + (apply str (map emit-infer-code + cmds)) + (end-string))) + (println @load-paths) + (let [cmd-str (str "c++ " + (apply str (interpose " " pixie.platform/c-flags)) + " " infile " " + (apply str (map (fn [x] ( str " -I " x " ")) + @load-paths)) + (apply str " " (interpose " " (:cxx-flags *config*))) + " -o " outfile " && " outfile) + _ (println cmd-str) + result (read-string (io/run-command cmd-str)) + gen (vec (map generate-code cmds result))] + (unlink infile) + (unlink outfile) + (rmdir tempdir) + `(do ~@gen)))) (defn full-lib-name [library-name] (if (= library-name "c") From d758bb8d5ac6a6763f4af12c3982c57687d3870e Mon Sep 17 00:00:00 2001 From: Pauli Jaakkola Date: Fri, 4 Dec 2015 21:42:13 +0200 Subject: [PATCH 296/349] Add CFloat ffi type. --- pixie/ffi-infer.pxi | 11 +++++++---- pixie/vm/libs/ffi.py | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 9f13ac74..efa3f431 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -104,11 +104,14 @@ return 0; (= (:type of-type) :function) (callback-type of-type in-struct?) :else 'pixie.stdlib/CVoidP)) +(def float-types {32 'pixie.stdlib/CFloat + 64 'pixie.stdlib/CDouble}) + (defmethod edn-to-ctype :float - [{:keys [size]} _] - (cond - (= size 8) 'pixie.stdlib/CDouble - :else (assert false "unknown type"))) + [{:keys [size] :as tp} _] + (let [tp-found (get float-types (* 8 size))] + (assert tp-found (str "No type found for " tp)) + tp-found)) (defmethod edn-to-ctype :void [_ _] diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 193b56ce..9cc0d348 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -350,6 +350,26 @@ def ffi_type(self): return clibffi.cast_type_to_ffitype(rffi.INT) CInt() +class CFloat(CType): + def __init__(self): + CType.__init__(self, u"pixie.stdlib.CFloat") + + def ffi_get_value(self, ptr): + casted = rffi.cast(rffi.FLOATP, ptr) + return Float(rffi.cast(rffi.DOUBLE, casted[0])) + + def ffi_set_value(self, ptr, val): + val = to_float(val) + casted = rffi.cast(rffi.FLOATP, ptr) + casted[0] = rffi.cast(rffi.FLOAT, val.float_val()) + + def ffi_size(self): + return rffi.sizeof(rffi.FLOAT) + + def ffi_type(self): + return clibffi.cast_type_to_ffitype(rffi.FLOAT) +CFloat() + class CDouble(CType): def __init__(self): CType.__init__(self, u"pixie.stdlib.CDouble") From cee88a2513999c10fa039d7741e3986d61f300f8 Mon Sep 17 00:00:00 2001 From: Chris Shea Date: Fri, 4 Dec 2015 16:23:38 -0500 Subject: [PATCH 297/349] Normalize docstrings in stdlib Use present tense, capitalization, and punctuation in docstrings. --- pixie/stdlib.pxi | 128 +++++++++++++++++++++++------------------------ 1 file changed, 64 insertions(+), 64 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index eab2357f..ec1ef49c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -47,7 +47,7 @@ x)) (def conj - (fn ^{:doc "Adds elements to the collection. Elements are added to the end except in the case of Cons lists" + (fn ^{:doc "Adds elements to the collection. Elements are added to the end except in the case of Cons lists." :signatures [[] [coll] [coll item] [coll item & args]] :added "0.1"} conj @@ -58,7 +58,7 @@ (reduce -conj (-conj coll item) args)))) (def conj! - (fn ^{:doc "Adds elements to the transient collection. Elements are added to the end except in the case of Cons lists" + (fn ^{:doc "Adds elements to the transient collection. Elements are added to the end except in the case of Cons lists." :signatures [[] [coll] [coll item] [coll item & args]] :added "0.1"} conj! @@ -96,7 +96,7 @@ ([coll] (-pop coll)))) (def push - (fn ^{:doc "Push an element on to a stack." + (fn ^{:doc "Pushes an element on to a stack." :signatures [[] [coll] [coll item] [coll item & args]] :added "0.1"} push @@ -110,7 +110,7 @@ ([coll] (-pop! coll)))) (def push! - (fn ^{:doc "Push an element on to a transient stack." + (fn ^{:doc "Pushes an element on to a transient stack." :signatures [[] [coll] [coll item] [coll item & args]] :added "0.1"} push! @@ -134,7 +134,7 @@ result (-reduce coll f init)] (f result))))) -(def map (fn ^{:doc "map - creates a transducer that applies f to every input element" +(def map (fn ^{:doc "Creates a transducer that applies f to every input element." :signatures [[f] [f coll]] :added "0.1"} map @@ -246,7 +246,7 @@ (reduce rrf result input)))))) (def mapcat - (fn ^{:doc "Maps f over the elements of coll and concatenates the result" + (fn ^{:doc "Maps f over the elements of coll and concatenates the result." :added "0.1"} mapcat ([f] @@ -338,7 +338,7 @@ ([state itm] (update-hash-unordered! state itm)))) (def string-builder - (fn ^{:doc "Creates a reducing function that builds a string based on calling str on the transduced collection"} + (fn ^{:doc "Creates a reducing function that builds a string based on calling str on the transduced collection."} ([] (-string-builder)) ([sb] (str sb)) ([sb item] (conj! sb item)))) @@ -471,7 +471,7 @@ (set-macro! defmacro) (defmacro defn- - {:doc "Define a new non-public function. Otherwise the same as defn" + {:doc "Define a new non-public function. Otherwise the same as defn." :signatures [[nm doc? meta? & body]] :added "0.1"} [nm & rest] @@ -480,14 +480,14 @@ (defn not {:doc "Inverts the input, if a truthy value is supplied, returns false, otherwise -returns true" +returns true." :signatures [[x]] :added "0.1"} [x] (if x false true)) (defn + - {:doc "Adds the arguments, returning 0 if no arguments" + {:doc "Adds the arguments, returning 0 if no arguments." :signatures [[& args]] :added "0.1"} ([] 0) @@ -511,7 +511,7 @@ returns true" (reduce -mul (-mul x y) args))) (defn unchecked-add - {:doc "Adds the arguments, returning 0 if no arguments" + {:doc "Adds the arguments, returning 0 if no arguments." :signatures [[& args]] :added "0.1"} ([] 0) @@ -547,7 +547,7 @@ returns true" (-rem num div)) (defn rand-int - {:doc "random integer between 0 (inclusive) and n (exclusive)"} + {:doc "Returns a random integer between 0 (inclusive) and n (exclusive)."} [n] (if (zero? n) 0 @@ -602,56 +602,56 @@ returns true" false))) (defn pos? - {:doc "Returns true if x is greater than zero" + {:doc "Returns true if x is greater than zero." :signatures [[x]] :added "0.1"} [x] (> x 0)) (defn neg? - {:doc "Returns true if x is less than zero" + {:doc "Returns true if x is less than zero." :signatures [[x]] :added "0.1"} [x] (< x 0)) (defn zero? - {:doc "Returns true if x is equal to zero" + {:doc "Returns true if x is equal to zero." :signatures [[x]] :added "0.1"} [x] (= x 0)) (defn inc - {:doc "Increments x by one" + {:doc "Increments x by one." :signatures [[x]] :added "0.1"} [x] (+ x 1)) (defn dec - {:doc "Decrements x by one" + {:doc "Decrements x by one." :signatures [[x]] :added "0.1"} [x] (- x 1)) (defn unchecked-inc - {:doc "Increments x by one" + {:doc "Increments x by one." :signatures [[x]] :added "0.1"} [x] (unchecked-add x 1)) (defn unchecked-dec - {:doc "Decrements x by one" + {:doc "Decrements x by one." :signatures [[x]] :added "0.1"} [x] (unchecked-subtract x 1)) (defn empty? - {:doc "returns true if the collection has no items, otherwise false" + {:doc "Returns true if the collection has no items, otherwise false." :signatures [[coll]] :added "0.1"} [coll] @@ -660,21 +660,21 @@ returns true" (not (seq coll)))) (defn not-empty? - {:doc "returns true if the collection has items, otherwise false" + {:doc "Returns true if the collection has items, otherwise false." :signatures [[coll]] :added "0.1"} [coll] (if (seq coll) true false)) (defn even? - {:doc "Returns true if n is even" + {:doc "Returns true if n is even." :signatures [[n]] :added "0.1"} [n] (zero? (rem n 2))) (defn odd? - {:doc "Returns true of n is odd" + {:doc "Returns true of n is odd." :signatures [[n]] :added "0.1"} [n] @@ -682,7 +682,7 @@ returns true" (defn nth {:doc "Returns the element at the idx. If the index is not found it will return an error. - However, if you specify a not-found parameter, it will substitute that instead" + However, if you specify a not-found parameter, it will substitute that instead." :signatures [[coll idx] [coll idx not-found]] :added "0.1"} ([coll idx] (-nth coll idx)) @@ -729,7 +729,7 @@ returns true" (first (next (next (next coll)))))) (defn assoc - {:doc "Associates the key with the value in the collection" + {:doc "Associates the key with the value in the collection." :signatures [[m] [m k v] [m k v & kvs]] :added "0.1"} ([m] m) @@ -739,7 +739,7 @@ returns true" (apply assoc (-assoc m k v) rest))) (defn dissoc - {:doc "Removes the value associated with the keys from the collection" + {:doc "Removes the value associated with the keys from the collection." :signatures [[m] [m & ks]] :added "0.1"} ([m] m) @@ -763,7 +763,7 @@ there's a value associated with the key. Use `some` for checking for values." (-contains-key coll key)) (defn hash-set [& args] - {:doc "Creates a hash-set from the arguments of the function" + {:doc "Creates a hash-set from the arguments of the function." :added "0.1"} (set args)) @@ -797,7 +797,7 @@ there's a value associated with the key. Use `some` for checking for values." (apply (transduce comp (apply list f1 f2 f3 fs)) args)))) (defmacro cond - {:doc "Checks if any of the tests is truthy, if so, stops and returns the value of the corresponding body" + {:doc "Checks if any of the tests is truthy, if so, stops and returns the value of the corresponding body." :signatures [[] [test then & clauses]] :added "0.1"} ([] nil) @@ -915,8 +915,8 @@ If further arguments are passed, invokes the method named by symbol, passing the (seq res)))) (defn complement - {:doc "Given a function, return a new function which takes the same arguments - but returns the opposite truth value"} + {:doc "Given a function, returns a new function which takes the same arguments + but returns the opposite truth value."} [f] (assert (fn? f) "Complement must be passed a function") (fn @@ -926,7 +926,7 @@ If further arguments are passed, invokes the method named by symbol, passing the ([x y & more] (not (apply f x y more))))) (defn constantly [x] - {:doc "Return a function that always returns x, no matter what it is called with." + {:doc "Returns a function that always returns x, no matter what it is called with." :examples [["(let [f (constantly :me)] [(f 1) (f \"foo\") (f :abc) (f nil)])" nil [:me :me :me :me]]]} (fn [& _] x)) @@ -977,7 +977,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (meta m))) (defn keys - {:doc "If called with no arguments returns a transducer that will extract the key from each map entry. If passed + {:doc "If called with no arguments, returns a transducer that will extract the key from each map entry. If passed a collection, will assume that it is a hashmap and return a vector of all keys from the collection." :signatures [[] [coll]] :added "0.1"} @@ -986,7 +986,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (transduce (map key) conj! m))) (defn vals - {:doc "If called with no arguments returns a transducer that will extract the key from each map entry. If passed + {:doc "If called with no arguments, returns a transducer that will extract the key from each map entry. If passed a collection, will assume that it is a hashmap and return a vector of all keys from the collection." :signatures [[] [coll]] :added "0.1"} @@ -1078,7 +1078,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (extend -repr Symbol -str) (defn get - {:doc "Get an element from a collection implementing ILookup, return nil or the default value if not found." + {:doc "Gets an element from a collection implementing ILookup. Returns nil or the default value if not found." :added "0.1"} ([mp k] (get mp k nil)) @@ -1095,7 +1095,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (defn get-in - {:doc "Get a value from a nested collection at the \"path\" given by the keys." + {:doc "Gets a value from a nested collection at the \"path\" given by the keys." :examples [["(get-in {:a [{:b 42}]} [:a 0 :b])" nil 42]] :signatures [[m ks] [m ks not-found]] :added "0.1"} @@ -1113,7 +1113,7 @@ If further arguments are passed, invokes the method named by symbol, passing the m)))) (defn assoc-in - {:doc "Associate a value in a nested collection given by the path. + {:doc "Associates a value in a nested collection given by the path. Creates new maps if the keys are not present." :examples [["(assoc-in {} [:a :b :c] 42)" nil {:a {:b {:c 42}}}]] @@ -1127,7 +1127,7 @@ Creates new maps if the keys are not present." (assoc m k v))))) (defn update-in - {:doc "Update a value in a nested collection." + {:doc "Updates a value in a nested collection." :examples [["(update-in {:a {:b {:c 41}}} [:a :b :c] inc)" nil {:a {:b {:c 42}}}]] :added "0.1"} [m ks f & args] @@ -1154,7 +1154,7 @@ Creates new maps if the keys are not present." (str "Assert failed: " ~msg)])))) (defmacro resolve - {:doc "Resolve the var associated with the symbol in the current namespace." + {:doc "Resolves the var associated with the symbol in the current namespace." :added "0.1"} [sym] `(resolve-in (this-ns-name) ~sym)) @@ -1202,7 +1202,7 @@ Creates new maps if the keys are not present." (instance? Protocol x)) (defmacro deftype - {:doc "Define a custom type." + {:doc "Defines a custom type." :examples [["(deftype Person [name] IObject (-str [self] @@ -1291,7 +1291,7 @@ Creates new maps if the keys are not present." result)) (defmacro defrecord - {:doc "Define a record type. + {:doc "Defines a record type. Similar to `deftype`, but supports construction from a map using `map->Type` and implements IAssociative, ILookup and IObject." @@ -1511,7 +1511,7 @@ The new value is thus `(apply f current-value-of-atom args)`." (identical? x nil)) (defn some? [x] - {:doc "true if x is not nil"} + {:doc "Returns true if x is not nil."} (not (nil? x))) (defn fnil [f else] @@ -1528,7 +1528,7 @@ The new value is thus `(apply f current-value-of-atom args)`." ~(nth binding 1 nil))) (defmacro dotimes - {:doc "Execute the expressions in the body n times." + {:doc "Executes the expressions in the body n times." :examples [["(dotimes [i 3] (println i))" "1\n2\n3\n"]] :signatures [[[i n] & body]] :added "0.1"} @@ -1542,7 +1542,7 @@ The new value is thus `(apply f current-value-of-atom args)`." (recur (inc ~b)))))))) (defmacro and - {:doc "Check if the given expressions return truthy values, returning the last, or false." + {:doc "Checks if the given expressions return truthy values, returning the last, or false." :examples [["(and true false)" nil false] ["(and 1 2 3)" nil 3] ["(and 1 false 3)" nil false]] @@ -1604,7 +1604,7 @@ The new value is thus `(apply f current-value-of-atom args)`." false)) (defn nnext - {:doc "Equivalent to (next (next coll))" + {:doc "Equivalent to (next (next coll))." :added "0.1"} [coll] (next (next coll))) @@ -1624,7 +1624,7 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn ith {:doc "Returns the ith element of the collection, negative values count from the end. If an index is out of bounds, will throw an Index out of Range exception. - However, if you specify a not-found parameter, it will substitute that instead" + However, if you specify a not-found parameter, it will substitute that instead." :signatures [[coll i] [coll idx not-found]] :added "0.1"} ([coll i] @@ -1688,7 +1688,7 @@ The new value is thus `(apply f current-value-of-atom args)`." (defmacro while {:doc "Repeatedly executes body while test expression is true. Presumes - some side-effect will cause test to become false/nil. Returns nil" + some side-effect will cause test to become false/nil. Returns nil." :added "0.1"} [test & body] `(loop [] @@ -1761,7 +1761,7 @@ The new value is thus `(apply f current-value-of-atom args)`." ;; TODO: use a transient map in the future (defn frequencies - {:doc "Returns a map with distinct elements as keys and the number of occurences as values" + {:doc "Returns a map with distinct elements as keys and the number of occurences as values." :added "0.1"} [coll] (reduce (fn [res elem] @@ -2114,7 +2114,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} self)))) (defn filter - {:doc "Filter the collection for elements matching the predicate." + {:doc "Filters the collection for elements matching the predicate." :signatures [[pred] [pred coll]] :added "0.1"} ([pred] @@ -2260,7 +2260,7 @@ user => (refer 'pixie.string :exclude '(substring))" (reduce merge2 (first maps) (next maps))))) (defn every? - {:doc "Check if every element of the collection satisfies the predicate." + {:doc "Checks if every element of the collection satisfies the predicate." :added "0.1"} [pred coll] (cond @@ -2377,7 +2377,7 @@ If the number of arguments is even and no clause matches, throws an exception." (defmacro defmulti - {:doc "Define a multimethod, which dispatches to its methods based on dispatch-fn." + {:doc "Defines a multimethod, which dispatches to its methods based on dispatch-fn." :examples [["(defmulti greet first)"] ["(defmethod greet :hi [[_ name]] (str \"Hi, \" name \"!\"))"] ["(defmethod greet :hello [[_ name]] (str \"Hello, \" name \".\"))"] @@ -2396,7 +2396,7 @@ If the number of arguments is even and no clause matches, throws an exception." `(def ~name (->MultiMethod ~dispatch-fn ~(get options :default :default) (atom {}))))) (defmacro defmethod - {:doc "Define a method of a multimethod. See `(doc defmulti)` for details." + {:doc "Defines a method of a multimethod. See `(doc defmulti)` for details." :signatures [[name dispatch-val [param*] & body]] :added "0.1"} [name dispatch-val params & body] @@ -2413,14 +2413,14 @@ If the number of arguments is even and no clause matches, throws an exception." [x] x) (defmacro declare - {:doc "Forward declare the given variable names, setting them to nil." + {:doc "Forward declares the given variable names, setting them to nil." :added "0.1"} [& nms] (let [defs (map (fn [nm] `(def ~nm)) (seq nms))] `(do ~@defs))) (defmacro defprotocol - {:doc "Define a new protocol." + {:doc "Defines a new protocol." :examples [["(defprotocol SayHi (hi [x]))"] ["(extend hi String (fn [name] (str \"Hi, \" name \"!\")))"] ["(hi \"Jane\")" nil "Hi, Jane!"]] @@ -2433,7 +2433,7 @@ If the number of arguments is even and no clause matches, throws an exception." sigs))) (defmacro extend-type - {:doc "Extend the protocols to the given type. + {:doc "Extends the protocols to the given type. Expands to calls to `extend`." :examples [["(defprotocol SayHi (hi [x]))"] @@ -2521,7 +2521,7 @@ Expands to calls to `extend-type`." (defprotocol IRecord) (defn record? - {:doc "Returns true if x implements IRecord" + {:doc "Returns true if x implements IRecord." :since "0.1"} [x] (satisfies? IRecord x)) @@ -2552,7 +2552,7 @@ Expands to calls to `extend-type`." `(or (seq ~(gen-loop [] bindings)) '()))) (defmacro doto - {:doc "Evaluate o, uses the value as the first argument in each form. Returns o"} + {:doc "Evaluate o, uses the value as the first argument in each form. Returns o."} [o & forms] (let [s (gensym o)] `(let [~s ~o] @@ -2598,14 +2598,14 @@ Expands to calls to `extend-type`." result#))) (defn pst - {:doc "Prints the trace of a Runtime Exception if given, or the last Runtime Exception in *e" + {:doc "Prints the trace of a Runtime Exception if given, or the last Runtime Exception in *e." :signatures [[] [e]] :added "0.1"} ([] (pst *e)) ([e] (when e (print (str e))))) (defn trace - {:doc "Returns a seq of the trace of a Runtime Exception or the last Runtime Exception in *e" + {:doc "Returns a seq of the trace of a Runtime Exception or the last Runtime Exception in *e." :signatures [[] [e]] :added "0.1"} ([] (trace *e)) @@ -2701,7 +2701,7 @@ Calling this function on something that is not ISeqable returns a seq with that (str "#Environment{" (transduce (comp entry->str (interpose [", "]) cat) string-builder v) "}")))) (defn interleave - "Returns a seq of all the items in the input collections interleaved" + "Returns a seq of all the items in the input collections interleaved." ([] ()) ([c1] (seq c1)) ([c1 c2] @@ -2719,13 +2719,13 @@ Calling this function on something that is not ISeqable returns a seq with that (apply interleave (map next ss)))))))) (defn min - "Returns the smallest of all the arguments to this function. Assumes arguments are numeric" + "Returns the smallest of all the arguments to this function. Assumes arguments are numeric." ([x] x) ([x y] (if (< x y) x y)) ([x y & zs] (apply min (min x y) zs))) (defn max - "Returns the largest of all the arguments to this function. Assumes arguments are numeric" + "Returns the largest of all the arguments to this function. Assumes arguments are numeric." ([x] x) ([x y] (if (> x y) x y)) ([x y & zs] (apply max (max x y) zs))) @@ -2812,7 +2812,7 @@ Calling this function on something that is not ISeqable returns a seq with that (defmacro some-> {:doc "When expr is not nil, threads it into the first form (via ->), - and when that result is not nil, through the next etc" + and when that result is not nil, through the next etc." :signatures [[expr & forms]] :added "0.1"} [expr & forms] @@ -2827,7 +2827,7 @@ Calling this function on something that is not ISeqable returns a seq with that (defmacro some->> {:doc "When expr is not nil, threads it into the first form (via ->>), - and when that result is not nil, through the next etc" + and when that result is not nil, through the next etc." :signatures [[x & forms]] :added "0,1"} [expr & forms] @@ -2891,7 +2891,7 @@ Calling this function on something that is not ISeqable returns a seq with that (defprotocol IComparable (-compare [x y] - "Compare to objects returing 0 if the same -1 with x is logically smaller than y and 1 if x is logically larger")) + "Compare to objects returing 0 if the same -1 with x is logically smaller than y and 1 if x is logically larger.")) (defn compare-numbers [x y] From dee802dbe97daa3a3450adbb9234c94cb01295e3 Mon Sep 17 00:00:00 2001 From: Lucas Stadler Date: Sat, 5 Dec 2015 08:11:36 +0100 Subject: [PATCH 298/349] Add `is_recursive=True` to the main JitDriver This seems to be required in recent versions of pypy/rpython. --- pixie/vm/interpreter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/vm/interpreter.py b/pixie/vm/interpreter.py index 83e873df..d279e2fb 100644 --- a/pixie/vm/interpreter.py +++ b/pixie/vm/interpreter.py @@ -11,7 +11,7 @@ def get_location(ip, sp, is_continuation, bc, base_code): return code.BYTECODES[bc[ip]] + " in " + str(base_code._name) jitdriver = JitDriver(greens=["ip", "sp", "is_continuation", "bc", "base_code"], reds=["frame"], virtualizables=["frame"], - get_printable_location=get_location) + get_printable_location=get_location, is_recursive=True) @elidable From 0daaefef0fd35ee011c49a3583b216923272775f Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Mon, 7 Dec 2015 11:23:25 +0100 Subject: [PATCH 299/349] Fix the build for the latest PyPy nightly build --- pixie/vm/c_api.py | 16 ++++------------ pixie/vm/interpreter.py | 2 +- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/pixie/vm/c_api.py b/pixie/vm/c_api.py index 38b30e6e..45888295 100644 --- a/pixie/vm/c_api.py +++ b/pixie/vm/c_api.py @@ -1,31 +1,23 @@ -from rpython.rlib.entrypoint import entrypoint, RPython_StartupCode +from rpython.rlib.entrypoint import entrypoint_highlevel, RPython_StartupCode from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rtyper.lltypesystem.lloperation import llop -@entrypoint('main', [rffi.CCHARP], c_name='pixie_init') +@entrypoint_highlevel('main', [rffi.CCHARP], c_name='pixie_init') def pypy_execute_source(ll_progname): from target import init_vm - after = rffi.aroundstate.after - if after: after() progname = rffi.charp2str(ll_progname) init_vm(progname) res = 0 - before = rffi.aroundstate.before - if before: before() return rffi.cast(rffi.INT, res) -@entrypoint('main', [rffi.CCHARP], c_name='pixie_execute_source') +@entrypoint_highlevel('main', [rffi.CCHARP], c_name='pixie_execute_source') def pypy_execute_source(ll_source): from target import EvalFn, run_with_stacklets - after = rffi.aroundstate.after - if after: after() source = rffi.charp2str(ll_source) f = EvalFn(source) run_with_stacklets.invoke([f]) res = 0 - before = rffi.aroundstate.before - if before: before() - return rffi.cast(rffi.INT, res) \ No newline at end of file + return rffi.cast(rffi.INT, res) diff --git a/pixie/vm/interpreter.py b/pixie/vm/interpreter.py index 83e873df..d279e2fb 100644 --- a/pixie/vm/interpreter.py +++ b/pixie/vm/interpreter.py @@ -11,7 +11,7 @@ def get_location(ip, sp, is_continuation, bc, base_code): return code.BYTECODES[bc[ip]] + " in " + str(base_code._name) jitdriver = JitDriver(greens=["ip", "sp", "is_continuation", "bc", "base_code"], reds=["frame"], virtualizables=["frame"], - get_printable_location=get_location) + get_printable_location=get_location, is_recursive=True) @elidable From 4e3b95191f4bf646523a9bbca0cc2f17a271292d Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 8 Dec 2015 13:44:28 +0000 Subject: [PATCH 300/349] delete dead code --- pixie/vm/code.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 920c3dd9..14883796 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -484,18 +484,6 @@ def invoke_with(self, args, this_fn): def invoke(self, args): return self.deref().invoke(args) -class bindings(py_object): - def __init__(self, *args): - self._args = list(args) - - def __enter__(self): - _dynamic_vars.push_binding_frame() - for x in range(0, len(self._args), 2): - self._args[x].set_value(self._args[x + 1]) - - def __exit__(self, exc_type, exc_val, exc_tb): - _dynamic_vars.pop_binding_frame() - class Refer(py_object): def __init__(self, ns, refer_syms=[], refer_all=False): From 75e7db741f48537cf2e111c44a3d77506f511990 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Tue, 8 Dec 2015 16:21:12 +0100 Subject: [PATCH 301/349] Add pixie.data.json for reading and writing JSON --- pixie/data/json.pxi | 40 ++++++++++++++++++++++++++++ tests/pixie/tests/data/test-json.pxi | 19 +++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 pixie/data/json.pxi create mode 100644 tests/pixie/tests/data/test-json.pxi diff --git a/pixie/data/json.pxi b/pixie/data/json.pxi new file mode 100644 index 00000000..9ec7a995 --- /dev/null +++ b/pixie/data/json.pxi @@ -0,0 +1,40 @@ +(ns pixie.data.json + (:require [pixie.parser.json] + [pixie.string :as string])) + +(def read-string pixie.parser.json/read-string) + +(defprotocol IToJSON + (write-string [this])) + +(defn- write-map [m] + (if (empty? m) + "{}" + (str "{ " + (->> m + (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) + (string/join ", ")) + " }"))) + +(defn- write-sequential [xs] + (if (empty? xs) + "[]" + (str "[ " + (->> (map write-string xs) + (string/join ", ")) + " ]"))) + +(defn- write-str [s] + (string/interp "\"$s$\"")) + +(extend-protocol IToJSON + Character (write-string [this] (write-str this)) + Cons (write-string [this] (write-sequential this)) + EmptyList (write-string [this] (write-sequential this)) + Number (write-string [this] (str this)) + Keyword (write-string [this] (write-str (name this))) + LazySeq (write-string [this] (write-sequential this)) + IMap (write-string [this] (write-map this)) + IVector (write-string [this] (write-sequential this)) + Ratio (write-string [this] (str (float this))) + String (write-string [this] (write-str this))) diff --git a/tests/pixie/tests/data/test-json.pxi b/tests/pixie/tests/data/test-json.pxi new file mode 100644 index 00000000..1dc81891 --- /dev/null +++ b/tests/pixie/tests/data/test-json.pxi @@ -0,0 +1,19 @@ +(ns pixie.tests.data.test-json + (:require [pixie.test :refer :all] + [pixie.data.json :as json])) + + + +;; This test just ensures that we can use read-string; more thorough testing is +;; done in pixie.tests.parser.test-json +(deftest test-read-string + (assert= (json/read-string "{\"foo\": 42, \"bar\": [\"baz\"]}") + {"foo" 42, "bar" ["baz"]})) + +(deftest test-write-string + (assert= (json/write-string {:strings {:a \a, :b "b", :c "", :d :d} + :numbers {:one 1, :two 2.0, :three 3/1} + :lists {:empty {:vector [], :list '(), :seq (take 0 (range))} + :non-empty {:vector [1 2 3], :list '(1 2 3), :seq (take 3 (range))}} + :maps {:empty {}, :non-empty {:this "is covered, right? ;)"}}}) + "{ \"strings\": { \"b\": \"b\", \"c\": \"\", \"a\": \"a\", \"d\": \"d\" }, \"maps\": { \"non-empty\": { \"this\": \"is covered, right? ;)\" }, \"empty\": {} }, \"lists\": { \"non-empty\": { \"seq\": [ 0, 1, 2 ], \"list\": [ 1, 2, 3 ], \"vector\": [ 1, 2, 3 ] }, \"empty\": { \"seq\": [], \"list\": [], \"vector\": [] } }, \"numbers\": { \"one\": 1, \"two\": 2.000000, \"three\": 3 } }")) From 98fbd71749f68244fe8766131f9380cea3047085 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Tue, 8 Dec 2015 16:51:29 +0100 Subject: [PATCH 302/349] data.test-json : add round-trip tests --- tests/pixie/tests/data/test-json.pxi | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/pixie/tests/data/test-json.pxi b/tests/pixie/tests/data/test-json.pxi index 1dc81891..02d43ec4 100644 --- a/tests/pixie/tests/data/test-json.pxi +++ b/tests/pixie/tests/data/test-json.pxi @@ -17,3 +17,12 @@ :non-empty {:vector [1 2 3], :list '(1 2 3), :seq (take 3 (range))}} :maps {:empty {}, :non-empty {:this "is covered, right? ;)"}}}) "{ \"strings\": { \"b\": \"b\", \"c\": \"\", \"a\": \"a\", \"d\": \"d\" }, \"maps\": { \"non-empty\": { \"this\": \"is covered, right? ;)\" }, \"empty\": {} }, \"lists\": { \"non-empty\": { \"seq\": [ 0, 1, 2 ], \"list\": [ 1, 2, 3 ], \"vector\": [ 1, 2, 3 ] }, \"empty\": { \"seq\": [], \"list\": [], \"vector\": [] } }, \"numbers\": { \"one\": 1, \"two\": 2.000000, \"three\": 3 } }")) + +(deftest test-round-trip + (let [data {"foo" 1, "bar" [2 3]}] ; won't work with keywords because the parser doesn't keywordise them (yet) + (assert= (-> data json/write-string json/read-string) + data)) + + (let [string "{ \"foo\": [ 1, 2, 3 ] }"] + (assert= (-> string json/read-string json/write-string) + string))) From 4bd54cc349332ceee0e9c037fd37e293ddf0ee40 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Tue, 8 Dec 2015 17:02:51 +0100 Subject: [PATCH 303/349] data.json : use transducers for maps and sequences --- pixie/data/json.pxi | 11 +++++++---- tests/pixie/tests/data/test-json.pxi | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/pixie/data/json.pxi b/pixie/data/json.pxi index 9ec7a995..cb161871 100644 --- a/pixie/data/json.pxi +++ b/pixie/data/json.pxi @@ -12,16 +12,19 @@ "{}" (str "{ " (->> m - (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) - (string/join ", ")) + (transduce (comp (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) + (interpose ", ")) + string-builder)) " }"))) (defn- write-sequential [xs] (if (empty? xs) "[]" (str "[ " - (->> (map write-string xs) - (string/join ", ")) + (->> xs + (transduce (comp (map write-string) + (interpose ", ")) + string-builder)) " ]"))) (defn- write-str [s] diff --git a/tests/pixie/tests/data/test-json.pxi b/tests/pixie/tests/data/test-json.pxi index 02d43ec4..3eee66c7 100644 --- a/tests/pixie/tests/data/test-json.pxi +++ b/tests/pixie/tests/data/test-json.pxi @@ -16,7 +16,7 @@ :lists {:empty {:vector [], :list '(), :seq (take 0 (range))} :non-empty {:vector [1 2 3], :list '(1 2 3), :seq (take 3 (range))}} :maps {:empty {}, :non-empty {:this "is covered, right? ;)"}}}) - "{ \"strings\": { \"b\": \"b\", \"c\": \"\", \"a\": \"a\", \"d\": \"d\" }, \"maps\": { \"non-empty\": { \"this\": \"is covered, right? ;)\" }, \"empty\": {} }, \"lists\": { \"non-empty\": { \"seq\": [ 0, 1, 2 ], \"list\": [ 1, 2, 3 ], \"vector\": [ 1, 2, 3 ] }, \"empty\": { \"seq\": [], \"list\": [], \"vector\": [] } }, \"numbers\": { \"one\": 1, \"two\": 2.000000, \"three\": 3 } }")) + "{ \"numbers\": { \"three\": 3, \"two\": 2.000000, \"one\": 1 }, \"lists\": { \"empty\": { \"vector\": [], \"list\": [], \"seq\": [] }, \"non-empty\": { \"vector\": [ 1, 2, 3 ], \"list\": [ 1, 2, 3 ], \"seq\": [ 0, 1, 2 ] } }, \"maps\": { \"empty\": {}, \"non-empty\": { \"this\": \"is covered, right? ;)\" } }, \"strings\": { \"d\": \"d\", \"a\": \"a\", \"c\": \"\", \"b\": \"b\" } }")) (deftest test-round-trip (let [data {"foo" 1, "bar" [2 3]}] ; won't work with keywords because the parser doesn't keywordise them (yet) From 6b6673d1eddeb48f6c4bb52ef3e1b70351af53e8 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Wed, 9 Dec 2015 10:16:42 +0100 Subject: [PATCH 304/349] data.json : handle Nil and PersistentList --- pixie/data/json.pxi | 30 ++++++------- tests/pixie/tests/data/test-json.pxi | 64 ++++++++++++++++++++++++---- 2 files changed, 70 insertions(+), 24 deletions(-) diff --git a/pixie/data/json.pxi b/pixie/data/json.pxi index cb161871..7fde6354 100644 --- a/pixie/data/json.pxi +++ b/pixie/data/json.pxi @@ -8,24 +8,20 @@ (write-string [this])) (defn- write-map [m] - (if (empty? m) - "{}" - (str "{ " - (->> m - (transduce (comp (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) - (interpose ", ")) - string-builder)) - " }"))) + (str "{" + (->> m + (transduce (comp (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) + (interpose ", ")) + string-builder)) + "}")) (defn- write-sequential [xs] - (if (empty? xs) - "[]" - (str "[ " - (->> xs - (transduce (comp (map write-string) - (interpose ", ")) - string-builder)) - " ]"))) + (str "[" + (->> xs + (transduce (comp (map write-string) + (interpose ", ")) + string-builder)) + "]")) (defn- write-str [s] (string/interp "\"$s$\"")) @@ -34,10 +30,12 @@ Character (write-string [this] (write-str this)) Cons (write-string [this] (write-sequential this)) EmptyList (write-string [this] (write-sequential this)) + Nil (write-string [_] "null") Number (write-string [this] (str this)) Keyword (write-string [this] (write-str (name this))) LazySeq (write-string [this] (write-sequential this)) IMap (write-string [this] (write-map this)) IVector (write-string [this] (write-sequential this)) + PersistentList (write-string [this] (write-sequential this)) Ratio (write-string [this] (str (float this))) String (write-string [this] (write-str this))) diff --git a/tests/pixie/tests/data/test-json.pxi b/tests/pixie/tests/data/test-json.pxi index 3eee66c7..098ad019 100644 --- a/tests/pixie/tests/data/test-json.pxi +++ b/tests/pixie/tests/data/test-json.pxi @@ -10,19 +10,67 @@ (assert= (json/read-string "{\"foo\": 42, \"bar\": [\"baz\"]}") {"foo" 42, "bar" ["baz"]})) -(deftest test-write-string - (assert= (json/write-string {:strings {:a \a, :b "b", :c "", :d :d} - :numbers {:one 1, :two 2.0, :three 3/1} - :lists {:empty {:vector [], :list '(), :seq (take 0 (range))} - :non-empty {:vector [1 2 3], :list '(1 2 3), :seq (take 3 (range))}} - :maps {:empty {}, :non-empty {:this "is covered, right? ;)"}}}) - "{ \"numbers\": { \"three\": 3, \"two\": 2.000000, \"one\": 1 }, \"lists\": { \"empty\": { \"vector\": [], \"list\": [], \"seq\": [] }, \"non-empty\": { \"vector\": [ 1, 2, 3 ], \"list\": [ 1, 2, 3 ], \"seq\": [ 0, 1, 2 ] } }, \"maps\": { \"empty\": {}, \"non-empty\": { \"this\": \"is covered, right? ;)\" } }, \"strings\": { \"d\": \"d\", \"a\": \"a\", \"c\": \"\", \"b\": \"b\" } }")) +(deftest test-strings + (assert-table [x y] (assert= (json/write-string x) y) + \a "\"a\"" + "foo" "\"foo\"" + :bar "\"bar\"" + "" "\"\"")) + +(deftest test-numbers + (assert-table [x y] (assert= (json/write-string x) y) + 1 "1" + 1.0 "1.000000" + 0.1 "0.100000" + 1.1 "1.100000" + 1234.5678 "1234.567800" + -1 "-1" + -0.1 "-0.100000" + -1.1 "-1.100000" + -1234.5678 "-1234.567800" + 1e1 "10.000000" + 3/1 "3")) + +(deftest test-vectors + (assert-table [x y] (assert= (json/write-string x) y) + [] "[]" + [nil] "[null]" + [1 2] "[1, 2]" + [1 1.0 nil] "[1, 1.000000, null]" + ["foo" 42] "[\"foo\", 42]")) + +(deftest test-seqs + (assert-table [x y] (assert= (json/write-string x) y) + (take 0 (range)) "[]" + (take 1 (repeat nil)) "[null]" + (map identity [1 2]) "[1, 2]" + (reduce + [1 2 3]) "6")) + +(deftest test-lists + (assert-table [x y] (assert= (json/write-string x) y) + '() "[]" + '(nil) "[null]" + '(1 2) "[1, 2]" + '(1 1.0 nil) "[1, 1.000000, null]" + '("foo" 42) "[\"foo\", 42]" + (list) "[]" + (list nil) "[null]" + (list 1 2) "[1, 2]" + (list 1 1.0 nil) "[1, 1.000000, null]" + (list "foo" 42) "[\"foo\", 42]")) + +(deftest test-maps + (assert-table [x y] (assert= (json/write-string x) y) + {} "{}" + {:foo 42} "{\"foo\": 42}" + {"foo" 42} "{\"foo\": 42}" + {"foo" 42, "bar" nil} "{\"foo\": 42, \"bar\": null}")) (deftest test-round-trip (let [data {"foo" 1, "bar" [2 3]}] ; won't work with keywords because the parser doesn't keywordise them (yet) (assert= (-> data json/write-string json/read-string) data)) - (let [string "{ \"foo\": [ 1, 2, 3 ] }"] + (let [string "{\"foo\": [1, 2, 3]}"] (assert= (-> string json/read-string json/write-string) string))) From e6741066162984363d1bf8fe1bafda030fdf31a9 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Wed, 9 Dec 2015 10:20:56 +0100 Subject: [PATCH 305/349] Update gitignore to ignore build artifacts --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index d2f96fde..62c09a44 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,7 @@ lib include *.pxic test.tmp +/libuv* +/uv-* +/uv.h +/*compressed-output.* From 5fa954e02d542c6f092db582953cca5afcd1b248 Mon Sep 17 00:00:00 2001 From: Chris Shea Date: Fri, 11 Dec 2015 15:54:26 -0500 Subject: [PATCH 306/349] Normalize docstrings in io-related namespaces --- pixie/io-blocking.pxi | 10 +++++----- pixie/io.pxi | 14 +++++++------- pixie/io/tcp.pxi | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi index c6547486..4af15739 100644 --- a/pixie/io-blocking.pxi +++ b/pixie/io-blocking.pxi @@ -38,15 +38,15 @@ (common/stream-reducer this f init))) (defn open-read - {:doc "Open a file for reading, returning a IInputStream" + {:doc "Opens a file for reading. Returns an IInputStream." :added "0.1"} [filename] (assert (string? filename) "Filename must be a string") (->FileStream (fopen filename "r"))) (defn read-line - "Read one line from input-stream for each invocation. - nil when all lines have been read" + "Reads one line from input-stream for each invocation. + Returns nil when all lines have been read." [input-stream] (let [line-feed (into #{} (map int [\newline \return])) buf (buffer 1)] @@ -62,7 +62,7 @@ (defn line-seq "Returns the lines of text from input-stream as a lazy sequence of strings. - input-stream must implement IInputStream" + input-stream must implement IInputStream." [input-stream] (when-let [line (read-line input-stream)] (cons line (lazy-seq (line-seq input-stream))))) @@ -131,7 +131,7 @@ (common/stream-reducer this f init))) (defn popen-read - {:doc "Open a file for reading, returning a IInputStream" + {:doc "Opens a file for reading. Returns an IInputStream." :added "0.1"} [command] (assert (string? command) "Command must be a string") diff --git a/pixie/io.pxi b/pixie/io.pxi index 16ec14be..3dd8bdf2 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -41,7 +41,7 @@ (common/stream-reducer this f init))) (defn open-read - {:doc "Open a file for reading, returning a IInputStream" + {:doc "Opens a file for reading. Returns an IInputStream." :added "0.1"} [filename] (assert (string? filename) "Filename must be a string") @@ -95,15 +95,15 @@ (throw [::Exception "Expected a LineReader, UTF8InputStream, or BufferedInputStream"]))) (defn read-line - "Read one line from input-stream for each invocation. - nil when all lines have been read. + "Reads one line from input-stream for each invocation. + Returns nil when all lines have been read. Pass a BufferedInputStream for best performance." [input-stream] (-read-line (line-reader input-stream))) (defn line-seq "Returns the lines of text from input-stream as a lazy sequence of strings. - input-stream must implement IInputStream" + input-stream must implement IInputStream." [input-stream] (let [lr (line-reader input-stream)] (when-let [line (-read-line lr)] @@ -213,7 +213,7 @@ result) (defn open-write - {:doc "Open a file for writing, returning a IOutputStream" + {:doc "Opens a file for writing. Returns an IOutputStream." :added "0.1"} [filename] (assert (string? filename) "Filename must be a string") @@ -244,8 +244,8 @@ :else (throw [::Exception "Expected a string or IOutputStream"]))) -(defn slurp - "Reads in the contents of input. Input must be a filename or an IInputStream" +(defn slurp + "Reads in the contents of input. Input must be a filename or an IInputStream." [input] (let [stream (cond (string? input) (open-read input) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi index 4836e7a6..0233d00a 100644 --- a/pixie/io/tcp.pxi +++ b/pixie/io/tcp.pxi @@ -64,7 +64,7 @@ (defn tcp-client - "Creates a TCP connection to the given ip (as a string) and port (an integer). Will return a TCPStream" + "Creates a TCP connection to the given ip (as a string) and port (an integer). Returns a TCPStream." [ip port] (let [client-addr (uv/sockaddr_in) uv-connect (uv/uv_connect_t) From 91309e886fce31598ec6912fcf2228e6c56d8124 Mon Sep 17 00:00:00 2001 From: Chris Shea Date: Fri, 18 Dec 2015 16:31:31 -0500 Subject: [PATCH 307/349] Add a few more docstrings --- pixie/stdlib.pxi | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ec1ef49c..be13ccfe 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2245,6 +2245,11 @@ user => (refer 'pixie.string :exclude '(substring))" (defn merge-with + {:doc "Returns a map consisting of each map merged onto the first. If a + map contains a key that already exists in the result, the + value will be f applied to the value in the result map and + the value from the map being merged in." + :examples [["(merge-with + {:a 1 :b 2} {:a 3 :c 5} {:c 3 :d 4})" nil {:a 4, :b 2, :c 8 :d 4}]]} [f & maps] (cond (empty? maps) nil @@ -2570,24 +2575,29 @@ Expands to calls to `extend-type`." (into () coll)) (defmacro use + "Loads a namespace and refers all symbols from it." [ns] `(do (load-ns ~ns) (refer ~ns :refer :all))) (defn count-rf - "A Reducing function that counts the items reduced over" + "A Reducing function that counts the items reduced over." ([] 0) ([result] result) ([result _] (inc result))) (defn dispose! - "Finalizes use of the object by cleaning up resources used by the object" + "Finalizes use of the object by cleaning up resources used by the object." [x] (-dispose! x) nil) -(defmacro using [bindings & body] +(defmacro using + "Evaluates body with the bindings available as with let, + calling -dispose! on each name afterwards. Returns the value of the + last expression in body." + [bindings & body] (let [pairs (partition 2 bindings) names (map first pairs)] `(let [~@bindings @@ -2653,6 +2663,8 @@ Calling this function on something that is not ISeqable returns a seq with that {} m)) (defn mapv + {:doc "Returns a vector consisting of f applied to each element in col." + :examples [["(mapv inc '(1 2 3))" nil [2 3 4]]]} ([f col] (transduce (map f) conj col))) @@ -2687,7 +2699,10 @@ Calling this function on something that is not ISeqable returns a seq with that (def hash-map hashmap) -(defn zipmap [a b] +(defn zipmap + "Returns a map with the elements of a mapped to the corresponding + elements of b." + [a b] (into {} (map vector a b))) (extend -str Environment @@ -2775,6 +2790,7 @@ Calling this function on something that is not ISeqable returns a seq with that (defn bool? + "Returns true if x is a Bool." [x] (instance? Bool x)) @@ -2891,7 +2907,8 @@ Calling this function on something that is not ISeqable returns a seq with that (defprotocol IComparable (-compare [x y] - "Compare to objects returing 0 if the same -1 with x is logically smaller than y and 1 if x is logically larger.")) + "Compares two objects. Returns 0 when x is equal to y, -1 when x + is logically smaller than y, and 1 when x is logically larger.")) (defn compare-numbers [x y] @@ -2981,6 +2998,9 @@ Calling this function on something that is not ISeqable returns a seq with that (throw [::ComparisonError (str "Cannot compare: " x " to " y)])))) (defn compare + "Compares two objects. Returns 0 when x is equal to y, -1 when x is + logically smaller than y, and 1 when x is logically larger. x must + implement IComparable." [x y] (if (satisfies? IComparable x) (-compare x y) From 9788a3fad9d60fbaf014f8f3820278e5861379af Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sat, 19 Dec 2015 19:27:33 +0000 Subject: [PATCH 308/349] freeze rpython --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index cbe6086c..0ef5b975 100644 --- a/Makefile +++ b/Makefile @@ -58,7 +58,7 @@ lib: $(EXTERNALS)/pypy: mkdir $(EXTERNALS); \ cd $(EXTERNALS); \ - curl https://bitbucket.org/pypy/pypy/get/default.tar.bz2 > pypy.tar.bz2; \ + curl https://bitbucket.org/pypy/pypy/get/81254.tar.bz2 > pypy.tar.bz2; \ mkdir pypy; \ cd pypy; \ tar -jxf ../pypy.tar.bz2 --strip-components=1 From d3c18882baed7a9c001ed72ea7b468d04b059d47 Mon Sep 17 00:00:00 2001 From: Josh Glover Date: Mon, 21 Dec 2015 10:42:22 +0100 Subject: [PATCH 309/349] Makefile : do not fetch externals when present --- .gitignore | 2 +- Makefile | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 62c09a44..5928d907 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ *.pyc -externals +externals* pixie-vm .idea lib diff --git a/Makefile b/Makefile index 0ef5b975..7a6848af 100644 --- a/Makefile +++ b/Makefile @@ -47,12 +47,13 @@ build_preload_no_jit: fetch_externals build: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) $(JIT_OPTS) $(TARGET_OPTS) -fetch_externals: $(EXTERNALS)/pypy ./lib +fetch_externals: $(EXTERNALS)/pypy externals.fetched -lib: +externals.fetched: echo https://github.com/pixie-lang/external-deps/releases/download/1.0/`uname -s`-`uname -m`.tar.bz2 curl -L https://github.com/pixie-lang/external-deps/releases/download/1.0/`uname -s`-`uname -m`.tar.bz2 > /tmp/externals.tar.bz2 tar -jxf /tmp/externals.tar.bz2 --strip-components=2 + touch externals.fetched $(EXTERNALS)/pypy: @@ -92,6 +93,6 @@ clean_pxic: clean: clean_pxic rm -rf ./lib rm -rf ./include - rm -rf ./externals + rm -rf ./externals* rm -f ./pixie-vm rm -f ./*.pyc From 7a0c6906066f9ac8d0a55c7088a8da5d8847a4eb Mon Sep 17 00:00:00 2001 From: Stuart Hinson Date: Wed, 23 Dec 2015 16:32:40 -0500 Subject: [PATCH 310/349] implement cycle --- pixie/stdlib.pxi | 13 +++++++++++++ tests/pixie/tests/test-stdlib.pxi | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index be13ccfe..16c68916 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1746,6 +1746,19 @@ The new value is thus `(apply f current-value-of-atom args)`." s)))] (lazy-seq (step pred coll))))) +(defn cycle + [coll] + (if (empty? coll) + () + (let [cycle' + (fn cycle' [current] + (lazy-seq + (cons + (first current) + (let [rst (rest current)] + (cycle' (if (empty? rst) coll rst))))))] + (cycle' coll)))) + ;; TODO: use a transient map in the future (defn group-by {:doc "Groups the collection into a map keyed by the result of applying f on each element. The value at each key is a vector of elements in order of appearance." diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index ae219c75..8e96707f 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -568,6 +568,12 @@ (t/assert= (transduce (drop-while even?) conj [0 2] [1 4 6]) [0 2 1 4 6]) (t/assert= (transduce (drop-while even?) conj [0 2] [2 4 6 7 8]) [0 2 7 8])) +(t/deftest test-cycle + (t/assert= (cycle ()) ()) + (t/assert= (cycle nil) ()) + (t/assert= (take 5 (cycle '(1 2))) '(1 2 1 2 1)) + (t/assert= (take 3 (cycle [nil])) '(nil nil nil))) + (t/deftest test-trace (try (/ 0 0) From 98eedd2a24fede820c79beeaaff8be47603ac1b6 Mon Sep 17 00:00:00 2001 From: hswick Date: Wed, 30 Dec 2015 15:19:23 -0600 Subject: [PATCH 311/349] Added generate-docs.pxi --- generate-docs.pxi | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 generate-docs.pxi diff --git a/generate-docs.pxi b/generate-docs.pxi new file mode 100644 index 00000000..5f8abb5b --- /dev/null +++ b/generate-docs.pxi @@ -0,0 +1,54 @@ +(ns pixie.generate-docs + (:require [pixie.io :as io] + [pixie.string :as string])) + +(let [[namespace] program-arguments] + + (println "==============") + (println (name namespace)) + (println "==============") + + (load-ns (symbol namespace)) + (println) + + ;;Should be sorting the map + ;;Like so: (sort-by first map) + ;;However, I'm holding off until sort is properly supported + (doseq [[k v] (ns-map (the-ns namespace))] + (println (name k)) + (println "====================================") + (println) + + (if-let [m (meta @v)] + (do + ;(println m) + (if-let [doc (:doc m)];; + (println doc) + (println "No doc available :(")) + (println) + + (when-let (examples (:examples m)) + (println "**Examples:**") + (doseq [[code _ result] examples] + (println) + (println code) + (println) + (when (not (nil? result)) + (println "=> " result))) + (println)) + + (when-let (signatures (:signatures m)) + (println "**Signatures:**") + (println) + (doseq [sig signatures] + (println (str "- " sig))) + (println)) + + (when (and (:line-number m) (:file m)) + (let [file (str "pixie/" (last (string/split (:file m) "/")))] + (println (str "http://github.com/pixie-lang/pixie/blob/master/" + file "#L" (:line-number m)))) + (println))) + + (println "No meta data available :(")) + (println))) \ No newline at end of file From a7a81cd6d3946f188fb203f62383f64f1a431eed Mon Sep 17 00:00:00 2001 From: Pauli Jaakkola Date: Mon, 11 Jan 2016 18:05:05 +0200 Subject: [PATCH 312/349] Add CFloat test. --- tests/pixie/tests/test-ffi.pxi | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index f2d997c7..813098e9 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -1,6 +1,7 @@ (ns pixie.tests.test-ffi (require pixie.test :as t) - (require pixie.math :as m)) + (require pixie.math :as m) + (require pixie.ffi-infer :as i)) @@ -36,6 +37,17 @@ (t/deftest test-ffi-infer (t/assert= 0.5 (m/asin (m/sin 0.5)))) +(t/deftest test-cdouble + (i/with-config {:library "m" + :cxx-flags ["-lm"] + :includes ["math.h"]} + (i/defcfn sinf) + (i/defcfn asinf) + (i/defcfn cosf) + (i/defcfn powf)) + (t/assert= 0.5 (asinf (sinf 0.5))) + (t/assert= 1.0 (+ (powf (sinf 0.5) 2.0) (powf (cosf 0.5) 2.0)))) + (t/deftest test-ffi-callbacks (let [MAX 255 From baabdabcb1056624276caf07885ccfe25f7c0acf Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 21 Dec 2015 12:33:42 +0000 Subject: [PATCH 313/349] Remove remands of preloader --- .travis.yml | 5 ----- Makefile | 6 ------ target_preload.py | 32 -------------------------------- 3 files changed, 43 deletions(-) delete mode 100644 target_preload.py diff --git a/.travis.yml b/.travis.yml index 7176dc4b..77846892 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,14 +2,9 @@ sudo: false env: - JIT_OPTS='--opt=jit' TARGET_OPTS='target.py' - JIT_OPTS='' TARGET_OPTS='target.py' - #- JIT_OPTS='--opt=jit' TARGET_OPTS='target_preload.py' - #- JIT_OPTS='' TARGET_OPTS='target_preload.py' matrix: fast_finish: true - allow_failures: - - env: JIT_OPTS='--opt=jit' TARGET_OPTS='target_preload.py' - - env: JIT_OPTS='' TARGET_OPTS='target_preload.py' script: - make PYTHON=python build diff --git a/Makefile b/Makefile index 7a6848af..15f691e5 100644 --- a/Makefile +++ b/Makefile @@ -38,12 +38,6 @@ compile_basics: @echo -e "\n\n\n\nWARNING: Compiling core libs. If you want to modify one of these files delete the .pxic files first\n\n\n\n" ./pixie-vm -c pixie/uv.pxi -c pixie/io.pxi -c pixie/stacklets.pxi -c pixie/stdlib.pxi -c pixie/repl.pxi -build_preload_with_jit: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) --opt=jit target_preload.py 2>&1 >/dev/null | grep -v 'WARNING' - -build_preload_no_jit: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target_preload.py - build: fetch_externals $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) $(JIT_OPTS) $(TARGET_OPTS) diff --git a/target_preload.py b/target_preload.py deleted file mode 100644 index 3bb0fbe8..00000000 --- a/target_preload.py +++ /dev/null @@ -1,32 +0,0 @@ -from target import entry_point, load_stdlib, init_load_path, LOAD_PATHS, load_path, BatchModeFn -from pixie.vm.atom import Atom -from pixie.vm.persistent_vector import EMPTY as EMPTY_VECTOR -from pixie.vm.symbol import symbol -from pixie.vm.code import intern_var - -import pixie.vm.rt as rt -rt.init() - -load_path.set_root(rt.wrap(u"./")) -LOAD_PATHS.set_root(Atom(EMPTY_VECTOR.conj(rt.wrap(u"./")))) -load_stdlib() - -BatchModeFn(["pixie/preload.pxi"]).invoke([]) - -def target(*args): - import pixie.vm.rt as rt - driver = args[0] - driver.exe_name = "pixie-vm" - rt.__config__ = args[0].config - - - - - - return entry_point, None - -import rpython.config.translationoption -print rpython.config.translationoption.get_combined_translation_config() - -if __name__ == "__main__": - entry_point(sys.argv) \ No newline at end of file From 9811e61c06f4750e217341c84bc55e2f28f1a30f Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 13 Jan 2016 09:36:44 +0100 Subject: [PATCH 314/349] improve pixie.math scope (adapted from work of @edw found here: https://gist.github.com/edw/87a4e234a33b5a1e0377) --- pixie/math.pxi | 107 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 33 deletions(-) diff --git a/pixie/math.pxi b/pixie/math.pxi index 15a778c4..0cb53ae1 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -4,52 +4,93 @@ (i/with-config {:library "m" :cxx-flags ["-lm"] :includes ["math.h"]} - (i/defcfn sin) - (i/defcfn cos) - (i/defcfn tan) + (i/defconst M_E) + (i/defconst M_LOG2E) + (i/defconst M_LOG10E) + (i/defconst M_LN2) + (i/defconst M_LN10) + (i/defconst M_PI) + (i/defconst M_PI_2) + (i/defconst M_PI_4) + (i/defconst M_1_PI) + (i/defconst M_2_PI) + (i/defconst M_2_SQRTPI) + (i/defconst M_SQRT2) + (i/defconst M_SQRT1_2) - (i/defcfn asin) - (i/defcfn acos) - (i/defcfn atan) - (i/defcfn atan2) ; Arc tangent function of two variables. + (i/defcfn nan) + (i/defcfn ceil) + (i/defcfn floor) + (i/defcfn nearbyint) + (i/defcfn rint) + (i/defcfn lround) + (i/defcfn llrint) + (i/defcfn llround) + (i/defcfn trunc) - (i/defcfn sinh) - (i/defcfn cosh) - (i/defcfn tanh) + (i/defcfn fmod) + (i/defcfn remainder) + (i/defcfn remquo) - (i/defcfn asinh) - (i/defcfn acosh) - (i/defcfn atanh) + (i/defcfn fdim) + (i/defcfn fmax) + (i/defcfn fmin) + + (i/defcfn fma) + + (i/defcfn fabs) + (i/defcfn sqrt) + (i/defcfn cbrt) + (i/defcfn hypot) (i/defcfn exp) - (i/defcfn ldexp) + (i/defcfn exp2) + (i/defcfn exp10) + (i/defcfn expm1) (i/defcfn log) (i/defcfn log2) (i/defcfn log10) (i/defcfn log1p) + (i/defcfn logb) (i/defcfn ilogb) - ;; (i/defcfn modf) ;; Needs ffi support + (i/defcfn modf) + (i/defcfn frexp) + + (i/defcfn ldexp) + (i/defcfn scalbn) + (i/defcfn scalbln) + (i/defcfn pow) - (i/defcfn sqrt) - (i/defcfn ceil) - (i/defcfn fabs) - (i/defcfn floor) - (i/defcfn fmod) - (i/defconst M_E) ; base of natural logarithm, e - (i/defconst M_LOG2E) ; log2(e) - (i/defconst M_LOG10E) ; log10(e) - (i/defconst M_LN2) ; ln(2) - (i/defconst M_LN10) ; ln(10) - (i/defconst M_PI) ; pi - (i/defconst M_PI_2) ; pi / 2 - (i/defconst M_PI_4) ; pi / 4 - (i/defconst M_1_PI) ; 1 / pi - (i/defconst M_2_PI) ; 2 / pi - (i/defconst M_2_SQRTPI) ; 2 / sqrt(pi) - (i/defconst M_SQRT2) ; sqrt(2) - (i/defconst M_SQRT1_2)) ; sqrt(1/2) + (i/defcfn cos) + (i/defcfn sin) + (i/defcfn tan) + + (i/defcfn cosh) + (i/defcfn sinh) + (i/defcfn tanh) + + (i/defcfn acos) + (i/defcfn asin) + (i/defcfn atan) + (i/defcfn atan2) + + (i/defcfn acosh) + (i/defcfn asinh) + (i/defcfn atanh) + + (i/defcfn tgamma) + (i/defcfn lgamma) + + (i/defcfn j0) + (i/defcfn j1) + (i/defcfn jn) + (i/defcfn y0) + (i/defcfn y1) + (i/defcfn yn) + (i/defcfn erf) + (i/defcfn erfc)) From 780ee38e14b5bd069291a7a0f69f98049427749c Mon Sep 17 00:00:00 2001 From: David Schaefer Date: Sat, 23 Jan 2016 15:57:58 +0100 Subject: [PATCH 315/349] Raise runtime_error in to_float --- pixie/vm/numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index ab80edbe..b9363665 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -320,7 +320,7 @@ def to_float(x): return rt.wrap(float(x.int_val())) if isinstance(x, BigInteger): return rt.wrap(x.bigint_val().tofloat()) - assert False + object.runtime_error(u"Cannot convert %s to float" %x.type().name()) def to_float_conv(c): if c == Float: From 034349daaf083970aedcc9aba44796d2291f231e Mon Sep 17 00:00:00 2001 From: David Schaefer Date: Mon, 25 Jan 2016 15:56:31 +0100 Subject: [PATCH 316/349] added to_float exception test --- tests/pixie/tests/test-ffi.pxi | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index 813098e9..ba5f9bd1 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -48,6 +48,14 @@ (t/assert= 0.5 (asinf (sinf 0.5))) (t/assert= 1.0 (+ (powf (sinf 0.5) 2.0) (powf (cosf 0.5) 2.0)))) +(t/deftest test-invalid-float-argument + (try + (m/sin "nil") + (catch ex (t/assert= (type ex) RuntimeException))) + (try + (m/exp nil) + (catch ex (t/assert= (type ex) RuntimeException))) + ) (t/deftest test-ffi-callbacks (let [MAX 255 From d397fd8131c58b38fd3b92ace9f77dcdff00e15e Mon Sep 17 00:00:00 2001 From: David Schaefer Date: Mon, 25 Jan 2016 16:38:41 +0100 Subject: [PATCH 317/349] using assert-throws? in test-invalid-float-argument --- tests/pixie/tests/test-ffi.pxi | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index ba5f9bd1..4cc486dd 100644 --- a/tests/pixie/tests/test-ffi.pxi +++ b/tests/pixie/tests/test-ffi.pxi @@ -49,12 +49,8 @@ (t/assert= 1.0 (+ (powf (sinf 0.5) 2.0) (powf (cosf 0.5) 2.0)))) (t/deftest test-invalid-float-argument - (try - (m/sin "nil") - (catch ex (t/assert= (type ex) RuntimeException))) - (try - (m/exp nil) - (catch ex (t/assert= (type ex) RuntimeException))) + (t/assert-throws? (m/sin "nil")) + (t/assert-throws? (m/sin nil)) ) (t/deftest test-ffi-callbacks From d2b1b3acc3491273fa1e9b17af62078dcb3d491a Mon Sep 17 00:00:00 2001 From: Sebastiano Barrera Date: Wed, 3 Feb 2016 12:37:26 +0100 Subject: [PATCH 318/349] Add `eduction` and `completing` The `eduction` function was added, as requested in issue #483. The implementation and the tests were imported and adapted from Clojure's standard library (from [1] and [2], respectively). Since Clojure's implementation uses it, the function `completing` was imported as well (from the same source). As of now, Pixie's stdlib lacks a `sort`/`sort-by` function, one of the tests is disabled (commented out), and another is modified in order to avoid the call to `sort-by`. Sources: Both from Clojure's main repo, fetched at commit `3b98a00`. [1] https://github.com/clojure/clojure/blob/3b98a00e86f961550fb2eaee64e70754e04d1089/src/clj/clojure/core.clj#L7339 [2] https://github.com/clojure/clojure/blob/3b98a00e86f961550fb2eaee64e70754e04d1089/test/clojure/test_clojure/transducers.clj --- pixie/stdlib.pxi | 29 +++++++++++++++++++++++++++++ tests/pixie/tests/test-stdlib.pxi | 28 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 16c68916..46f656a1 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1884,6 +1884,35 @@ not enough elements were present." (when-let [s (seq coll)] (reductions f (f init (first s)) (rest s)))))))) +(defn completing + "Takes a reducing function f of 2 args and returns a fn suitable for + transduce by adding an arity-1 signature that calls cf (default - + identity) on the result argument." + ([f] (completing f identity)) + ([f cf] + (fn + ([] (f)) + ([x] (cf x)) + ([x y] (f x y))))) + +(deftype Eduction [xform coll] + IReduce + (-reduce [self f init] + ;; NB (completing f) isolates completion of inner rf from outer rf + (transduce xform (completing f) init coll)) + + ISeqable + (-seq [self] + (reduce conj self))) + +(defn eduction + "Returns a reducible/iterable application of the transducers + to the items in coll. Transducers are applied in order as if + combined with comp. Note that these applications will be + performed every time reduce/iterator is called." + [& xforms] + (->Eduction (apply comp (butlast xforms)) (last xforms))) + (defn destructure [binding expr] (cond (symbol? binding) [binding expr] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 8e96707f..48e3b4e1 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -574,6 +574,34 @@ (t/assert= (take 5 (cycle '(1 2))) '(1 2 1 2 1)) (t/assert= (take 3 (cycle [nil])) '(nil nil nil))) +(t/deftest test-eduction + ;; one xform + (t/assert= [1 2 3 4 5] + (eduction (map inc) (range 5))) + ;; multiple xforms + (t/assert= ["2" "4"] + (eduction (map inc) (filter even?) (map str) (range 5))) + ;; materialize at the end + ;; TODO: For when sort is implemented + ;; (t/assert= [1 1 1 1 2 2 2 3 3 4] + ;; (->> (range 5) + ;; (eduction (mapcat range) (map inc)) + ;; sort)) + (t/assert= [1 1 2 1 2 3 1 2 3 4] + (vec (->> (range 5) + (eduction (mapcat range) (map inc))))) + (t/assert= {1 4, 2 3, 3 2, 4 1} + (->> (range 5) + (eduction (mapcat range) (map inc)) + frequencies)) + (t/assert= ["tac" "god" "hsif" "drib" "kravdraa"] + (->> ["cat" "dog" "fish" "bird" "aardvark"] + (eduction (map pixie.string/reverse)) + (seq))) + ;; expanding transducer with nils + (t/assert= '(1 2 3 nil 4 5 6 nil) + (eduction cat [[1 2 3 nil] [4 5 6 nil]]))) + (t/deftest test-trace (try (/ 0 0) From 2789b879e5b3b0770bccabd28e429fad851d8769 Mon Sep 17 00:00:00 2001 From: Sebastiano Barrera Date: Wed, 3 Feb 2016 16:25:35 +0100 Subject: [PATCH 319/349] eduction: remove superfluous test --- tests/pixie/tests/test-stdlib.pxi | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 48e3b4e1..6dfd3efc 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -582,11 +582,6 @@ (t/assert= ["2" "4"] (eduction (map inc) (filter even?) (map str) (range 5))) ;; materialize at the end - ;; TODO: For when sort is implemented - ;; (t/assert= [1 1 1 1 2 2 2 3 3 4] - ;; (->> (range 5) - ;; (eduction (mapcat range) (map inc)) - ;; sort)) (t/assert= [1 1 2 1 2 3 1 2 3 4] (vec (->> (range 5) (eduction (mapcat range) (map inc))))) From df3b2a0a1b318e01aadb24908a60fc0273427fea Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Tue, 9 Feb 2016 21:31:09 +0000 Subject: [PATCH 320/349] make typing less verbose Object's type method is now used by default so all subtypes can use the inherited implementation --- pixie/vm/array.py | 8 -------- pixie/vm/atom.py | 3 --- pixie/vm/code.py | 33 --------------------------------- pixie/vm/cons.py | 3 --- pixie/vm/custom_types.py | 2 -- pixie/vm/interpreter.py | 4 ---- pixie/vm/lazy_seq.py | 3 --- pixie/vm/libs/env.py | 3 --- pixie/vm/libs/ffi.py | 14 -------------- pixie/vm/libs/path.py | 3 --- pixie/vm/libs/pxic/writer.py | 2 -- pixie/vm/map_entry.py | 3 --- pixie/vm/numbers.py | 15 --------------- pixie/vm/object.py | 15 ++++++--------- pixie/vm/persistent_hash_map.py | 6 ------ pixie/vm/persistent_hash_set.py | 3 --- pixie/vm/persistent_list.py | 5 ----- pixie/vm/persistent_vector.py | 9 --------- pixie/vm/primitives.py | 10 ---------- pixie/vm/reader.py | 10 ---------- pixie/vm/reduced.py | 2 -- pixie/vm/stacklet.py | 5 +---- pixie/vm/string.py | 6 ------ pixie/vm/string_builder.py | 5 +---- pixie/vm/threads.py | 3 --- pixie/vm/util.py | 3 --- 26 files changed, 8 insertions(+), 170 deletions(-) diff --git a/pixie/vm/array.py b/pixie/vm/array.py index 3bde8642..9d15f550 100644 --- a/pixie/vm/array.py +++ b/pixie/vm/array.py @@ -14,8 +14,6 @@ class Array(object.Object): _type = object.Type(u"pixie.stdlib.Array") _immutable_fields_ = ["_list"] - def type(self): - return Array._type def __init__(self, lst): self._list = lst @@ -98,9 +96,6 @@ def reduce(self, f, init): init = f.invoke([init, rt.nth(self._w_array, rt.wrap(x))]) return init - def type(self): - return self._type - @extend(proto._first, ArraySeq) def _first(self): assert isinstance(self, ArraySeq) @@ -174,9 +169,6 @@ def __init__(self, size): for x in range(size): self._buffer[x] = chr(0) - def type(self): - return ByteArray._type - def __del__(self): lltype.free(self._buffer, flavor="raw") diff --git a/pixie/vm/atom.py b/pixie/vm/atom.py index 77ecd50d..28254673 100644 --- a/pixie/vm/atom.py +++ b/pixie/vm/atom.py @@ -7,9 +7,6 @@ class Atom(object.Object): _type = object.Type(u"pixie.stdlib.Atom") - def type(self): - return Atom._type - def with_meta(self, meta): return Atom(self._boxed_value, meta) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index 14883796..5a54ea25 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -148,9 +148,6 @@ class MultiArityFn(BaseCode): _immutable_fields_ = ["_arities[*]", "_required_arity", "_rest_fn"] - def type(self): - return MultiArityFn._type - def __init__(self, name, arities, required_arity=0, rest_fn=None, meta=nil): BaseCode.__init__(self) self._name = name @@ -199,9 +196,6 @@ class NativeFn(BaseCode): def __init__(self, doc=None): BaseCode.__init__(self) - def type(self): - return NativeFn._type - def invoke(self, args): return self.inner_invoke(args) @@ -217,9 +211,6 @@ class Code(BaseCode): _type = object.Type(u"pixie.stdlib.Code") _immutable_fields_ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta", "_debug_points"] - def type(self): - return Code._type - def __init__(self, name, arity, bytecode, consts, stack_size, debug_points, meta=nil): BaseCode.__init__(self) self._arity = arity @@ -277,9 +268,6 @@ class VariadicCode(BaseCode): _immutable_fields_ = ["_required_arity", "_code", "_meta"] _type = object.Type(u"pixie.stdlib.VariadicCode") - def type(self): - return VariadicCode._type - def __init__(self, code, required_arity, meta=nil): BaseCode.__init__(self) self._required_arity = r_uint(required_arity) @@ -319,9 +307,6 @@ class Closure(BaseCode): _type = object.Type(u"pixie.stdlib.Closure") _immutable_fields_ = ["_closed_overs[*]", "_code", "_meta"] - def type(self): - return Closure._type - def __init__(self, code, closed_overs, meta=nil): BaseCode.__init__(self) affirm(isinstance(code, Code), u"Code argument to Closure must be an instance of Code") @@ -373,9 +358,6 @@ def get_debug_points(self): class Undefined(object.Object): _type = object.Type(u"pixie.stdlib.Undefined") - def type(self): - return Undefined._type - undefined = Undefined() @@ -413,9 +395,6 @@ class Var(BaseCode): _type = object.Type(u"pixie.stdlib.Var") _immutable_fields_ = ["_ns_ref"] - def type(self): - return Var._type - def __init__(self, ns_ref, ns, name): BaseCode.__init__(self) self._ns_ref = ns_ref @@ -497,9 +476,6 @@ class Namespace(object.Object): _immutable_fields_ = ["_rev?"] - def type(self): - return Namespace._type - def __init__(self, name): self._rev = 0 self._registry = {} @@ -636,9 +612,6 @@ class Protocol(object.Object): _immutable_fields_ = ["_rev?"] - def type(self): - return Protocol._type - def __init__(self, name): self._name = name self._polyfns = {} @@ -663,9 +636,6 @@ def satisfies(self, tp): class PolymorphicFn(BaseCode): _type = object.Type(u"pixie.stdlib.PolymorphicFn") - def type(self): - return PolymorphicFn._type - _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): @@ -745,9 +715,6 @@ class DoublePolymorphicFn(BaseCode): """A function that is polymorphic on the first two arguments""" _type = object.Type(u"pixie.stdlib.DoublePolymorphicFn") - def type(self): - return DefaultProtocolFn._type - _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): diff --git a/pixie/vm/cons.py b/pixie/vm/cons.py index bc27357e..27fcc109 100644 --- a/pixie/vm/cons.py +++ b/pixie/vm/cons.py @@ -7,9 +7,6 @@ class Cons(object.Object): _type = object.Type(u"pixie.stdlib.Cons") - def type(self): - return Cons._type - def __init__(self, head, tail, meta=nil): self._first = head self._next = tail diff --git a/pixie/vm/custom_types.py b/pixie/vm/custom_types.py index 0cbbc4ef..d5fb3047 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -216,8 +216,6 @@ def get_field(inst, field): class AbstractMutableCell(Object): _type = Type(u"pixie.stdlib.AbstractMutableCell") - def type(self): - return self._type def set_mutable_cell_value(self, ct, fields, nm, idx, value): pass diff --git a/pixie/vm/interpreter.py b/pixie/vm/interpreter.py index d279e2fb..cb11508d 100644 --- a/pixie/vm/interpreter.py +++ b/pixie/vm/interpreter.py @@ -159,10 +159,6 @@ def __init__(self, frame, val): self._frame = frame self._val = val - def type(self): - return ShallowContinuation._type - - def is_finished(self): return self._frame.finished diff --git a/pixie/vm/lazy_seq.py b/pixie/vm/lazy_seq.py index b95c3c94..65cb744c 100644 --- a/pixie/vm/lazy_seq.py +++ b/pixie/vm/lazy_seq.py @@ -9,9 +9,6 @@ class LazySeq(object.Object): _type = object.Type(u"pixie.stdlib.LazySeq") - def type(self): - return LazySeq._type - def __init__(self, fn, meta=nil): self._fn = fn self._meta = meta diff --git a/pixie/vm/libs/env.py b/pixie/vm/libs/env.py index 25bfb7ca..39b806df 100644 --- a/pixie/vm/libs/env.py +++ b/pixie/vm/libs/env.py @@ -10,9 +10,6 @@ class Environment(Object): _type = Type(u"pixie.stdlib.Environment") - def type(self): - return Environment._type - def val_at(self, key, not_found): if not isinstance(key, String): runtime_error(u"Environment variables are strings ") diff --git a/pixie/vm/libs/ffi.py b/pixie/vm/libs/ffi.py index 9cc0d348..cdd670b4 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -41,9 +41,6 @@ def __init__(self, name): class ExternalLib(object.Object): _type = object.Type(u"pixie.stdlib.ExternalLib") - def type(self): - return ExternalLib._type - def __init__(self, nm): assert isinstance(nm, unicode) self._name = nm @@ -94,9 +91,6 @@ class FFIFn(object.Object): _type = object.Type(u"pixie.stdlib.FFIFn") _immutable_fields_ = ["_name", "_f_ptr", "_c_fn_type"] - def type(self): - return FFIFn._type - def __init__(self, name, fn_ptr, c_fn_type): assert isinstance(c_fn_type, CFunctionType) self._rev = 0 @@ -219,9 +213,6 @@ class Buffer(PointerType): """ _type = object.Type(u"pixie.stdlib.Buffer") - def type(self): - return Buffer._type - def __init__(self, size): self._size = size self._used_size = 0 @@ -502,8 +493,6 @@ def ffi_type(self): class VoidP(PointerType): _type = cvoidp - def type(self): - return VoidP._type def __init__(self, raw_data): self._raw_data = raw_data @@ -604,9 +593,6 @@ def __init__(self, cft, raw_closure, id, fn): self._is_invoked = False self._unique_id = id - def type(self): - return CCallback._type - def get_raw_closure(self): return self._raw_closure diff --git a/pixie/vm/libs/path.py b/pixie/vm/libs/path.py index 8afd0ef2..e512efe8 100644 --- a/pixie/vm/libs/path.py +++ b/pixie/vm/libs/path.py @@ -8,9 +8,6 @@ class Path(Object): _type = Type(u"pixie.path.Path") - def type(self): - return Path._type - def __init__(self, top): self._path = rt.name(top) diff --git a/pixie/vm/libs/pxic/writer.py b/pixie/vm/libs/pxic/writer.py index 7aedcb17..0d2e511a 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -73,8 +73,6 @@ def finish(self): class WriterBox(Object): _type = Type(u"pixie.stdlib.WriterBox") - def type(self): - return WriterBox._type def __init__(self, wtr): self._pxic_writer = wtr diff --git a/pixie/vm/map_entry.py b/pixie/vm/map_entry.py index 543fb7d3..3b14a6c4 100644 --- a/pixie/vm/map_entry.py +++ b/pixie/vm/map_entry.py @@ -6,9 +6,6 @@ class MapEntry(object.Object): _type = object.Type(u"pixie.stdlib.MapEntry") - def type(self): - return MapEntry._type - def __init__(self, key, val): self._key = key self._val = val diff --git a/pixie/vm/numbers.py b/pixie/vm/numbers.py index b9363665..8e637365 100644 --- a/pixie/vm/numbers.py +++ b/pixie/vm/numbers.py @@ -13,9 +13,6 @@ class Number(object.Object): _type = object.Type(u"pixie.stdlib.Number") - def type(self): - return Number._type - class Integer(Number): _type = object.Type(u"pixie.stdlib.Integer", Number._type) _immutable_fields_ = ["_int_val"] @@ -32,9 +29,6 @@ def r_uint_val(self): def promote(self): return Integer(jit.promote(self._int_val)) - def type(self): - return Integer._type - zero_int = Integer(0) one_int = Integer(1) @@ -48,9 +42,6 @@ def __init__(self, bi_val): def bigint_val(self): return self._bigint_val - def type(self): - return BigInteger._type - class Float(Number): _type = object.Type(u"pixie.stdlib.Float", Number._type) _immutable_fields_ = ["_float_val"] @@ -61,9 +52,6 @@ def __init__(self, f_val): def float_val(self): return self._float_val - def type(self): - return Float._type - class Ratio(Number): _type = object.Type(u"pixie.stdlib.Ratio", Number._type) _immutable_fields_ = ["_numerator", "_denominator"] @@ -79,9 +67,6 @@ def numerator(self): def denominator(self): return self._denominator - def type(self): - return Ratio._type - @wrap_fn def ratio_write(obj): assert isinstance(obj, Ratio) diff --git a/pixie/vm/object.py b/pixie/vm/object.py index ccddf276..1b47e22c 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -26,8 +26,12 @@ class Object(object): """ _attrs_ = () + # Initialized after Type is defined. + _type = None + def type(self): - affirm(False, u".type isn't overloaded") + assert(isinstance(self.__class__._type, Type)) + return self.__class__._type @jit.unroll_safe def invoke(self, args): @@ -109,9 +113,6 @@ def __init__(self, name, parent=None, object_inited=True): def name(self): return self._name - def type(self): - return Type._type - def parent(self): return self._parent @@ -157,9 +158,6 @@ def __init__(self, msg, data): self._data = data self._trace = [] - def type(self): - return RuntimeException._type - def __repr__(self): import pixie.vm.rt as rt s = [] @@ -211,8 +209,7 @@ def safe_invoke(f, args): class ErrorInfo(Object): _type = Type(u"pixie.stdlib.ErrorInfo") - def type(self): - return ErrorInfo._type + def __init__(self): pass diff --git a/pixie/vm/persistent_hash_map.py b/pixie/vm/persistent_hash_map.py index c36dbbdc..7cab577c 100644 --- a/pixie/vm/persistent_hash_map.py +++ b/pixie/vm/persistent_hash_map.py @@ -19,9 +19,6 @@ def __init__(self): class PersistentHashMap(object.Object): _type = object.Type(u"pixie.stdlib.PersistentHashMap") - def type(self): - return PersistentHashMap._type - def __init__(self, cnt, root, meta=nil): self._cnt = cnt self._root = root @@ -62,9 +59,6 @@ def without(self, key): class INode(object.Object): _type = object.Type(u"pixie.stdlib.INode") - def type(self): - return INode._type - def assoc_inode(self, shift, hash_val, key, val, added_leaf): pass diff --git a/pixie/vm/persistent_hash_set.py b/pixie/vm/persistent_hash_set.py index 9327ea42..f2bd5d4a 100644 --- a/pixie/vm/persistent_hash_set.py +++ b/pixie/vm/persistent_hash_set.py @@ -12,9 +12,6 @@ class PersistentHashSet(object.Object): _type = object.Type(u"pixie.stdlib.PersistentHashSet") - def type(self): - return PersistentHashSet._type - def __init__(self, meta, m): self._meta = meta self._map = m diff --git a/pixie/vm/persistent_list.py b/pixie/vm/persistent_list.py index 54d6b11a..10514b43 100644 --- a/pixie/vm/persistent_list.py +++ b/pixie/vm/persistent_list.py @@ -8,9 +8,6 @@ class PersistentList(object.Object): _type = object.Type(u"pixie.stdlib.PersistentList") - def type(self): - return PersistentList._type - def __init__(self, head, tail, cnt, meta=nil): self._first = head self._next = tail @@ -100,8 +97,6 @@ def _with_meta(self, meta): class EmptyList(object.Object): _type = object.Type(u"pixie.stdlib.EmptyList") - def type(self): - return EmptyList._type def __init__(self, meta=nil): self._meta = meta diff --git a/pixie/vm/persistent_vector.py b/pixie/vm/persistent_vector.py index 202e3c72..2740caf5 100644 --- a/pixie/vm/persistent_vector.py +++ b/pixie/vm/persistent_vector.py @@ -13,9 +13,6 @@ class Node(object.Object): _type = object.Type(u"pixie.stdlib.PersistentVectorNode") - def type(self): - return Node._type - def __init__(self, edit, array=None): self._edit = edit self._array = [None] * 32 if array is None else array @@ -27,9 +24,6 @@ def __init__(self, edit, array=None): class PersistentVector(object.Object): _type = object.Type(u"pixie.stdlib.PersistentVector") - def type(self): - return PersistentVector._type - def __init__(self, meta, cnt, shift, root, tail): self._meta = meta self._cnt = cnt @@ -211,9 +205,6 @@ def new_path(edit, level, node): class TransientVector(object.Object): _type = object.Type(u"pixie.stdlib.TransientVector") - def type(self): - return TransientVector._type - def __init__(self, cnt, shift, root, tail): self._cnt = cnt self._shift = shift diff --git a/pixie/vm/primitives.py b/pixie/vm/primitives.py index 6bab30aa..5924b6a5 100644 --- a/pixie/vm/primitives.py +++ b/pixie/vm/primitives.py @@ -1,25 +1,15 @@ import pixie.vm.object as object - class Nil(object.Object): _type = object.Type(u"pixie.stdlib.Nil") def __repr__(self): return u"nil" - def type(self): - return Nil._type - - nil = Nil() - class Bool(object.Object): _type = object.Type(u"pixie.stdlib.Bool") - def type(self): - return Bool._type - - true = Bool() false = Bool() diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 84dccfba..09e4fdf9 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -43,9 +43,6 @@ class PlatformReader(object.Object): _type = object.Type(u"PlatformReader") - def type(self): - return PlatformReader._type - def read(self): assert False @@ -57,8 +54,6 @@ def reset_line(self): class StringReader(PlatformReader): _type = object.Type(u"pixie.stdlib.StringReader") - def type(self): - return StringReader._type def __init__(self, s): affirm(isinstance(s, unicode), u"StringReader requires unicode") @@ -111,8 +106,6 @@ def reader_fn(fn): class LinePromise(object.Object): _type = object.Type(u"pixie.stdlib.LinePromise") - def type(self): - return LinePromise._type def __init__(self): self._chrs = [] @@ -770,9 +763,6 @@ def read_symbol(rdr, ch): class EOF(object.Object): _type = object.Type(u"EOF") - def type(self): - return EOF._type - eof = EOF() diff --git a/pixie/vm/reduced.py b/pixie/vm/reduced.py index d1d703ea..c94739a6 100644 --- a/pixie/vm/reduced.py +++ b/pixie/vm/reduced.py @@ -6,8 +6,6 @@ class Reduced(object.Object): _type = object.Type(u"pixie.stdlib.Reduced") - def type(self): - return Reduced._type def __init__(self, boxed_value): self._boxed_value = boxed_value diff --git a/pixie/vm/stacklet.py b/pixie/vm/stacklet.py index da42cfc0..d4e8e5c4 100644 --- a/pixie/vm/stacklet.py +++ b/pixie/vm/stacklet.py @@ -25,9 +25,6 @@ def __init__(self, h): self._stacklet_handle = h self._used = False - def type(self): - return self._type - def invoke(self, args): affirm(not self._used, u"Can only call a given stacklet handle once.") affirm(len(args) == 1, u"Only one arg should be handed to a stacklet handle") @@ -53,4 +50,4 @@ def new_handler(h, _): def new_stacklet(fn): global_state._val = fn h = global_state._th.new(new_handler) - return StackletHandle(h) \ No newline at end of file + return StackletHandle(h) diff --git a/pixie/vm/string.py b/pixie/vm/string.py index c9be8844..17327fa9 100644 --- a/pixie/vm/string.py +++ b/pixie/vm/string.py @@ -11,9 +11,6 @@ class String(Object): _type = Type(u"pixie.stdlib.String") - def type(self): - return String._type - def __init__(self, s): #assert isinstance(s, unicode) self._str = s @@ -76,9 +73,6 @@ class Character(Object): _type = Type(u"pixie.stdlib.Character") _immutable_fields_ = ["_char_val"] - def type(self): - return Character._type - def __init__(self, i): assert isinstance(i, int) self._char_val = i diff --git a/pixie/vm/string_builder.py b/pixie/vm/string_builder.py index d2a94296..588b00a5 100644 --- a/pixie/vm/string_builder.py +++ b/pixie/vm/string_builder.py @@ -6,9 +6,6 @@ class StringBuilder(Object): _type = Type(u"pixie.stdlib.StringBuilder") - def type(self): - return StringBuilder._type - def __init__(self): self._strs = [] @@ -34,4 +31,4 @@ def _str(self): @as_var("-string-builder") def _string_builder(): - return StringBuilder() \ No newline at end of file + return StringBuilder() diff --git a/pixie/vm/threads.py b/pixie/vm/threads.py index 5140608b..b523aa2f 100644 --- a/pixie/vm/threads.py +++ b/pixie/vm/threads.py @@ -65,9 +65,6 @@ class Lock(Object): def __init__(self, ll_lock): self._ll_lock = ll_lock - def type(self): - return Lock._type - @as_var("-create-lock") def _create_lock(): diff --git a/pixie/vm/util.py b/pixie/vm/util.py index 931ba731..cd97ed7b 100644 --- a/pixie/vm/util.py +++ b/pixie/vm/util.py @@ -78,9 +78,6 @@ def mix_coll_hash(hash, count): class HashingState(Object): _type = Type(u"pixie.stdlib.HashingState") - def type(self): - return HashingState._type - def __init__(self): self._n = r_uint(0) self._hash = r_uint(1) From 6e9ec11b8608e80fc4bf817490c27666f6388909 Mon Sep 17 00:00:00 2001 From: keymone Date: Thu, 11 Feb 2016 18:17:44 +0100 Subject: [PATCH 321/349] Make pixie.math/exp10 platform-specific OS X math library doesn't define exp10, define it within math.pxi instead. --- pixie/math.pxi | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pixie/math.pxi b/pixie/math.pxi index 0cb53ae1..253bc132 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -1,5 +1,6 @@ (ns pixie.math - (:require [pixie.ffi-infer :as i])) + (:require [pixie.ffi-infer :as i] + [pixie.string :as s])) (i/with-config {:library "m" :cxx-flags ["-lm"] @@ -45,7 +46,8 @@ (i/defcfn exp) (i/defcfn exp2) - (i/defcfn exp10) + (if-not (s/starts-with? pixie.platform/name "darwin") + (i/defcfn exp10)) (i/defcfn expm1) (i/defcfn log) @@ -94,3 +96,6 @@ (i/defcfn erf) (i/defcfn erfc)) + +(if (s/starts-with? pixie.platform/name "darwin") + (defn exp10 [x] (pow 10.0 x))) From 7b0680be167c2f6aebf6586ed3ce255b17bf7e43 Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Thu, 11 Feb 2016 16:12:40 +0000 Subject: [PATCH 322/349] Added iterate function and tests --- pixie/stdlib.pxi | 8 ++++++++ tests/pixie/tests/test-stdlib.pxi | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 46f656a1..93abc01c 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -3072,3 +3072,11 @@ ex: (vary-meta x assoc :foo 42)" (swap! cache assoc argsv ret) ret) val))))) + +(defn iterate + {:doc "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of + side-effects" + :signatures [[f x]] + :added "0.1"} + [f x] + (lazy-seq (cons x (iterate f (f x))))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 6dfd3efc..0868cac8 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -761,3 +761,7 @@ (t/deftest test-memoize (let [f (memoize rand)] (t/assert= (f) (f)))) + +(t/deftest test-iterate + (t/assert= (take 5 (iterate inc 5)) '(5 6 7 8 9)) + (t/assert= (str (type (iterate inc 1))) "")) From 3b9d76a40bfc6614fafbe143de6b6743bc2556d2 Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Fri, 12 Feb 2016 16:10:32 +0000 Subject: [PATCH 323/349] Added IReduce to iterate --- pixie/stdlib.pxi | 10 ++++++++++ tests/pixie/tests/test-stdlib.pxi | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 93abc01c..de683993 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -3073,6 +3073,16 @@ ex: (vary-meta x assoc :foo 42)" ret) val))))) +(deftype Iterate [f x] + IReduce + (-reduce [self f init] + (loop [acc (f (if (nil? init) + (first self) + init))] + (if (reduced? acc) + @acc + (recur (f acc)))))) + (defn iterate {:doc "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects" diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 0868cac8..70adcd6e 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -764,4 +764,5 @@ (t/deftest test-iterate (t/assert= (take 5 (iterate inc 5)) '(5 6 7 8 9)) - (t/assert= (str (type (iterate inc 1))) "")) + (t/assert= (str (type (iterate inc 1))) "") + (t/assert= (reduce (fn [a v] (if (< a 10) (+ a v) (reduced a))) (iterate (partial + 2) 1)) 16)) From 027220f17607852550e54e13abedd2e7ece55a31 Mon Sep 17 00:00:00 2001 From: keymone Date: Sat, 13 Feb 2016 11:11:15 +0100 Subject: [PATCH 324/349] find python using which -a --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 15f691e5..e27182ee 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ all: help EXTERNALS=externals -PYTHON ?= python2 +PYTHON ?= `env which -a python2 python2.7 | head -n1` PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy From ffbb0822a80e6f4344c5d179bba233b81c62410e Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Mon, 15 Feb 2016 16:27:04 +0000 Subject: [PATCH 325/349] Refactored iterate into type and added IReduce --- pixie/stdlib.pxi | 14 ++++++++------ tests/pixie/tests/test-stdlib.pxi | 5 +++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index de683993..311df7fb 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -3075,13 +3075,15 @@ ex: (vary-meta x assoc :foo 42)" (deftype Iterate [f x] IReduce - (-reduce [self f init] - (loop [acc (f (if (nil? init) - (first self) - init))] + (-reduce [self rf init] + (loop [col (rest self) + acc (rf init (first self))] (if (reduced? acc) @acc - (recur (f acc)))))) + (recur (rest col) (rf acc (first col)))))) + ISeq + (-seq [self] + (cons x (lazy-seq* (fn [] (->Iterate f (f x))))))) (defn iterate {:doc "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of @@ -3089,4 +3091,4 @@ ex: (vary-meta x assoc :foo 42)" :signatures [[f x]] :added "0.1"} [f x] - (lazy-seq (cons x (iterate f (f x))))) + (->Iterate f x)) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 70adcd6e..12ad9912 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -764,5 +764,6 @@ (t/deftest test-iterate (t/assert= (take 5 (iterate inc 5)) '(5 6 7 8 9)) - (t/assert= (str (type (iterate inc 1))) "") - (t/assert= (reduce (fn [a v] (if (< a 10) (+ a v) (reduced a))) (iterate (partial + 2) 1)) 16)) + (t/assert= (reduce (fn [a v] (reduced "foo")) 0 (iterate inc 1)) "foo") + (t/assert= (reduce (fn [a v] (if (< a 10) (+ a v) (reduced a))) 0 (iterate (partial + 2) 1)) 16)) + From 501b241d6e31753decb3d9435830180466cb3b5f Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Thu, 18 Feb 2016 16:56:06 +0100 Subject: [PATCH 326/349] Added mkdtmp to stdlib --- pixie/stdlib.pxi | 1 + 1 file changed, 1 insertion(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 311df7fb..8953592d 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -17,6 +17,7 @@ (def srand (ffi-fn libc "srand" [CInt] CInt)) (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) (def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) +(def mkdtemp (ffi-fn libc "mkdtemp" [CCharP] CCharP)) (def libm (ffi-library (str "libm." pixie.platform/so-ext))) (def atan2 (ffi-fn libm "atan2" [CDouble CDouble] CDouble)) From df8afb0bc1486b116373a7361832efe1f510d2ac Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Thu, 18 Feb 2016 17:08:30 +0100 Subject: [PATCH 327/349] Added rmdir to stdlib --- pixie/stdlib.pxi | 1 + 1 file changed, 1 insertion(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 8953592d..02916e72 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -18,6 +18,7 @@ (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) (def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) (def mkdtemp (ffi-fn libc "mkdtemp" [CCharP] CCharP)) +(def rmdir (ffi-fn libc "rmdir" [CCharP] CCharP)) (def libm (ffi-library (str "libm." pixie.platform/so-ext))) (def atan2 (ffi-fn libm "atan2" [CDouble CDouble] CDouble)) From 8bed3a84edac36705e6e765119d4a417610a75e6 Mon Sep 17 00:00:00 2001 From: Matt Carroll Date: Thu, 18 Feb 2016 17:26:15 +0100 Subject: [PATCH 328/349] Added mkdir and rm --- pixie/stdlib.pxi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 02916e72..8ccfe2df 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -18,7 +18,9 @@ (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) (def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) (def mkdtemp (ffi-fn libc "mkdtemp" [CCharP] CCharP)) +(def mkdir (ffi-fn libc "mkdir" [CCharP] CCharP)) (def rmdir (ffi-fn libc "rmdir" [CCharP] CCharP)) +(def rm (ffi-fn libc "remove" [CCharP] CCharP)) (def libm (ffi-library (str "libm." pixie.platform/so-ext))) (def atan2 (ffi-fn libm "atan2" [CDouble CDouble] CDouble)) From 3f81e6576eb58827a519ea985f42971e0ae1163f Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 19 Feb 2016 00:06:19 +0000 Subject: [PATCH 329/349] fixes the speed of iterates reduce the reduce implementation was creating some lazy lists --- pixie/stdlib.pxi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 311df7fb..fab91331 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -3076,11 +3076,11 @@ ex: (vary-meta x assoc :foo 42)" (deftype Iterate [f x] IReduce (-reduce [self rf init] - (loop [col (rest self) - acc (rf init (first self))] + (loop [next (f x) + acc (rf init x)] (if (reduced? acc) @acc - (recur (rest col) (rf acc (first col)))))) + (recur (f next) (rf acc next))))) ISeq (-seq [self] (cons x (lazy-seq* (fn [] (->Iterate f (f x))))))) From 94d607944ecdc673964c2d6969c8e6f73ae8abbc Mon Sep 17 00:00:00 2001 From: keymone Date: Fri, 19 Feb 2016 16:19:14 +0100 Subject: [PATCH 330/349] deref macro? arg if it's a var --- pixie/vm/stdlib.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 79a9061c..d8611d72 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -687,7 +687,8 @@ def set_macro(f): @returns(bool) @as_var("macro?") -def macro_QMARK_(f): +def macro_QMARK_(v): + f = v.deref() if isinstance(v, Var) else v return true if isinstance(f, BaseCode) and f.is_macro() else false @returns(unicode) From 02971267f7fa291c87d89962448f951c947d0854 Mon Sep 17 00:00:00 2001 From: keymone Date: Fri, 19 Feb 2016 17:37:58 +0100 Subject: [PATCH 331/349] look for symbol in current ns --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 3d9c2443..77b3cede 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2726,7 +2726,7 @@ Calling this function on something that is not ISeqable returns a seq with that (= () form)) form (let [[sym & args] form - fvar (resolve sym)] + fvar (resolve-in *ns* sym)] (if (and fvar (macro? @fvar)) (apply @fvar args) form)))) From bb7b335d89b141a4bcf4e7af21d17ce4e65ccce1 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sat, 5 Mar 2016 15:20:41 +0000 Subject: [PATCH 332/349] catch exception when compiling with -c --- target.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/target.py b/target.py index 7eb8932c..71be1c7d 100644 --- a/target.py +++ b/target.py @@ -117,8 +117,11 @@ def __init__(self, filename): def inner_invoke(self, args): import pixie.vm.rt as rt - - rt.compile_file(rt.wrap(self._filename)) + try: + rt.compile_file(rt.wrap(self._filename)) + except WrappedException as ex: + print "Error: ", ex._ex.__repr__() + os._exit(1) class IsPreloadFlag(object): From bbdde9cd2e9768b95ec6071619a15c1b54d3d080 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 6 Mar 2016 01:02:39 +0000 Subject: [PATCH 333/349] keywords can start with numbers or true, false, nil --- pixie/vm/reader.py | 21 ++++++++++++++++--- tests/pixie/tests/test-keywords.pxi | 32 ++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 09e4fdf9..9cc2e36a 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -10,7 +10,6 @@ from pixie.vm.keyword import keyword, Keyword import pixie.vm.rt as rt from pixie.vm.persistent_vector import EMPTY as EMPTY_VECTOR -from pixie.vm.libs.libedit import _readline from pixie.vm.string import Character from pixie.vm.code import wrap_fn from pixie.vm.persistent_hash_map import EMPTY as EMPTY_MAP @@ -306,6 +305,21 @@ def invoke(self, rdr, ch): return cons(symbol(u"quote"), cons(itm)) class KeywordReader(ReaderHandler): + def read(self, rdr): + acc = [] + + try: + while True: + ch = rdr.read() + if is_whitespace(ch) or is_terminating_macro(ch): + rdr.unread() + break + acc.append(ch) + except EOFError: + pass + sym_str = u"".join(acc) + return symbol(sym_str) + def fqd(self, itm): ns_alias = rt.namespace(itm) current_nms = rt.ns.deref() @@ -319,11 +333,12 @@ def fqd(self, itm): def invoke(self, rdr, ch): ch = rdr.read() if ch == u":": - itm = read_inner(rdr, True) + itm = self.read(rdr) return self.fqd(itm) else: rdr.unread() - itm = read_inner(rdr, True) + itm = self.read(rdr) + return keyword(rt.name(itm), rt.namespace(itm)) class LiteralStringReader(ReaderHandler): diff --git a/tests/pixie/tests/test-keywords.pxi b/tests/pixie/tests/test-keywords.pxi index 06e2deb7..1094cf45 100644 --- a/tests/pixie/tests/test-keywords.pxi +++ b/tests/pixie/tests/test-keywords.pxi @@ -6,7 +6,6 @@ (t/assert= (:a m) 1) (t/assert= (:b m) 2) (t/assert= (:c m) 3) - (t/assert= (:d m) nil) (t/assert= (:d m :foo) :foo))) @@ -29,9 +28,40 @@ (t/assert= (not= :foo/bar :cat/bar) true) (t/assert= (not= :foo/cat :foo/dog) true)) +(t/deftest keyword-reader + (t/assert= (read-string ":1") :1) + (t/assert= (read-string ":1") :1) + (t/assert= (read-string ":1.0") :1.0) + (t/assert= (read-string ":foo") :foo) + (t/assert= (read-string ":1foo") :1foo) + (t/assert= (read-string ":foo/bar") :foo/bar) + (t/assert= (read-string ":1foo/1bar") :1foo/1bar) + (t/assert= (read-string ":nil") :nil) + (t/assert= (read-string ":true") :true) + (t/assert= (read-string ":false") :false) + + ;; We are reading at runtime so the namespace isn't + ;; going to be pixie.test.test-keywords. Its probably + ;; 'user but lets explicitly set it. + ;; The refer-ns is to initialize a new space + (refer-ns 'my.other.ns 'my.fake.core 'fake) + (binding [*ns* (the-ns 'my.other.ns)] + (t/assert= (read-string "::1") :my.other.ns/1) + (t/assert= (read-string "::1.0") :my.other.ns/1.0) + (t/assert= (read-string "::foo") :my.other.ns/foo) + (t/assert= (read-string "::true") :my.other.ns/true))) + (t/deftest string-to-keyword + (t/assert= (keyword "1") :1) + (t/assert= (keyword "1") :1) + (t/assert= (keyword "1.0") :1.0) (t/assert= (keyword "foo") :foo) + (t/assert= (keyword "1foo") :1foo) (t/assert= (keyword "foo/bar") :foo/bar) + (t/assert= (keyword "1foo/1bar") :1foo/1bar) + (t/assert= (keyword "nil") :nil) + (t/assert= (keyword "true") :true) + (t/assert= (keyword "false") :false) (t/assert-throws? (keyword 1)) (t/assert-throws? (keyword :a)) (t/assert-throws? (keyword 'a)) From a6ecc893395ef8d2f501962afbff7a03cb174901 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 6 Mar 2016 10:52:40 +0000 Subject: [PATCH 334/349] simplify --- pixie/vm/reader.py | 37 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/pixie/vm/reader.py b/pixie/vm/reader.py index 9cc2e36a..4a6ab292 100644 --- a/pixie/vm/reader.py +++ b/pixie/vm/reader.py @@ -305,21 +305,6 @@ def invoke(self, rdr, ch): return cons(symbol(u"quote"), cons(itm)) class KeywordReader(ReaderHandler): - def read(self, rdr): - acc = [] - - try: - while True: - ch = rdr.read() - if is_whitespace(ch) or is_terminating_macro(ch): - rdr.unread() - break - acc.append(ch) - except EOFError: - pass - sym_str = u"".join(acc) - return symbol(sym_str) - def fqd(self, itm): ns_alias = rt.namespace(itm) current_nms = rt.ns.deref() @@ -333,11 +318,11 @@ def fqd(self, itm): def invoke(self, rdr, ch): ch = rdr.read() if ch == u":": - itm = self.read(rdr) + ch = rdr.read() + itm = read_symbol(rdr, ch, False) return self.fqd(itm) else: - rdr.unread() - itm = self.read(rdr) + itm = read_symbol(rdr, ch, False) return keyword(rt.name(itm), rt.namespace(itm)) @@ -754,7 +739,7 @@ def read_number(rdr, ch): return parsed return Symbol(joined) -def read_symbol(rdr, ch): +def read_symbol(rdr, ch, convert_primitives=True): acc = [ch] try: while True: @@ -767,12 +752,14 @@ def read_symbol(rdr, ch): pass sym_str = u"".join(acc) - if sym_str == u"true": - return true - if sym_str == u"false": - return false - if sym_str == u"nil": - return nil + + if convert_primitives: + if sym_str == u"true": + return true + if sym_str == u"false": + return false + if sym_str == u"nil": + return nil return symbol(sym_str) class EOF(object.Object): From 90ea228d09cd03eca90f25acf0cb71e4a3b18a32 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Sun, 6 Mar 2016 16:07:59 +0000 Subject: [PATCH 335/349] Update to most recent pypy --- Makefile | 2 +- pixie/vm/c_api.py | 5 +---- pixie/vm/object.py | 1 - pixie/vm/threads.py | 50 +++------------------------------------------ 4 files changed, 5 insertions(+), 53 deletions(-) diff --git a/Makefile b/Makefile index e27182ee..8a5f9ccf 100644 --- a/Makefile +++ b/Makefile @@ -53,7 +53,7 @@ externals.fetched: $(EXTERNALS)/pypy: mkdir $(EXTERNALS); \ cd $(EXTERNALS); \ - curl https://bitbucket.org/pypy/pypy/get/81254.tar.bz2 > pypy.tar.bz2; \ + curl https://bitbucket.org/pypy/pypy/get/default.tar.bz2 > pypy.tar.bz2; \ mkdir pypy; \ cd pypy; \ tar -jxf ../pypy.tar.bz2 --strip-components=1 diff --git a/pixie/vm/c_api.py b/pixie/vm/c_api.py index 45888295..a050a070 100644 --- a/pixie/vm/c_api.py +++ b/pixie/vm/c_api.py @@ -1,10 +1,7 @@ - - -from rpython.rlib.entrypoint import entrypoint_highlevel, RPython_StartupCode +from rpython.rlib.entrypoint import entrypoint_highlevel from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rtyper.lltypesystem.lloperation import llop - @entrypoint_highlevel('main', [rffi.CCHARP], c_name='pixie_init') def pypy_execute_source(ll_progname): from target import init_vm diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 1b47e22c..2ef03de3 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -8,7 +8,6 @@ def __init__(self): self._registry = [] def register(self, o): - print "register finalizer ", o self._registry.append(o) def run_finalizers(self): diff --git a/pixie/vm/threads.py b/pixie/vm/threads.py index b523aa2f..e42d7d18 100644 --- a/pixie/vm/threads.py +++ b/pixie/vm/threads.py @@ -6,8 +6,6 @@ from pixie.vm.code import as_var import pixie.vm.rt as rt -from rpython.rlib.objectmodel import invoke_around_extcall - class Bootstrapper(object): def __init__(self): self._is_inited = False @@ -15,10 +13,9 @@ def __init__(self): def init(self): if not self._is_inited: - self._is_inited = True self._lock = rthread.allocate_lock() - rgil.gil_allocate() - invoke_around_extcall(before_external_call, after_external_call) + self._is_inited = True + rgil.allocate() def aquire(self, fn): self.init() @@ -55,7 +52,7 @@ def new_thread(fn): @as_var("-yield-thread") def yield_thread(): - do_yield_thread() + rgil.yield_thread() return nil # Locks @@ -86,46 +83,5 @@ def _release_lock(self): return rt.wrap(self._ll_lock.release()) - -## From PYPY - - -after_thread_switch = lambda: None # hook for signal.py - -# Fragile code below. We have to preserve the C-level errno manually... - -def before_external_call(): - # this function must not raise, in such a way that the exception - # transformer knows that it cannot raise! - rgil.gil_release() -before_external_call._gctransformer_hint_cannot_collect_ = True -before_external_call._dont_reach_me_in_del_ = True - -def after_external_call(): - rgil.gil_acquire() - rthread.gc_thread_run() - after_thread_switch() -after_external_call._gctransformer_hint_cannot_collect_ = True -after_external_call._dont_reach_me_in_del_ = True - -# The _gctransformer_hint_cannot_collect_ hack is needed for -# translations in which the *_external_call() functions are not inlined. -# They tell the gctransformer not to save and restore the local GC -# pointers in the shadow stack. This is necessary because the GIL is -# not held after the call to before_external_call() or before the call -# to after_external_call(). - -def do_yield_thread(): - # explicitly release the gil, in a way that tries to give more - # priority to other threads (as opposed to continuing to run in - # the same thread). - if rgil.gil_yield_thread(): - rthread.gc_thread_run() - after_thread_switch() -do_yield_thread._gctransformer_hint_close_stack_ = True -do_yield_thread._dont_reach_me_in_del_ = True -do_yield_thread._dont_inline_ = True - -# do_yield_thread() needs a different hint: _gctransformer_hint_close_stack_. # The *_external_call() functions are themselves called only from the rffi # module from a helper function that also has this hint. From 46d8277d6eefe0696f1cf12dc08da1850a17186e Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Mon, 7 Mar 2016 21:56:30 +0000 Subject: [PATCH 336/349] fix compiler --- pixie/vm/compiler.py | 8 +++---- tests/pixie/tests/test-compiler.pxi | 36 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/pixie/vm/compiler.py b/pixie/vm/compiler.py index 5d0f214f..60cc353a 100644 --- a/pixie/vm/compiler.py +++ b/pixie/vm/compiler.py @@ -539,8 +539,8 @@ def compile_fn_body(name, args, body, ctx): compile_form(body, new_ctx) else: while body is not nil: - if rt.next(body) is nil: - new_ctx.enable_tail_call() + #if rt.next(body) is nil: + # new_ctx.enable_tail_call() compile_form(rt.first(body), new_ctx) body = rt.next(body) if body is not nil: @@ -635,7 +635,7 @@ def compile_quote(form, ctx): def compile_recur(form, ctx): form = form.next() - #affirm(ctx.can_tail_call, u"Can't recur in non-tail position") + affirm(ctx.can_tail_call, u"Can't recur in non-tail position") ctc = ctx.can_tail_call ctx.disable_tail_call() args = 0 @@ -697,7 +697,7 @@ def compile_loop(form, ctx): bindings = rt.first(form) affirm(isinstance(bindings, PersistentVector), u"Loop bindings must be a vector") body = rt.next(form) - + ctx.enable_tail_call() ctc = ctx.can_tail_call ctx.disable_tail_call() diff --git a/tests/pixie/tests/test-compiler.pxi b/tests/pixie/tests/test-compiler.pxi index 944343d4..751ee95e 100644 --- a/tests/pixie/tests/test-compiler.pxi +++ b/tests/pixie/tests/test-compiler.pxi @@ -35,3 +35,39 @@ (t/deftest test-deftype-mutables (mutate! (->Foo 0))) + +(t/deftest test-recur-must-tail + (t/assert-throws? + (eval + '(loop [n 0] + (inc (recur n))))) + + (t/assert-throws? + (eval + '(fn [n] + (if (zero? n) + 1 + (* n (recur (dec n))))))) + +(t/assert-throws? + (eval + '(fn [n] + (if (zero? n) + (* n (recur (dec n))) + 1)))) + + (t/assert= + (eval + '(loop [n 0] + (if (= 10 n) + n + (recur (inc n))))) + 10) + + (t/assert= + (eval + '(loop [n 0] + (if (not= 10 n) + (recur (inc n)) + n))) + 10)) From b3d41163d48fc51dc4c94acc6975e6fd890aa0b5 Mon Sep 17 00:00:00 2001 From: angusiguess Date: Tue, 8 Mar 2016 23:09:02 -0400 Subject: [PATCH 337/349] Add sequence to stdlib --- pixie/stdlib.pxi | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 77b3cede..a529de33 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -903,7 +903,7 @@ If further arguments are passed, invokes the method named by symbol, passing the (if (next coll) (recur (next coll)) (first coll)) - + (satisfies? ISeqable coll) (recur (seq coll)))) @@ -2106,7 +2106,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} val not-found))) ISeq - (-first [this] + (-first [this] (when (not= start stop) start)) (-next [this] @@ -2188,6 +2188,14 @@ For more information, see http://clojure.org/special_forms#binding-forms"} ([pred coll] (filter (complement pred) coll))) +(defn sequence + "Returns a lazy sequence of `data`, optionally transforming it using `xform`. + Given an `eduction`, produces a lazy sequence of it." + ([eduction] + (lazy-seq (cons (first eduction) (sequence (rest eduction))))) + ([xform data] + (sequence (eduction xform data)))) + (defn distinct {:doc "Returns the distinct elements in the collection." :signatures [[] [coll]] @@ -3080,7 +3088,7 @@ ex: (vary-meta x assoc :foo 42)" (deftype Iterate [f x] IReduce (-reduce [self rf init] - (loop [next (f x) + (loop [next (f x) acc (rf init x)] (if (reduced? acc) @acc From d340de4ee39936246a6f026f14e3a4b3ba047bfc Mon Sep 17 00:00:00 2001 From: angusiguess Date: Wed, 9 Mar 2016 10:22:12 -0400 Subject: [PATCH 338/349] Handle the empty case, fix eduction to conform to seqable --- pixie/stdlib.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index a529de33..ff070380 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1907,7 +1907,7 @@ not enough elements were present." ISeqable (-seq [self] - (reduce conj self))) + (seq (reduce conj self)))) (defn eduction "Returns a reducible/iterable application of the transducers @@ -2192,7 +2192,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} "Returns a lazy sequence of `data`, optionally transforming it using `xform`. Given an `eduction`, produces a lazy sequence of it." ([eduction] - (lazy-seq (cons (first eduction) (sequence (rest eduction))))) + (when (seq eduction) (lazy-seq (cons (first eduction) (sequence (rest eduction)))))) ([xform data] (sequence (eduction xform data)))) From 1626fff48d763d86f9c0d5c7b5a1ccff14f7017f Mon Sep 17 00:00:00 2001 From: angusiguess Date: Wed, 9 Mar 2016 10:22:20 -0400 Subject: [PATCH 339/349] Add tests --- tests/pixie/test-sequence.pxi | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tests/pixie/test-sequence.pxi diff --git a/tests/pixie/test-sequence.pxi b/tests/pixie/test-sequence.pxi new file mode 100644 index 00000000..e8a8e748 --- /dev/null +++ b/tests/pixie/test-sequence.pxi @@ -0,0 +1,23 @@ +(ns pixie.tests.test-sequence + (:require [pixie.test :as t])) + +(t/deftest empty-sequences + (t/assert= '() (take 1 (sequence (map inc) '()))) + (t/assert= '() (take 1 (sequence (map inc) []))) + (t/assert= '() (take 1 (sequence (map inc) #{}))) + (t/assert= '() (take 1 (sequence (map inc) {})))) + +(t/deftest non-empty-sequences + (t/assert= '(1 3) (take 2 (sequence (comp + (filter even?) + (map inc)) (range 3)))) + (t/assert= '(1) (take 1 (sequence (distinct) (repeat 4 1))))) + +(t/deftest early-terminating-sequences + (t/assert= '() (take 5 (sequence (filter (fn [x] false)) (repeat 8 8)))) + (t/assert= '(1 2) (take 3 (sequence (map identity) [1 2]))) + (t/assert= #{[:a 1] [:b 2]} (into #{} (take 3 (sequence (filter (fn [[k v]] + (keyword? k)) {:a 1 + :b 2 + "c" 3 + "d" 4})))))) From 283e6477709fa5e5d743f29abbe90da99fe5cc36 Mon Sep 17 00:00:00 2001 From: notnew <> Date: Sat, 12 Mar 2016 20:49:26 -0600 Subject: [PATCH 340/349] fix transducer composition problems, add tests remove `preserving-reduced` from several transducers. This was modifying the reducing function passed to the transducer, causing reduced values to be wrapped in `reduced` twice, so the reducing process wasn't completely unwrapping reduced values when finishing. Reducing functions only need to be wrapped with `preserving-reduced` if they call `reduce` themselves. (Like `cat` and `pixie.io.common/stream-reducer`) Also fixes a problem with the `take` transducer consuming one more element than needed. Add tests for these problems. --- pixie/io.pxi | 30 +++++++++--------- pixie/stdlib.pxi | 42 ++++++++++++------------- tests/pixie/tests/test-io.pxi | 33 ++++++++++++++++++-- tests/pixie/tests/test-stdlib.pxi | 52 ++++++++++++++++++++++++++----- 4 files changed, 110 insertions(+), 47 deletions(-) diff --git a/pixie/io.pxi b/pixie/io.pxi index 3dd8bdf2..a6ed1286 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -66,14 +66,13 @@ (str string)))))) IReduce (-reduce [this f init] - (let [rrf (preserving-reduced f)] - (loop [acc init] - (if-let [line (-read-line this)] - (let [result (rrf acc line)] - (if (not (reduced? result)) - (recur result) - @result)) - acc))))) + (loop [acc init] + (if-let [line (-read-line this)] + (let [result (f acc line)] + (if (reduced? result) + @result + (recur result))) + acc)))) (defn line-reader [input-stream] @@ -150,14 +149,13 @@ (deftype BufferedInputStream [upstream idx buffer] IReduce (-reduce [this f init] - (let [rrf (preserving-reduced f)] - (loop [acc init] - (if-let [next-byte (read-byte this)] - (let [step (rrf acc next-byte)] - (if (reduced? step) - @step - (recur step))) - acc)))) + (loop [acc init] + (if-let [next-byte (read-byte this)] + (let [result (f acc next-byte)] + (if (reduced? result) + @result + (recur result))) + acc))) IByteInputStream (read-byte [this] (when (= idx (count buffer)) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 77b3cede..92b09062 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1640,21 +1640,25 @@ The new value is thus `(apply f current-value-of-atom args)`." (let [idx (if (neg? i) (+ i (count coll)) i)] (nth coll idx not-found))))) +(defn ensure-reduced [x] + (if (reduced? x) + x + (reduced x))) + (defn take {:doc "Takes n elements from the collection, or fewer, if not enough." :added "0.1"} ([n] (fn [rf] - (let [rrf (preserving-reduced rf) - seen (atom 0)] + (let [seen (atom 0)] (fn ([] (rf)) ([result] (rf result)) ([result input] (let [s (swap! seen inc)] - (if (<= s n) - (rrf result input) - (reduced result)))))))) + (cond (< s n) (rf result input) + (= s n) (ensure-reduced (rf result input)) + :else (reduced result)))))))) ([n coll] (lazy-seq (when (pos? n) @@ -1666,8 +1670,7 @@ The new value is thus `(apply f current-value-of-atom args)`." :added "0.1"} ([n] (fn [rf] - (let [rrf (preserving-reduced rf) - seen (atom 0)] + (let [seen (atom 0)] (fn ([] (rf)) ([result] @@ -1675,7 +1678,7 @@ The new value is thus `(apply f current-value-of-atom args)`." ([result input] (let [s (swap! seen inc)] (if (> s n) - (rrf result input) + (rf result input) result))))))) ([n coll] (let [s (seq coll)] @@ -1707,14 +1710,13 @@ The new value is thus `(apply f current-value-of-atom args)`." :added "0.1"} ([pred] (fn [rf] - (let [rrf (preserving-reduced rf)] - (fn - ([] (rf)) - ([result] (rf result)) - ([result input] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] (if (pred input) - (rrf result input) - (reduced result))))))) + (rf result input) + (reduced result)))))) ([pred coll] (lazy-seq (when-let [s (seq coll)] @@ -1825,13 +1827,12 @@ not enough elements were present." :signatures [[f] [f coll]]} ([f] (fn [rf] - (let [i (atom -1) - rrf (preserving-reduced rf)] + (let [i (atom -1)] (fn ([] (rf)) ([result] (rf result)) ([result input] - (rrf result (f (swap! i inc) input))))))) + (rf result (f (swap! i inc) input))))))) ([f coll] (let [mapi (fn mapi [i coll] (lazy-seq @@ -1849,8 +1850,7 @@ not enough elements were present." :added "0.1"} ([f] (fn [rf] - (let [iv (atom -1) - rrf (preserving-reduced rf)] + (let [iv (atom -1)] (fn ([] (rf)) ([result] (rf result)) @@ -1859,7 +1859,7 @@ not enough elements were present." v (f i input)] (if (nil? v) result - (rrf result v)))))))) + (rf result v)))))))) ([f coll] (let [keepi (fn keepi [i coll] (lazy-seq diff --git a/tests/pixie/tests/test-io.pxi b/tests/pixie/tests/test-io.pxi index 1d41c4a5..07a3606b 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -3,6 +3,7 @@ (require pixie.streams :as st :refer :all) (require pixie.streams.utf8 :as utf8 :refer :all) (require pixie.io :as io) + (require pixie.io-blocking :as blocking) (require pixie.streams.zlib :as zlib)) (t/deftest test-file-reduction @@ -10,11 +11,25 @@ (t/assert= (transduce (map identity) count-rf f) - 91))) + 91)) + (let [f (io/open-read "tests/pixie/tests/test-io.txt")] + (t/assert= (transduce (comp (map char) (take 4)) string-builder f) + "This")) + (let [f (blocking/open-read "tests/pixie/tests/test-io.txt")] + (t/assert= (transduce (map identity) + count-rf + f) + 91)) + (let [f (blocking/open-read "tests/pixie/tests/test-io.txt")] + (t/assert= (transduce (comp (map char) (take 4)) string-builder f) + "This"))) (t/deftest test-process-reduction (let [f (io/run-command "ls tests/pixie/tests/test-io.txt")] - (t/assert= f "tests/pixie/tests/test-io.txt\n"))) + (t/assert= f "tests/pixie/tests/test-io.txt\n")) + (let [pipe (blocking/popen-read "ls tests/pixie/tests/test-io.txt")] + (t/assert= (transduce (comp (map char) (take 6)) string-builder pipe) + "tests/"))) (t/deftest test-read-into-buffer (let [f (io/open-read "tests/pixie/tests/test-io.txt")] @@ -38,6 +53,14 @@ (t/assert= (io/read-line f) "Second line.") (t/assert= (io/read-line f) nil))) +(t/deftest test-line-reader + (let [lines (io/line-reader (io/open-read "tests/pixie/tests/test-io.txt"))] + (t/assert= (transduce (map count) conj [] lines) + [77 12])) + (let [lines (io/line-reader (io/open-read "tests/pixie/tests/test-io.txt"))] + (t/assert= (transduce (comp (map count) (take 1)) conj [] lines) + [77]))) + (t/deftest test-line-seq (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt")) s (io/line-seq f)] @@ -58,7 +81,11 @@ (t/assert= (char (io/read-byte f)) \T) (t/assert= (char (io/read-byte f)) \h) (t/assert= (char (io/read-byte f)) \i) - (t/assert= (char (io/read-byte f)) \s))) + (t/assert= (char (io/read-byte f)) \s) + (t/assert= (transduce (comp (map char) (take 5)) string-builder f) + " is a") + (t/assert= (transduce (comp (map char) (take 5)) string-builder f) + " test"))) (t/deftest test-buffered-input-streams-throws-on-non-input-streams (let [f (io/buffered-input-stream (io/open-read "tests/pixie/tests/test-io.txt"))] diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 12ad9912..f4d2f763 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -28,9 +28,28 @@ (t/assert= (keep-indexed (constantly nil) []) []) (t/assert= (keep-indexed (fn [i x] [i x]) [:a :b]) [[0 :a] [1 :b]]) - (t/assert= (transduce (keep-indexed (constantly true)) conj []) []) - (t/assert= (transduce (keep-indexed (constantly nil)) conj []) []) - (t/assert= (transduce (keep-indexed (fn [i x] [i x])) conj [:a :b]) [[0 :a] [1 :b]])) + (t/assert= (transduce (keep-indexed (constantly true)) conj [:a :b]) [true true]) + (t/assert= (transduce (keep-indexed (constantly nil)) conj [:a :b]) []) + (t/assert= (transduce (keep-indexed (fn [i x] [i x])) conj [:a :b]) [[0 :a] [1 :b]]) + + (let [even-index? (fn [i x] + (when (even? i) + x))] + (t/assert= (transduce (keep-indexed even-index?) conj [:a :b :c :d]) + [:a :c]) + (t/assert= (transduce (map-indexed even-index?) conj [:a :b :c :d]) + [:a nil :c nil]) + + (t/assert= (transduce (comp (keep-indexed even-index?) + (take 3)) + conj + [:a :b :c :d :e :f]) + [:a :c :e]) + (t/assert= (transduce (comp (map-indexed even-index?) + (take 3)) + conj + [:a :b :c :d]) + [:a nil :c]))) (t/deftest test-reductions (t/assert= (reductions + nil) @@ -542,7 +561,21 @@ (t/assert= (transduce (take 0) conj [1 2 3 4]) []) (t/assert= (transduce (take 1) conj [1 2 3 4]) [1]) (t/assert= (transduce (take 2) conj [1 2 3 4]) [1 2]) - (t/assert= (transduce (take 3) conj [1 2 3 4]) [1 2 3])) + (t/assert= (transduce (take 3) conj [1 2 3 4]) [1 2 3]) + (t/assert= (transduce (take 10) conj [1 2 3 4]) [1 2 3 4]) + (t/assert= (transduce (comp (take 2) (take 1)) conj [1 2 3 4]) [1]) + (t/assert= (transduce (comp (take 1) (take 2)) conj [1 2 3 4]) [1]) + + (let [call-count (atom 0) + inc-call-count! (fn [x] + (swap! call-count inc) + x)] + (t/assert= (transduce (comp (map inc-call-count!) (take 2)) conj (range 10)) + [0 1]) + (t/assert= @call-count 2) + (t/assert= (transduce (comp (take 2) (map inc-call-count!)) conj (range 10)) + [0 1]) + (t/assert= @call-count 4))) (t/deftest test-drop (t/assert= (drop 0 [1 2 3 4]) [1 2 3 4]) @@ -552,21 +585,26 @@ (t/assert= (transduce (drop 0) conj [1 2 3 4]) [1 2 3 4]) (t/assert= (transduce (drop 1) conj [1 2 3 4]) [2 3 4]) (t/assert= (transduce (drop 2) conj [1 2 3 4]) [3 4]) - (t/assert= (transduce (drop 3) conj [1 2 3 4]) [4])) + (t/assert= (transduce (drop 3) conj [1 2 3 4]) [4]) + (t/assert= (transduce (drop 10) conj [1 2 3 4]) []) + (t/assert= (transduce (comp (drop 1) (take 2)) conj [1 2 3 4]) [2 3]) + (t/assert= (transduce (comp (take 2) (drop 1)) conj [1 2 3 4]) [2])) (t/deftest test-take-while (t/assert= (take-while pos? [1 2 3 -1]) [1 2 3]) (t/assert= (take-while pos? [-1 2]) ()) (t/assert= (transduce (take-while even?) conj [2 4 6 7 8]) [2 4 6]) (t/assert= (transduce (take-while even?) conj [0 2] [1 4 6]) [0 2]) - (t/assert= (transduce (take-while even?) conj [1 3] [2 4 6 7 8]) [1 3 2 4 6])) + (t/assert= (transduce (take-while even?) conj [1 3] [2 4 6 7 8]) [1 3 2 4 6]) + (t/assert= (transduce (comp (take-while even?) (take 2)) conj [1 3] [2 4 6 7 8]) [1 3 2 4])) (t/deftest test-drop-while (t/assert= (drop-while pos? [1 2 3 -1]) [-1]) (t/assert= (drop-while pos? [-1 2]) [-1 2]) (t/assert= (transduce (drop-while even?) conj [2 4 6 7 8]) [7 8]) (t/assert= (transduce (drop-while even?) conj [0 2] [1 4 6]) [0 2 1 4 6]) - (t/assert= (transduce (drop-while even?) conj [0 2] [2 4 6 7 8]) [0 2 7 8])) + (t/assert= (transduce (drop-while even?) conj [0 2] [2 4 6 7 8]) [0 2 7 8]) + (t/assert= (transduce (comp (drop-while even?) (take 2)) conj [0 2] [2 4 6 7 8]) [0 2 7 8])) (t/deftest test-cycle (t/assert= (cycle ()) ()) From c94144b43c3a01f1bf4c4921ddc8e8c6912dc97c Mon Sep 17 00:00:00 2001 From: angusiguess Date: Sun, 13 Mar 2016 20:33:58 -0300 Subject: [PATCH 341/349] Make sequence lazy, make educe seq use sequence --- pixie/stdlib.pxi | 20 +++++++++++++------- tests/pixie/test-sequence.pxi | 23 ----------------------- tests/pixie/tests/test-stdlib.pxi | 22 +++++++++++++++++++++- 3 files changed, 34 insertions(+), 31 deletions(-) delete mode 100644 tests/pixie/test-sequence.pxi diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index ff070380..23a9f7e4 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -1907,7 +1907,7 @@ not enough elements were present." ISeqable (-seq [self] - (seq (reduce conj self)))) + (sequence xform coll))) (defn eduction "Returns a reducible/iterable application of the transducers @@ -2189,12 +2189,18 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (filter (complement pred) coll))) (defn sequence - "Returns a lazy sequence of `data`, optionally transforming it using `xform`. - Given an `eduction`, produces a lazy sequence of it." - ([eduction] - (when (seq eduction) (lazy-seq (cons (first eduction) (sequence (rest eduction)))))) - ([xform data] - (sequence (eduction xform data)))) + "Returns a lazy sequence of `data`, optionally transforming it using `xform`" + ([coll] + (if (seq? coll) coll + (or (seq coll) ()))) + ([xform coll] + (let [step (defn step [xform acc xs] + (if-let [s (seq xs)] + (let [next-acc ((xform conj) acc (first s))] + (if (= acc next-acc) (step xform next-acc (next s)) + (concat (drop (count acc) next-acc) (step xform next-acc (next s))))) + nil))] + (lazy-seq (step xform [] coll))))) (defn distinct {:doc "Returns the distinct elements in the collection." diff --git a/tests/pixie/test-sequence.pxi b/tests/pixie/test-sequence.pxi deleted file mode 100644 index e8a8e748..00000000 --- a/tests/pixie/test-sequence.pxi +++ /dev/null @@ -1,23 +0,0 @@ -(ns pixie.tests.test-sequence - (:require [pixie.test :as t])) - -(t/deftest empty-sequences - (t/assert= '() (take 1 (sequence (map inc) '()))) - (t/assert= '() (take 1 (sequence (map inc) []))) - (t/assert= '() (take 1 (sequence (map inc) #{}))) - (t/assert= '() (take 1 (sequence (map inc) {})))) - -(t/deftest non-empty-sequences - (t/assert= '(1 3) (take 2 (sequence (comp - (filter even?) - (map inc)) (range 3)))) - (t/assert= '(1) (take 1 (sequence (distinct) (repeat 4 1))))) - -(t/deftest early-terminating-sequences - (t/assert= '() (take 5 (sequence (filter (fn [x] false)) (repeat 8 8)))) - (t/assert= '(1 2) (take 3 (sequence (map identity) [1 2]))) - (t/assert= #{[:a 1] [:b 2]} (into #{} (take 3 (sequence (filter (fn [[k v]] - (keyword? k)) {:a 1 - :b 2 - "c" 3 - "d" 4})))))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 12ad9912..8805cd14 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -595,7 +595,7 @@ (seq))) ;; expanding transducer with nils (t/assert= '(1 2 3 nil 4 5 6 nil) - (eduction cat [[1 2 3 nil] [4 5 6 nil]]))) + (seq (eduction cat [[1 2 3 nil] [4 5 6 nil]])))) (t/deftest test-trace (try @@ -767,3 +767,23 @@ (t/assert= (reduce (fn [a v] (reduced "foo")) 0 (iterate inc 1)) "foo") (t/assert= (reduce (fn [a v] (if (< a 10) (+ a v) (reduced a))) 0 (iterate (partial + 2) 1)) 16)) +(t/deftest test-sequence-empty-sequences + (t/assert= '() (take 1 (sequence (map inc) '()))) + (t/assert= '() (take 1 (sequence (map inc) []))) + (t/assert= '() (take 1 (sequence (map inc) #{}))) + (t/assert= '() (take 1 (sequence (map inc) {})))) + +(t/deftest test-sequence-non-empty-sequences + (t/assert= '(1 3) (take 2 (sequence (comp + (filter even?) + (map inc)) (range 3)))) + (t/assert= '(1) (take 1 (sequence (distinct) (repeat 4 1))))) + +(t/deftest test-sequence-early-terminating-sequences + (t/assert= '() (take 5 (sequence (filter (fn [x] false)) (repeat 8 8)))) + (t/assert= '(1 2) (take 3 (sequence (map identity) [1 2]))) + (t/assert= #{[:a 1] [:b 2]} (into #{} (take 3 (sequence (filter (fn [[k v]] + (keyword? k)) {:a 1 + :b 2 + "c" 3 + "d" 4})))))) From 06cfb08e2ad01671c1831c0dcc7220faadbdf273 Mon Sep 17 00:00:00 2001 From: Thomas Mulvaney Date: Fri, 25 Mar 2016 16:49:04 +0000 Subject: [PATCH 342/349] Throw RuntimeExceptions for array functions --- pixie/vm/array.py | 39 ++++++++++++++++++------------- tests/pixie/tests/test-arrays.pxi | 35 +++++++++++++++++++++++---- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/pixie/vm/array.py b/pixie/vm/array.py index 9d15f550..4ca97813 100644 --- a/pixie/vm/array.py +++ b/pixie/vm/array.py @@ -26,6 +26,8 @@ def reduce_small(self, f, init): init = f.invoke([init, self._list[x]]) return init + def list(self): + return self._list def reduce_large(self, f, init): for x in range(len(self._list)): @@ -37,14 +39,14 @@ def reduce_large(self, f, init): @extend(proto._count, Array) def _count(self): assert isinstance(self, Array) - return rt.wrap(len(self._list)) + return rt.wrap(len(self.list())) @extend(proto._nth, Array) def _nth(self, idx): assert isinstance(self, Array) ival = idx.int_val() - if ival < len(self._list): - return self._list[ival] + if ival < len(self.list()): + return self.list()[ival] else: affirm(False, u"Index out of Range") @@ -52,15 +54,15 @@ def _nth(self, idx): def _nth_not_found(self, idx, not_found): assert isinstance(self, Array) ival = idx.int_val() - if ival < len(self._list): - return self._list[ival] + if ival < len(self.list()): + return self.list()[ival] else: return not_found @extend(proto._reduce, Array) def reduce(self, f, init): assert isinstance(self, Array) - if len(self._list) > UNROLL_IF_SMALLER_THAN: + if len(self.list()) > UNROLL_IF_SMALLER_THAN: return self.reduce_large(f, init) return self.reduce_small(f, init) @@ -122,34 +124,39 @@ def array(lst): @as_var("aget") def aget(self, idx): - assert isinstance(self, Array) - return self._list[idx.int_val()] + affirm(isinstance(self, Array), u"aget expects an Array as the first argument") + affirm(isinstance(idx, Integer), u"aget expects an Integer as the second argument") + return self.list()[idx.int_val()] @as_var("aset") def aset(self, idx, val): - assert isinstance(self, Array) - self._list[idx.int_val()] = val + affirm(isinstance(self, Array), u"aset expects an Array as the first argument") + affirm(isinstance(idx, Integer), u"aset expects an Integer as the second argument") + self.list()[idx.int_val()] = val return val @as_var("aslice") def aslice(self, offset): - assert isinstance(self, Array) and isinstance(offset, Integer) + affirm(isinstance(self, Array), u"aset expects an Array as the first argument") + affirm(isinstance(offset, Integer), u"aset expects an Integer as the second argument") offset = offset.int_val() if offset >= 0: - return Array(self._list[offset:]) + return Array(self.list()[offset:]) else: rt.throw(rt.wrap(u"offset must be an Integer >= 0")) @as_var("aconcat") def aconcat(self, other): - assert isinstance(self, Array) and isinstance(other, Array) - return Array(self._list + other._list) + affirm(isinstance(self, Array) and isinstance(other, Array), + u"aconcat expects 2 Arrays") + return Array(self.list() + other.list()) @as_var("alength") def alength(self): - assert isinstance(self, Array) - return rt.wrap(len(self._list)) + affirm(isinstance(self, Array), u"alength expects an Array") + + return rt.wrap(len(self.list())) @as_var("make-array") def make_array(l): diff --git a/tests/pixie/tests/test-arrays.pxi b/tests/pixie/tests/test-arrays.pxi index fbd55937..ecd651cb 100644 --- a/tests/pixie/tests/test-arrays.pxi +++ b/tests/pixie/tests/test-arrays.pxi @@ -8,6 +8,12 @@ (foreach [x a] (t/assert= x nil)))) +(t/deftest test-alength + (let [a (make-array 10)] + (t/assert= (alength a) 10) + (t/assert-throws? RuntimeException + (alength [])))) + (t/deftest test-aget-and-aset (let [a (make-array 10)] (dotimes [i 10] @@ -17,7 +23,13 @@ (aset a i i)) (dotimes [i 10] - (t/assert= (aget a i) i)))) + (t/assert= (aget a i) i)) + + (t/assert-throws? RuntimeException + (aget a 1.0)) + + (t/assert-throws? RuntimeException + (aset a 1.0 :foo)))) (t/deftest test-aconcat (let [a1 (make-array 10) @@ -30,7 +42,13 @@ (let [a3 (aconcat a1 a2)] (dotimes [i 20] - (t/assert= (aget a3 i) i))))) + (t/assert= (aget a3 i) i))) + + (t/assert-throws? RuntimeException + (t/aconcat a1 [])) + + (t/assert-throws? RuntimeException + (t/aconcat a1 '())))) (t/deftest test-aslice (let [a (make-array 10)] @@ -42,10 +60,19 @@ (foreach [i (range 0 7)] (t/assert= (aget a1 i) (+ i 3))) (foreach [i (range 0 3)] - (t/assert= (aget a2 i) (+ i 7)))))) + (t/assert= (aget a2 i) (+ i 7)))) + + (t/assert-throws? RuntimeException + (aslice [1 2 3 4] 0 2)) + + (t/assert-throws? RuntimeException + (aslice '() 0 2)) + + (t/assert-throws? RuntimeException + (aslice a 1.0 2)))) (t/deftest test-byte-array-creation (let [ba (byte-array 10)] (t/assert= (vec ba) [0 0 0 0 0 0 0 0 0 0]) - (t/assert= (count ba) 10))) \ No newline at end of file + (t/assert= (count ba) 10))) From 808d8298e31eaf5c760636021714ca8e5f4295e0 Mon Sep 17 00:00:00 2001 From: Tom Mulvaney Date: Sun, 14 Aug 2016 20:25:33 +0100 Subject: [PATCH 343/349] lock pypy version down --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 8a5f9ccf..5979fde8 100644 --- a/Makefile +++ b/Makefile @@ -53,7 +53,7 @@ externals.fetched: $(EXTERNALS)/pypy: mkdir $(EXTERNALS); \ cd $(EXTERNALS); \ - curl https://bitbucket.org/pypy/pypy/get/default.tar.bz2 > pypy.tar.bz2; \ + curl https://bitbucket.org/pypy/pypy/get/91db1a9.tar.bz2 > pypy.tar.bz2; \ mkdir pypy; \ cd pypy; \ tar -jxf ../pypy.tar.bz2 --strip-components=1 From 946b408e2013c2a2b3f1c55796aba59e079ddef0 Mon Sep 17 00:00:00 2001 From: Bryce Covert Date: Thu, 29 Sep 2016 23:25:26 -0700 Subject: [PATCH 344/349] for bindings can depend on previous ones. --- pixie/stdlib.pxi | 14 +++++++------- tests/pixie/tests/test-stdlib.pxi | 6 +++++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index b1a39041..b30c6900 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2606,14 +2606,14 @@ Expands to calls to `extend-type`." `(loop [res# [] ~c (seq ~coll)] (if ~c - (recur (into res# - ~(gen-loop (into coll-bindings - [binding `(first ~c)]) - (nnext bindings))) - (next ~c)) + (let [~binding (first ~c)] + (recur (into res# + ~(gen-loop (into coll-bindings + [binding `(first ~c)]) + (nnext bindings))) + (next ~c))) res#))) - `(let ~coll-bindings - [~@body])))] + `[~@body]))] `(or (seq ~(gen-loop [] bindings)) '()))) (defmacro doto diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 6e1984e8..17e6bc5b 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -452,7 +452,11 @@ (t/assert= (for [x [1 2 3] y [:a :b :c]] [x y]) [[1 :a] [1 :b] [1 :c] [2 :a] [2 :b] [2 :c] - [3 :a] [3 :b] [3 :c]])) + [3 :a] [3 :b] [3 :c]]) + (t/assert= (for [x [[1 2 3]] + y x] + y) + [1 2 3])) (t/deftest test-doto (let [a (atom 0)] From e3861de3ba7b1f5948a64b5eb08c7d110eb5882c Mon Sep 17 00:00:00 2001 From: Angus Fletcher Date: Sat, 24 Dec 2016 13:27:26 -0400 Subject: [PATCH 345/349] Replace defn by fn --- pixie/stdlib.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index b1a39041..4da12535 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -2194,7 +2194,7 @@ For more information, see http://clojure.org/special_forms#binding-forms"} (if (seq? coll) coll (or (seq coll) ()))) ([xform coll] - (let [step (defn step [xform acc xs] + (let [step (fn step [xform acc xs] (if-let [s (seq xs)] (let [next-acc ((xform conj) acc (first s))] (if (= acc next-acc) (step xform next-acc (next s)) From 060bb4a8058460b5af11ee325815099c763c87eb Mon Sep 17 00:00:00 2001 From: Shoozza Date: Sun, 2 Apr 2017 20:50:07 +0200 Subject: [PATCH 346/349] Fix LGPL svg link --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d66d94d1..a290aa99 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ -[![Build Status](https://travis-ci.org/pixie-lang/pixie.svg?branch=master)](https://travis-ci.org/pixie-lang/pixie)[![License: LGPL] (http://img.shields.io/badge/license-LGPL-green.svg)](http://img.shields.io/badge/license-LGPL-green.svg) +[![Build Status](https://travis-ci.org/pixie-lang/pixie.svg?branch=master)](https://travis-ci.org/pixie-lang/pixie) +[![License: LGPL](https://img.shields.io/badge/license-LGPL-green.svg)](https://img.shields.io/badge/license-LGPL-green.svg) # Pixie [![Join the chat at https://gitter.im/pixie-lang/pixie](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/pixie-lang/pixie?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From f82bf5f577a950051bd0b106865e3bd5608d36bd Mon Sep 17 00:00:00 2001 From: egregius313 Date: Wed, 7 Jun 2017 20:58:02 -0400 Subject: [PATCH 347/349] Change calls to throw to vector instead of string Calls to throw previously used strings, which is not a valid way to call throw (Thus raising an exception raised a completely different exception). Changed all calls to use vectors instead. --- pixie/fs.pxi | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pixie/fs.pxi b/pixie/fs.pxi index f3e73960..679bd5f6 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -109,7 +109,7 @@ (rel [this other] (if (satisfies? IFSPath other) (rel-path this other) - (throw "Second argument must satisfy IFSPath"))) + (throw [::AssertionException "Second argument must satisfy IFSPath"]))) (abs [this] (path/-abs pathz)) @@ -157,7 +157,7 @@ (rel [this other] (if (satisfies? IFSPath other) (rel-path this other) - (throw "Second argument must satisfy IFSPath"))) + (throw [::AssertionException "Second argument must satisfy IFSPath"]))) (abs [this] (path/-abs pathz)) @@ -217,7 +217,7 @@ (cond (path/-file? x) (->File x) (not (path/-exists? x)) (->File x) - :else (throw (str "A non-file object exists at path: " x))))) + :else (throw [::NotAFileException (str "A non-file object exists at path: " x)])))) (defn dir "Returns a dir if the path is a dir or does not exist. If a different filesystem object exists at the path an error will be thrown." @@ -226,7 +226,7 @@ (cond (path/-dir? x) (->Dir x) (not (path/-exists? x)) (->Dir x) - :else (throw (str "A non-dir object exists at path: " x))))) + :else (throw [::NotADirectoryException (str "A non-dir object exists at path: " x)])))) (defn fspath "Returns either a File or Dir if they exist at the path" @@ -235,6 +235,6 @@ (cond (path/-file? x) (->File x) (path/-dir? x) (->Dir x) - :else (throw (str "No file or directory at path: " x))))) + :else (throw [::FileNotFoundException (str "No file or directory at path: " x)])))) From 42d6fc0cc78075028c5fcdf612b0f9815b554603 Mon Sep 17 00:00:00 2001 From: Edward Minnix III Date: Thu, 5 Oct 2017 11:13:07 -0400 Subject: [PATCH 348/349] Add test for the letfn macro --- tests/pixie/tests/test-stdlib.pxi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index 17e6bc5b..9b2174e0 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -829,3 +829,16 @@ :b 2 "c" 3 "d" 4})))))) + +(t/deftest test-letfn + (letfn [(hello [] "Hello") + (adder [x y] (+ x y))] + (t/assert= "Hello" (hello)) + (dotimes [i 10] + (dotimes [j 20] + (t/assert= (+ i j) (adder i j))))) + (letfn [(f [x n] (vec (repeat n x)))] + (t/assert= (f :x 3) [:x :x :x]) + (t/assert= (f 0 20) [0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 0 0]))) From a25209bc464a7a3254636c445814ba4f92c870d5 Mon Sep 17 00:00:00 2001 From: Edward Minnix III Date: Thu, 5 Oct 2017 11:17:38 -0400 Subject: [PATCH 349/349] Added letfn --- pixie/stdlib.pxi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pixie/stdlib.pxi b/pixie/stdlib.pxi index 6c908a82..2501e2fe 100644 --- a/pixie/stdlib.pxi +++ b/pixie/stdlib.pxi @@ -482,6 +482,19 @@ (let [nm (with-meta nm (assoc (meta nm) :private true))] (cons `defn (cons nm rest)))) +(defmacro letfn + "fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+) + + Takes a vector of function specs and a body, and generates a set of + bindings of functions to their names. All of the names are available + in all of the definitions of the functions, as well as the body." + {:added "0.2" + :forms '[(letfn [fnspecs*] exprs*)]} + [fnspecs & body] + `(letfn* ~(vec (interleave (map first fnspecs) + (map #(cons `fn %) fnspecs))) + ~@body)) + (defn not {:doc "Inverts the input, if a truthy value is supplied, returns false, otherwise returns true."