diff --git a/.gitignore b/.gitignore index 391f400b..5928d907 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,12 @@ *.pyc -externals +externals* pixie-vm .idea lib include +*.pxic +test.tmp +/libuv* +/uv-* +/uv.h +/*compressed-output.* diff --git a/.travis.yml b/.travis.yml index 9d48c020..77846892 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,10 @@ +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 @@ -16,8 +12,14 @@ script: - make compile_tests - make run_built_tests -before_install: - - sudo apt-get install libffi-dev libedit-dev libboost-all-dev +addons: + apt: + packages: + - libffi-dev + - libedit-dev + - libboost-all-dev + - zlib1g-dev + - zlib-bin notifications: irc: "chat.freenode.net#pixie-lang" diff --git a/Dockerfile b/Dockerfile index ea969e9a..76ca6849 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++ libboost-dev 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"] diff --git a/Makefile b/Makefile index bb5cda71..5979fde8 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,12 @@ all: help -EXTERNALS=../externals +EXTERNALS=externals -PYTHON ?= python +PYTHON ?= `env which -a python2 python2.7 | head -n1` PYTHONPATH=$$PYTHONPATH:$(EXTERNALS)/pypy -COMMON_BUILD_OPTS?=--thread --no-shared --gcrootfinder=shadowstack +COMMON_BUILD_OPTS?=--thread --gcrootfinder=shadowstack --continuation JIT_OPTS?=--opt=jit TARGET_OPTS?=target.py @@ -19,32 +19,41 @@ 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 -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_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 -build_preload_no_jit: fetch_externals - $(PYTHON) $(EXTERNALS)/pypy/rpython/bin/rpython $(COMMON_BUILD_OPTS) target_preload.py + +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: 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 +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: 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 @@ -52,9 +61,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 @@ -68,4 +82,11 @@ 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 + rm -rf ./include + rm -rf ./externals* + rm -f ./pixie-vm + rm -f ./*.pyc diff --git a/README.md b/README.md index 39110fb4..a290aa99 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ -[![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) + ## 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. @@ -30,6 +33,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 @@ -38,7 +43,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 @@ -51,25 +56,24 @@ 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"? -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 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. +* 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)) @@ -77,12 +81,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 +94,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 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/benchmarks/read-line.pxi b/benchmarks/read-line.pxi new file mode 100644 index 00000000..c252fd09 --- /dev/null +++ b/benchmarks/read-line.pxi @@ -0,0 +1,42 @@ +(ns benchmarks.readline + (:require [pixie.time :as time] + [pixie.io :as io] + [pixie.streams.utf8 :as utf8])) + +(def file-name "/usr/share/dict/words") + +(println "Lazy line-seq") +(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/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/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/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) diff --git a/examples/tty-io-test.pxi b/examples/tty-io-test.pxi new file mode 100644 index 00000000..0fadfa3a --- /dev/null +++ b/examples/tty-io-test.pxi @@ -0,0 +1,29 @@ +(ns io-test + (:require [pixie.io :as io] + [pixie.system :as sys] + [pixie.io.tty :as tty])) + +(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 [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/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 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/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/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/async.pxi b/pixie/async.pxi new file mode 100644 index 00000000..ca7862f8 --- /dev/null +++ b/pixie/async.pxi @@ -0,0 +1,31 @@ +(ns pixie.async + (:require [pixie.stacklets :as st])) + + +(deftype Promise [val pending-callbacks delivered?] + IDeref + (-deref [self] + (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] + (assert (not delivered?) "Can only deliver a promise once") + (set-field! self :val v) + (set-field! self :delivered? true) + (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/buffers.pxi b/pixie/buffers.pxi new file mode 100644 index 00000000..5e6009db --- /dev/null +++ b/pixie/buffers.pxi @@ -0,0 +1,146 @@ +(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)) + + 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))) + +(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] + (loop [acc acc] + (if (reduced? acc) + @acc + (if (pos? (count buf)) + (recur (f acc (remove! buf))) + acc))))) diff --git a/pixie/channels.pxi b/pixie/channels.pxi new file mode 100644 index 00000000..1f8067df --- /dev/null +++ b/pixie/channels.pxi @@ -0,0 +1,203 @@ +(ns pixie.channels + (:require [pixie.stacklets :as st] + [pixie.uv :as uv] + [pixie.ffi :as ffi] + [pixie.buffers :as b])) + +(defprotocol ICancelable + (-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 cancelable 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")) + +(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] + (cond + (= idx 0) val + (= idx 1) cfn + :else (throw [::OutOfRangeException "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 (canceled? 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 (and closed? + (b/empty-buffer? buffer) + (b/empty-buffer? puts)) + (do (-commit! cfn) + (st/-run-later (partial cfn nil)) + false) + (if (not (b/empty-buffer? 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 (-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)) + (b/add-unbounded! takes cfn) + true)))))) + IWritePort + (-put! [this val cfn] + (if (or (canceled? cfn)) + false + (if closed? + (do (-commit! cfn) + (st/-run-later (partial cfn false)) + false) + (if-let [tfn (-get-non-canceled! takes)] + (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)) + (set-field! this :ops-since-last-clean (inc ops-since-last-clean)) + true)))))) + ICloseable + (-close! [this] + (set-field! this :closed? true) + (when (not (b/empty-buffer? takes)) + (loop [] + (when-let [tfn (-get-non-canceled! takes)] + (-commit! tfn) + (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] + (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))))) + +(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] + @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)) + +(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 (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 new file mode 100644 index 00000000..32c96c8c --- /dev/null +++ b/pixie/csp.pxi @@ -0,0 +1,63 @@ +(ns pixie.csp + (:require [pixie.stacklets :as st] + [pixie.buffers :as b] + [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 + drain the channel before returning nil." + [c] + (chans/-close! c)) + +(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 > m + (transduce (comp (map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$"))) + (interpose ", ")) + string-builder)) + "}")) + +(defn- write-sequential [xs] + (str "[" + (->> xs + (transduce (comp (map write-string) + (interpose ", ")) + string-builder)) + "]")) + +(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)) + 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/pixie/ffi-infer.pxi b/pixie/ffi-infer.pxi index 49578c20..6b6920d6 100644 --- a/pixie/ffi-infer.pxi +++ b/pixie/ffi-infer.pxi @@ -1,5 +1,6 @@ (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))) @@ -61,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] @@ -79,28 +84,37 @@ 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?] + `(pixie.ffi/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 (= (: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)) +(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 - [_] + [_ _] `pixie.stdlib/CVoid) (def int-types {[8 true] 'pixie.stdlib/CInt8 @@ -113,7 +127,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)) @@ -126,57 +140,76 @@ 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 [{: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))) +(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))] - `(do ~@(map generate-code cmds result)))) + (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") @@ -219,6 +252,29 @@ 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") + 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))) + diff --git a/pixie/fs.pxi b/pixie/fs.pxi index 7be65fda..679bd5f6 100644 --- a/pixie/fs.pxi +++ b/pixie/fs.pxi @@ -1,7 +1,7 @@ (ns pixie.fs - (require pixie.path :as path) - (require pixie.string :as string)) - + (:require [pixie.path :as path] + [pixie.string :as string] + [pixie.uv :as uv])) (defprotocol IFSPath (path [this] @@ -18,24 +18,25 @@ (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] + (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.")) @@ -51,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")) @@ -71,7 +72,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)) ".." @@ -80,6 +81,26 @@ :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) "\""))) + +(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] + (assert-existence path) + (fs-size (abs path))) + +(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] + (assert-existence path) + (permission-string (fs-mode (abs path)))) ;; File and Dir are just wrappers around paths. (deftype File [pathz] @@ -88,20 +109,26 @@ (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)) - + (exists? [this] (path/-exists? pathz)) (basename [this] (last (string/split (abs this) "/"))) - IFile + (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 - ;; #".". + ;; #".". (extension [this] (last (string/split (abs this) "."))) @@ -113,11 +140,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] @@ -130,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)) @@ -140,10 +167,16 @@ (basename [this] (last (string/split (abs this) "/"))) - + + (size [this] + (size-of-path this)) + + (permissions [this] + (permissions-of-path pathz)) + IDir (list [this] - (path/-list-dir pathz)) + (vec (map fspath (path/-list-dir pathz)))) (walk [this] (transduce (map #(if (path/-file? %) @@ -165,11 +198,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,23 +210,23 @@ ;; (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))))) + :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." [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))))) + :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" @@ -202,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)])))) diff --git a/pixie/io-blocking.pxi b/pixie/io-blocking.pxi new file mode 100644 index 00000000..4af15739 --- /dev/null +++ b/pixie/io-blocking.pxi @@ -0,0 +1,147 @@ +(ns pixie.io-blocking + (: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)) +(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)) +(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 EOF -1) + +(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)) + ISeekableStream + (seek [this pos] + (fseek fp pos 0)) + (rewind [this] + (-rewind fp)) + IDisposable + (-dispose! [this] + (fclose fp)) + IReduce + (-reduce [this f init] + (common/stream-reducer this f init))) + +(defn open-read + {: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 + "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)] + (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] + 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)) + IDisposable + (-dispose! [this] + (fclose fp))) + +(defn file-output-rf [filename] + (let [fp (->FileOutputStream (fopen filename "w"))] + (fn ([] 0) + ([cnt] (dispose! fp) nil) + ([cnt chr] + (assert (integer? chr)) + (let [written (write-byte fp chr)] + (if (= written EOF) + (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)] + (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] + (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)) + IDisposable + (-dispose! [this] + (pclose fp)) + IReduce + (-reduce [this f init] + (common/stream-reducer this f init))) + +(defn popen-read + {:doc "Opens a file for reading. Returns an 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)] + (dispose! c) + result)) diff --git a/pixie/io.pxi b/pixie/io.pxi index 46524dbf..a6ed1286 100644 --- a/pixie/io.pxi +++ b/pixie/io.pxi @@ -1,161 +1,275 @@ -(ns pixie.io) +(ns pixie.io + (: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] + [pixie.ffi-infer :as ffi-infer])) -(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)) +(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) - -(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")) - -(def DEFAULT-BUFFER-SIZE 1024) - -(deftype FileStream [fp] +(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 [read-count (fread buffer 1 len fp)] + (let [_ (pixie.ffi/set! uvbuf :base 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)) (set-buffer-count! buffer read-count) read-count)) - (read-byte [this] - (fgetc buffer)) - IClosable - (close [this] - (fclose fp)) + ISeekableStream + (position [this] + offset) + (rewind [this] + (set-field! this :offset 0)) + (seek [this pos] + (set-field! this :offset pos)) + 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)))))) + (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"))) + (->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" +(defprotocol ILineReader + (-read-line [this])) + +(def line-feed? #{\newline \return}) + +(deftype LineReader + [input-stream] + ILineReader + (-read-line [this] + (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)))))) + IReduce + (-reduce [this f init] + (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] - (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 + + (satisfies? utf8/IUTF8InputStream input-stream) + (-> input-stream ->LineReader) - (and (zero? len) (empty? acc)) nil + (instance? BufferedInputStream input-stream) + (-> input-stream ->LineReader) - :else (apply str (map char acc))))))) + + (satisfies? IInputStream input-stream) + (-> input-stream (buffered-input-stream 1) ->LineReader) + + :else + (throw [::Exception "Expected a LineReader, UTF8InputStream, or BufferedInputStream"]))) + +(defn read-line + "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] - (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] +(deftype FileOutputStream [fp offset uvbuf] 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)) + (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 offset)] + (when (neg? write-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)) + write-count)))) + IDisposable + (-dispose! [this] + (fs_close fp))) -(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)) +(deftype BufferedOutputStream [downstream idx buffer] + IByteOutputStream + (write-byte [this val] + (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))) + IDisposable + (-dispose! [this] + (set-buffer-count! buffer idx) + (flush this)) + IFlushableStream + (flush [this] + (set-buffer-count! buffer idx) + (set-field! this :idx 0) + (write downstream buffer) + (when (satisfies? IFlushableStream downstream) + (flush downstream)))) + +(deftype BufferedInputStream [upstream idx buffer] 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" + (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)) + (set-field! this :idx 0) + (read upstream buffer (buffer-capacity buffer))) + (when-not (empty? buffer) + (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))) + +(defn buffered-output-stream + ([downstream] + (buffered-output-stream downstream common/DEFAULT-BUFFER-SIZE)) + ([downstream size] + (->BufferedOutputStream downstream 0 (buffer size)))) + +(defn buffered-input-stream + ([upstream] + (buffered-input-stream upstream common/DEFAULT-BUFFER-SIZE)) + ([upstream size] + (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) + (throw [::UVException (uv/uv_err_name result)])) + result) + +(defn open-write + {:doc "Opens a file for writing. Returns an IOutputStream." :added "0.1"} - [command] - (assert (string? command) "Command must be a string") - (->ProcessInputStream (popen command "r"))) + [filename] + (assert (string? filename) "Filename must be a string") + (->FileOutputStream (throw-on-error (fs_open filename + (bit-or uv/O_WRONLY uv/O_CREAT) + uv/S_IRWXU)) + 0 + (uv/uv_buf_t))) +(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 [::Exception "Expected a string or IOutputStream"]))) -(defn run-command [command] - (let [c (->ProcessInputStream (popen command "r")) +(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 [:pixie.io/Exception "Expected a string or an IInputStream"])) result (transduce - (map char) + (map identity) string-builder - c)] - (close c) - result)) + (-> stream + buffered-input-stream + utf8/utf8-input-stream))] + (dispose! stream) + result)) + +(defn run-command [command] + (st/apply-blocking io-blocking/run-command command)) + + +(comment + (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/io/common.pxi b/pixie/io/common.pxi new file mode 100644 index 00000000..75a3e685 --- /dev/null +++ b/pixie/io/common.pxi @@ -0,0 +1,17 @@ +(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))))) diff --git a/pixie/io/tcp.pxi b/pixie/io/tcp.pxi new file mode 100644 index 00000000..0233d00a --- /dev/null +++ b/pixie/io/tcp.pxi @@ -0,0 +1,87 @@ +(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.io.uv-common :as uv-common] + [pixie.ffi :as ffi])) + +(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))) + +(deftype TCPStream [uv-client uv-write-buf] + IInputStream + (read [this buffer len] + (uv-common/cb-stream-reader uv-client buffer len)) + IOutputStream + (write [this buffer] + (uv-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/stream-reducer this f init))) + +(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 (uv/uv_buf_t)))) + svr) + (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." + [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-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-connection)) + (st/yield-control) + tcp-server)) + + +(defn tcp-client + "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) + 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/io/tty.pxi b/pixie/io/tty.pxi new file mode 100644 index 00000000..be8c0185 --- /dev/null +++ b/pixie/io/tty.pxi @@ -0,0 +1,44 @@ +(ns pixie.io.tty + (:require [pixie.stacklets :as st] + [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] + (uv-common/cb-stream-reader uv-client buf len)) + IDisposable + (-dispose! [this] + (uv/uv_close uv-client st/close_cb)) + IReduce + (-reduce [this f init] + (common/stream-reducer this f init))) + +(deftype TTYOutputStream [uv-client uv-write-buf] + IOutputStream + (write [this buffer] + (uv-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))) + +(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 [tty (uv/uv_tty_t)] + (uv/uv_tty_init (uv/uv_default_loop) tty fd 0) + (->TTYInputStream tty))) + +(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/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))))) 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/math.pxi b/pixie/math.pxi index 7c16889d..253bc132 100644 --- a/pixie/math.pxi +++ b/pixie/math.pxi @@ -1,26 +1,101 @@ (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"] :includes ["math.h"]} - (i/defcfn acos) - (i/defcfn asin) - (i/defcfn atan) - (i/defcfn atan2) - (i/defcfn cos) - (i/defcfn cosh) - (i/defcfn sin) - (i/defcfn sinh) - (i/defcfn tanh) + (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 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 fmod) + (i/defcfn remainder) + (i/defcfn remquo) + + (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) + (if-not (s/starts-with? pixie.platform/name "darwin") + (i/defcfn exp10)) + (i/defcfn expm1) + (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) + (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/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)) + +(if (s/starts-with? pixie.platform/name "darwin") + (defn exp10 [x] (pow 10.0 x))) diff --git a/pixie/parser.pxi b/pixie/parser.pxi new file mode 100644 index 00000000..79e18f6e --- /dev/null +++ b/pixie/parser.pxi @@ -0,0 +1,312 @@ +(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))) + String + (to-parser [this] + (println "bad-parser " this) + (assert false))) + + + + +(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)) + +(defn -parse-parser-args [args] + (loop [rules {} + args args] + (if args + (let [name (first args) + body (second args) + args (-> args next next)] + (assert (symbol? name) "Must name all rules") + (if (= '<- (first args)) + (let [return (first (next args)) + full-rule `(let [p# (to-parser ~body)] + (fn [cursor#] + (let [~'value (p# cursor#)] + (if (failure? ~'value) + ~'value + ~return))))] + (recur (assoc rules name full-rule) + (next (next args)))) + (recur (assoc rules name body) + args))) + rules))) + +(defmacro parser + "(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] + (::forms (deref (resolve-in *ns* sym)))) + inherits) + (-parse-parser-args 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)) + +(defn end + "A parser that only succeeds if there is no more input left to process." + [cursor] + (if (at-end? cursor) + nil + fail)) + +(defn one-of + "Defines 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})) 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/pixie/repl.pxi b/pixie/repl.pxi new file mode 100644 index 00000000..6b21c862 --- /dev/null +++ b/pixie/repl.pxi @@ -0,0 +1,33 @@ +(ns pixie.repl + (:require [pixie.stacklets :as st] + [pixie.io :as io] + [pixie.ffi-infer :as f])) + +(f/with-config {:library "edit" + :includes ["editline/readline.h"]} + (f/defcfn readline) + (f/defcfn add_history)) + + +(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 + (do + (add_history line) + (str line "\n")) + ""))))] + (loop [] + (try (let [form (read rdr false)] + (if (or (= form eof) (= form :exit)) + (exit 0) + (let [x (eval form)] + (pixie.stdlib/-push-history x) + (prn x)))) + (catch ex + (pixie.stdlib/-set-*e ex) + (println "ERROR: \n" ex))) + (recur)))) diff --git a/pixie/set.pxi b/pixie/set.pxi new file mode 100644 index 00000000..23c4b425 --- /dev/null +++ b/pixie/set.pxi @@ -0,0 +1,78 @@ +(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- -must-be-sets [& sets] + (doseq [set sets] + (-must-be-set set))) + +(defn- -union [s t] + (-must-be-sets s t) + (if (< (count s) (count t)) + (into t s) + (into s t))) + +(defn union + "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))) + +(defn- -difference [s t] + (-must-be-sets s 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) + (into #{} (filter #(contains? s %)) t)) + +(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))) + +(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] + (-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." + [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/pixie/stacklets.pxi b/pixie/stacklets.pxi new file mode 100644 index 00000000..267c7530 --- /dev/null +++ b/pixie/stacklets.pxi @@ -0,0 +1,197 @@ +(ns pixie.stacklets + (: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. + +(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)) + + + +;; Yield + +(defrecord ThrowException [ex]) + +(defn run-and-process + ([k] + (run-and-process k nil)) + ([k val] + (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) + (if (instance? ThrowException val) + (throw [::Exception (:ex val)]) + val))) + +(defn -run-later [f] + (let [a (uv/uv_async_t) + cb (atom nil)] + (reset! cb (ffi/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) + (when (not @main-loop-running?) + (reset! main-loop-running? true) + (-release-lock main-loop-lock)) + nil)) + + +(defn yield-control [] + (call-cc (fn [k] + (-run-later (partial run-and-process k))))) + +(def close_cb (ffi/ffi-prep-callback uv/uv_close_cb + pixie.ffi/dispose!)) + +;;; Sleep +(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] + (call-cc (fn [k] + (-run-later (fn [] + (run-and-process (new-stacklet start-fn)))) + (-run-later (partial run-and-process k))))) + +(defmacro spawn [& body] + `(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))))))) + +(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 _] + (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 finalizer-loop [] + (spawn-background + (loop [] + (-run-finalizers) + (sleep 1000 true) + (recur)))) + + +(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) + (when (> @running-threads 0) + (reset! main-loop-running? false) + (-acquire-lock main-loop-lock true) + (recur))))) + +(defmacro with-stacklets [& body] + `(-with-stacklets + (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))) + +(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/stdlib.pxi b/pixie/stdlib.pxi index fe3db177..2501e2fe 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)) @@ -12,17 +11,19 @@ (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)) (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 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)) -(def floor (ffi-fn libm "floor" [CDouble] CDouble)) (def lround (ffi-fn libm "lround" [CDouble] CInt)) @@ -38,6 +39,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"} @@ -46,7 +51,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 @@ -57,7 +62,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! @@ -95,7 +100,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 @@ -109,7 +114,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! @@ -133,7 +138,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 @@ -144,44 +149,68 @@ ([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))))))))) - - -(def reduce (fn [rf init col] - (-reduce col rf init))) + (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 col] + (reduce rf (rf) col)) + ([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." + :signatures [[t x]]} + instance? [t x] + (if (-satisfies? ISeqable t) + (let [ts (seq t)] + (if (not ts) false + (if (-instance? (first ts) x) + true + (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." + :signatures [[t x]]} + satisfies? [p x] + (if (-satisfies? ISeqable p) + (let [ps (seq p)] + (if (not ps) true + (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`." - :signatures [[to from]] + :signatures [[to from] [to xform 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." @@ -200,7 +229,6 @@ ([val coll] (transduce (interpose val) conj coll)))) - (def preserving-reduced (fn preserving-reduced [rf] (fn pr-inner [a b] @@ -222,7 +250,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] @@ -241,16 +269,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]] @@ -263,6 +292,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) @@ -290,8 +320,8 @@ (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)) (extend -hash Integer hash-int) @@ -311,20 +341,25 @@ ([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] - (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] @@ -332,10 +367,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] @@ -344,10 +379,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] @@ -377,13 +412,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 @@ -395,7 +423,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." @@ -440,55 +475,36 @@ (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] (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))) - +(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" +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,6 +527,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)) @@ -523,6 +563,13 @@ returns true" (defn rem [num div] (-rem num div)) +(defn rand-int + {:doc "Returns a random integer between 0 (inclusive) and n (exclusive)."} + [n] + (if (zero? n) + 0 + (rem (rand) n))) + (defn = {:doc "Returns true if all the arguments are equivalent. Otherwise, returns false. Uses -eq to perform equality checks." @@ -572,63 +619,79 @@ 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." + :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" + {:doc "Returns true if the collection has no items, otherwise false." :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" + {: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] @@ -636,14 +699,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 +716,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 +726,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 +736,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"} @@ -683,7 +746,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) @@ -693,9 +756,9 @@ 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]] - :addded "0.1"} + :added "0.1"} ([m] m) ([m & ks] (reduce -dissoc m ks))) @@ -717,7 +780,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)) @@ -738,6 +801,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] @@ -750,7 +814,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) @@ -759,7 +823,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 @@ -773,21 +836,39 @@ 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)))))) - -(defn . + (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. If further arguments are passed, invokes the method named by symbol, passing the object and arguments." @@ -810,40 +891,34 @@ 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)) +(defn coll? [v] (satisfies? IPersistentCollection v)) (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 (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 (str "Can't convert a value of type " (type x) " to an Integer")))) +(defn map-entry? [v] (satisfies? IMapEntry v)) (defn last {:doc "Returns the last element of the collection, or nil if none." :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." @@ -857,28 +932,21 @@ 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] - (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)))))) - -(defn some - {:doc "Checks if the predicate is true for any element of the collection. - -Stops if it finds such an element." - :signatures [[pred coll]] - :added "0.1"} - [pred coll] - (cond - (nil? (seq coll)) false - (pred (first coll)) true - :else (recur pred (next coll)))) + (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 "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)) (extend -count MapEntry (fn [self] 2)) (extend -nth MapEntry (fn map-entry-nth [self idx] @@ -888,22 +956,45 @@ Stops if it finds such an element." (cond (= idx 0) (-key self) (= idx 1) (-val self) :else not-found))) +(extend -eq MapEntry (fn [self 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) (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] (transduce ordered-hash-reducing-fn v))) +(extend -seq MapEntry + (fn [self] + (list (-key self) (-val self)))) + +(defn select-keys + {: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 + (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 + {: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"} @@ -912,7 +1003,7 @@ Stops if it finds such an element." (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"} @@ -927,24 +1018,26 @@ Stops if it finds such an element." (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] (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] - (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 [_] '())) @@ -964,18 +1057,26 @@ Stops if it finds such an element." (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] (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"} @@ -993,20 +1094,25 @@ Stops if it finds such an element." (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." + {: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)) ([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." + {: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"} @@ -1024,7 +1130,7 @@ Stops if it finds such an element." 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}}}]] @@ -1038,7 +1144,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] @@ -1056,14 +1162,16 @@ 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." + {:doc "Resolves the var associated with the symbol in the current namespace." :added "0.1"} [sym] `(resolve-in (this-ns-name) ~sym)) @@ -1080,16 +1188,23 @@ 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)) + (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))) @@ -1104,16 +1219,11 @@ 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] - 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] @@ -1128,12 +1238,16 @@ 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)] + `(fn ~(symbol (str fn-name "_" nm)) ~args ~@body))) bodies (reduce (fn [res body] (cond @@ -1142,7 +1256,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))) + :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)] @@ -1155,18 +1271,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 @@ -1179,44 +1289,116 @@ 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. + {:doc "Defines 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))) + meta-gs (gensym "meta") 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 "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) - (. self k) - not-found)) + (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#))) + + '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#))) + 'ICounted + `(-count [self] ~(count fields)) + + 'ISeqable + `(-seq [self#] + (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 + ~@(conj field-syms meta-gs))) + `(-meta [self#] __meta) + '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 "not implemented"))] - deftype-decl `(deftype ~nm ~fields ~@default-bodies ~@body)] + (hash [~@field-syms])) + `IRecord] + 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." @@ -1252,11 +1434,16 @@ 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. + + 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." @@ -1275,11 +1462,13 @@ and implements IAssociative, ILookup and IObject." {:doc "Returns the documentation of the given value." :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))] (cond + (satisfies? IDoc x) (-doc x) has-doc? (let [sigs (get (meta x) :signatures) examples (get (meta x) :examples) indent (fn [s] @@ -1338,6 +1527,10 @@ The new value is thus `(apply f current-value-of-atom args)`." (defn nil? [x] (identical? x nil)) +(defn some? [x] + {:doc "Returns true if x is not nil."} + (not (nil? x))) + (defn fnil [f else] (fn [x & args] (apply f (if (nil? x) else x) args))) @@ -1351,20 +1544,8 @@ 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." + {: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"} @@ -1377,23 +1558,8 @@ 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." + {: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]] @@ -1428,6 +1594,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] @@ -1439,8 +1610,18 @@ 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))" + {:doc "Equivalent to (next (next coll))." :added "0.1"} [coll] (next (next coll))) @@ -1460,7 +1641,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] @@ -1472,26 +1653,62 @@ 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 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)] + (cond (< s n) (rf result input) + (= s n) (ensure-reduced (rf result input)) + :else (reduced 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." :added "0.1"} + ([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] + (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." + :examples [["(split-at 2 [:a :b :c :d :e])" nil + [(:a :b) (:c :d :e)]]]} [n coll] - (let [s (seq coll)] - (if (and (pos? n) s) - (recur (dec n) (next s)) - s))) + [(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" + some side-effect will cause test to become false/nil. Returns nil." :added "0.1"} [test & body] `(loop [] @@ -1548,22 +1765,37 @@ 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 [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]]}]] + ["(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] - {:doc "Returns a map with distinct elements as keys and the number of occurences as values" +(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))) {} @@ -1581,8 +1813,122 @@ 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))))))) + +(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 [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 + (let [n (f s)] + (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)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (rf 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)] + (fn + ([] (rf)) + ([result] (rf result)) + ([result input] + (let [i (swap! iv inc) + v (f i input)] + (if (nil? v) + result + (rf 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 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] + (sequence xform coll))) + +(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 @@ -1593,7 +1939,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) @@ -1656,7 +2003,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))] @@ -1665,12 +2015,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) @@ -1684,6 +2037,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] @@ -1697,14 +2096,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)) @@ -1715,23 +2106,38 @@ 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))] (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 "(" (transduce (interpose " ") string-builder v) ")"))) + +(extend -repr Range + (fn [v] + (str "(" (transduce (interpose " ") string-builder v) ")"))) (defn range {:doc "Returns a range of numbers." @@ -1746,33 +2152,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 []) @@ -1793,36 +2172,48 @@ 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." + {:doc "Filters 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 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 sequence + "Returns a lazy sequence of `data`, optionally transforming it using `xform`" + ([coll] + (if (seq? coll) coll + (or (seq coll) ()))) + ([xform coll] + (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)) + (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." @@ -1840,33 +2231,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. @@ -1885,16 +2278,20 @@ 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) {}) 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")) + (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)] (if (not syms) nil @@ -1903,19 +2300,29 @@ 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)) -(extend -iterator ISeq (fn [s] - (loop [s s] - (when s - (yield (first s)) - (recur (next s)))))) -(extend -at-end? EmptyList (fn [_] true)) + + +(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])))) + + (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 @@ -1931,7 +2338,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 @@ -1939,6 +2346,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. @@ -1948,9 +2358,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 @@ -1965,7 +2374,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 (str '~c))) post) + ~'%)) + body) + body (if pre + (seq (concat + (map (fn* [c] `(assert ~c (str '~c))) pre) + body)) + body)] (if (every? symbol? argv) `(~argv ~@body) `(~names @@ -1973,10 +2399,51 @@ 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)))) + +;; 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) @@ -1986,8 +2453,9 @@ 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." + {: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 \".\"))"] @@ -2006,27 +2474,31 @@ The params can be destructuring bindings, see `(doc let)` for details."} `(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] `(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." + {: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!"]] @@ -2039,7 +2511,7 @@ The params can be destructuring bindings, see `(doc let)` for details."} 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]))"] @@ -2087,6 +2559,51 @@ 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)) + +(defprotocol IRecord) + +(defn record? + {:doc "Returns true if x implements IRecord." + :since "0.1"} + [x] + (satisfies? IRecord x)) + (defmacro for {:doc "A list comprehension for the bindings." :examples [["(for [x [1 2 3]] x)" nil [1 2 3]] @@ -2102,35 +2619,58 @@ 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 + {: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.. + [coll] + "Returns a collection that contains all the elements of the argument in reverse order." + (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 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] + (-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 @@ -2139,15 +2679,16 @@ Expands to calls to `extend-type`." `(-dispose! ~nm)) names) 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)) @@ -2155,9 +2696,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 @@ -2165,3 +2706,420 @@ Expands to calls to `extend-type`." (when (branch? node) (mapcat walk (children node))))))] (walk root))) + +(defn flatten + ; TODO: laziness? + {: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." + :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 + {: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))) + +(defn map-invert + {: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] + (assoc m* (val ent) (key ent))) + {} 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))) + +(defn macroexpand-1 + {: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]]]} + [form] + (if (or (not (list? form)) + (= () form)) + form + (let [[sym & args] form + fvar (resolve-in *ns* sym)] + (if (and fvar (macro? @fvar)) + (apply @fvar args) + form)))) + +(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)) + +(def hash-map hashmap) + +(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 + (fn [v] + (let [entry->str (map (fn [e] (vector (-repr (key e)) " " (-repr (val e)))))] + (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)))))] + (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." + ([] ()) + ([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 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))))) + +(extend -str Namespace + (fn [v] (str ""))) + +(extend -repr Namespace -str) + + +(defn bool? + "Returns true if x is a Bool." + [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] + "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] + (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 ISeq + ISeqable + (-first [coll] (-first (seq coll))) + (-next [coll] (-next (seq coll)))) + +(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 + "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) + (throw [::ComparisonError (str x " does not satisfy IComparable")]))) + +(defn vary-meta + {: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))) + +(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))))) + +(deftype Iterate [f x] + IReduce + (-reduce [self rf init] + (loop [next (f x) + acc (rf init x)] + (if (reduced? acc) + @acc + (recur (f next) (rf acc next))))) + 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 + side-effects" + :signatures [[f x]] + :added "0.1"} + [f x] + (->Iterate f x)) diff --git a/pixie/streams.pxi b/pixie/streams.pxi new file mode 100644 index 00000000..1bdf358f --- /dev/null +++ b/pixie/streams.pxi @@ -0,0 +1,21 @@ +(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")) + +(defprotocol IOutputStream + (write [this buffer])) + +(defprotocol IByteInputStream + (read-byte [this])) + +(defprotocol IByteOutputStream + (write-byte [this byte])) + +(defprotocol ISeekableStream + (position [this]) + (seek [this position]) + (rewind [this])) diff --git a/pixie/streams/utf8.pxi b/pixie/streams/utf8.pxi new file mode 100644 index 00000000..8e8ab95f --- /dev/null +++ b/pixie/streams/utf8.pxi @@ -0,0 +1,86 @@ +(ns pixie.streams.utf8 + (require pixie.streams :refer :all)) + +(defprotocol IUTF8OutputStream + (write-char [this char] "Write a single character to the UTF8 stream")) + +(defprotocol IUTF8InputStream + (read-char [this] "Read a single character from the UTF8 stream")) + +(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)))) + :else (assert false (str "Cannot encode a UTF8 character of code " ch))))) + IDisposable + (-dispose! [this] + (dispose! out))) + +(deftype UTF8InputStream [in bad-char] + IUTF8InputStream + (read-char [this] + (when-let [byte (read-byte in)] + (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] + (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 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 + 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 + "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)))) 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/string.pxi b/pixie/string.pxi index 48b2f8dd..cc72b96f 100644 --- a/pixie/string.pxi +++ b/pixie/string.pxi @@ -1,11 +1,17 @@ (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) -(def index-of si/index-of) +(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) @@ -17,49 +23,111 @@ (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 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] (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 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 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." [s] (if s - (let [white #{\space \newline \tab \backspace \formfeed \return} - 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 + "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." + :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))))) 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/test.pxi b/pixie/test.pxi index cf77ccf2..2f622977 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 {})) @@ -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] @@ -82,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/pixie/time.pxi b/pixie/time.pxi new file mode 100644 index 00000000..a045b14f --- /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#) 1000000.0) " ms")) + return#)) diff --git a/pixie/uv.pxi b/pixie/uv.pxi index e6f03f15..0bcf4fba 100644 --- a/pixie/uv.pxi +++ b/pixie/uv.pxi @@ -1,12 +1,17 @@ (ns pixie.uv - (require pixie.ffi-infer :as f)) + (:require [pixie.ffi :as ffi] + [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) (f/defconst UV_RUN_NOWAIT) + (f/defcfn uv_close) + (f/defccallback uv_close_cb) + + (f/defcstruct uv_loop_t []) (f/defcfn uv_loop_init) @@ -15,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) @@ -23,8 +30,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 @@ -35,4 +52,219 @@ (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) + + ;; Time + (f/defcfn uv_hrtime) + + + ;; Filesystem + + (f/defcstruct uv_fs_t [:loop + :fs_type + :path + :result + :ptr + :statbuf.st_size + :statbuf.st_mode]) + (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 + :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) + (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/defconst UV_EOF) + + (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) + + (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) + + (f/defconst S_IRUSR) + (f/defconst S_IRWXU) + (f/defconst S_IWUSR) + + + ; ERRNO + (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) + + ; 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 []) + (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_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] + (let [b (buffer size) + bt (uv_buf_t)] + (pixie.ffi/set! bt :base b) + (pixie.ffi/set! bt :len size) + bt)) + + +(defn throw-on-error [result] + (if (neg? result) + (throw [::UVException (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))))) + +(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)))))) diff --git a/pixie/vm/array.py b/pixie/vm/array.py index 265001f7..4ca97813 100644 --- a/pixie/vm/array.py +++ b/pixie/vm/array.py @@ -13,9 +13,7 @@ class Array(object.Object): _type = object.Type(u"pixie.stdlib.Array") - __immutable_fields__ = ["_list[*]"] - def type(self): - return Array._type + _immutable_fields_ = ["_list"] def __init__(self, lst): self._list = lst @@ -28,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)): @@ -39,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") @@ -54,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) @@ -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 @@ -98,9 +98,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) @@ -127,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): @@ -174,9 +176,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 d372e920..28254673 100644 --- a/pixie/vm/atom.py +++ b/pixie/vm/atom.py @@ -7,18 +7,22 @@ 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) - def __init__(self, boxed_value): + 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) def _reset(self, v): assert isinstance(self, Atom) self._boxed_value = v - return self + return v @extend(proto._deref, Atom) @@ -26,6 +30,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/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/c_api.py b/pixie/vm/c_api.py new file mode 100644 index 00000000..a050a070 --- /dev/null +++ b/pixie/vm/c_api.py @@ -0,0 +1,20 @@ +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 + progname = rffi.charp2str(ll_progname) + init_vm(progname) + res = 0 + return rffi.cast(rffi.INT, res) + +@entrypoint_highlevel('main', [rffi.CCHARP], c_name='pixie_execute_source') +def pypy_execute_source(ll_source): + from target import EvalFn, run_with_stacklets + source = rffi.charp2str(ll_source) + f = EvalFn(source) + run_with_stacklets.invoke([f]) + res = 0 + return rffi.cast(rffi.INT, res) diff --git a/pixie/vm/code.py b/pixie/vm/code.py index ed17035f..5a54ea25 100644 --- a/pixie/vm/code.py +++ b/pixie/vm/code.py @@ -3,7 +3,9 @@ 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 +from rpython.rlib.objectmodel import we_are_translated import rpython.rlib.jit as jit import pixie.vm.rt as rt @@ -89,6 +91,7 @@ def slice_from_start(from_list, count, extra=r_uint(0)): class BaseCode(object.Object): + _immutable_fields_ = ["_meta", "_name"] def __init__(self): assert isinstance(self, BaseCode) self._name = u"unknown" @@ -124,15 +127,27 @@ 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") _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 @@ -153,13 +168,19 @@ 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 " + u",".join(acc)) + 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() def invoke(self, args): return self.invoke_with(args, self) @@ -172,12 +193,9 @@ 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): - return NativeFn._type - def invoke(self, args): return self.inner_invoke(args) @@ -191,10 +209,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"] - - def type(self): - return Code._type + _immutable_fields_ = ["_arity", "_consts[*]", "_bytecode", "_stack_size", "_meta", "_debug_points"] def __init__(self, name, arity, bytecode, consts, stack_size, debug_points, meta=nil): BaseCode.__init__(self) @@ -218,7 +233,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: @@ -249,12 +265,9 @@ 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): - return VariadicCode._type - def __init__(self, code, required_arity, meta=nil): BaseCode.__init__(self) self._required_arity = r_uint(required_arity) @@ -292,11 +305,8 @@ 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 - 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") @@ -348,49 +358,54 @@ def get_debug_points(self): class Undefined(object.Object): _type = object.Type(u"pixie.stdlib.Undefined") - def type(self): - return Undefined._type - undefined = Undefined() 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): _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 @@ -401,7 +416,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): @@ -414,17 +429,28 @@ 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(): - 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.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 @@ -437,18 +463,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): @@ -460,10 +474,10 @@ def __init__(self, ns, refer_syms=[], refer_all=False): class Namespace(object.Object): _type = object.Type(u"pixie.stdlib.Namespace") - def type(self): - return Namespace._type + _immutable_fields_ = ["_rev?"] def __init__(self, name): + self._rev = 0 self._registry = {} self._name = name self._refers = {} @@ -473,7 +487,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 @@ -497,10 +511,21 @@ 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) + + 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 @@ -509,14 +534,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 @@ -592,10 +610,7 @@ def invoke(self, args): class Protocol(object.Object): _type = object.Type(u"pixie.stdlib.Protocol") - __immutable_fields__ = ["_rev?"] - - def type(self): - return Protocol._type + _immutable_fields_ = ["_rev?"] def __init__(self, name): self._name = name @@ -621,10 +636,7 @@ def satisfies(self, tp): class PolymorphicFn(BaseCode): _type = object.Type(u"pixie.stdlib.PolymorphicFn") - def type(self): - return PolymorphicFn._type - - __immutable_fields__ = ["_rev?"] + _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): BaseCode.__init__(self) @@ -646,6 +658,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) @@ -695,10 +715,7 @@ 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?"] + _immutable_fields_ = ["_rev?"] def __init__(self, name, protocol): BaseCode.__init__(self) @@ -807,11 +824,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"): @@ -939,3 +957,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/compiler.py b/pixie/vm/compiler.py index afd06a1a..60cc353a 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 @@ -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 @@ -78,7 +80,10 @@ def __init__(self, name, argc, parent_ctx): self._max_sp = 0 self.can_tail_call = False self.closed_overs = [] - self.name = name + if name == default_fn_name and parent_ctx: + self.name = parent_ctx.name + u"_fn" + else: + self.name = name self.recur_points = [] self.debug_points = {} @@ -245,10 +250,17 @@ 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) -def resolve_var(ctx, name): + +def resolve_var(name): return NS_VAR.deref().resolve(name) def resolve_local(ctx, name): @@ -260,7 +272,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() @@ -311,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) @@ -341,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) + if rt._satisfies_QMARK_(rt.ISeq.deref(), form) and form is not nil: + + form = maybe_oop_invoke(form) + return compile_cons(form, ctx) if isinstance(form, numbers.Integer): ctx.push_const(form) @@ -367,7 +386,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) @@ -399,7 +418,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")) @@ -418,7 +436,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 @@ -449,7 +467,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") @@ -461,6 +482,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) @@ -468,12 +490,12 @@ 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) - 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) @@ -494,16 +516,13 @@ 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) 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)): @@ -520,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: @@ -616,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 @@ -678,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() @@ -686,7 +705,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) @@ -747,6 +766,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, @@ -754,13 +794,14 @@ def compile_in_ns(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, 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): @@ -815,7 +856,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() diff --git a/pixie/vm/cons.py b/pixie/vm/cons.py index e9f0eb92..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 @@ -57,12 +54,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/custom_types.py b/pixie/vm/custom_types.py index 7a1757b9..d5fb3047 100644 --- a/pixie/vm/custom_types.py +++ b/pixie/vm/custom_types.py @@ -1,55 +1,176 @@ -from pixie.vm.object import Object, Type, affirm +from pixie.vm.object import Object, Type, affirm, runtime_error, finalizer_registry 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 import pixie.vm.rt as rt +MAX_FIELDS = 32 + 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] + return self._slots.get(nm, -1) + + 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"] + _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 - self._fields = [None] * self._custom_type.get_num_slots() def type(self): return self._custom_type def set_field(self, name, val): idx = self._custom_type.get_slot_idx(name) - self._fields[idx] = val + if idx == -1: + 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.get_field_by_idx(idx) + if isinstance(old_val, AbstractMutableCell): + old_val.set_mutable_cell_value(self._custom_type, self, name, idx, val) + else: + self._custom_type.set_mutable(name) + self.set_field_by_idx(idx, val) return self + @jit.elidable + def _get_field_immutable(self, idx, rev): + return self.get_field_by_idx(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) - return self._fields[idx] + if idx == -1: + 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.get_field_by_idx(idx) + else: + value = self.get_field_immutable(idx) + + if isinstance(value, AbstractMutableCell): + return value.get_mutable_cell_value() + else: + 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) + 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): - affirm(isinstance(idx, r_uint), u"idx must be a r_uint") - self._fields[idx] = val - return self + 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)) @@ -60,9 +181,23 @@ def create_type(type_name, fields): return CustomType(rt.name(type_name), acc) @as_var("new") -def _new(tp): +@jit.unroll_safe +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): + 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 new_inst(tp, arr) @as_var("set-field!") def set_field(inst, field, val): @@ -77,3 +212,47 @@ 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 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) + if isinstance(value, Float): + fields.set_field_by_idx(idx, FloatMutableCell(value.float_val())) + else: + fields.set_field_by_idx(idx, value) + else: + self._mutable_integer_val = value.int_val() + + def get_mutable_cell_value(self): + 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.set_field_by_idx(idx, IntegerMutableCell(value.int_val())) + else: + fields.set_field_by_idx(idx, value) + else: + self._mutable_float_val = value.float_val() + + def get_mutable_cell_value(self): + return rt.wrap(self._mutable_float_val) diff --git a/pixie/vm/interpreter.py b/pixie/vm/interpreter.py index bbc96324..cb11508d 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 @@ -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): @@ -157,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/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/keyword.py b/pixie/vm/keyword.py index e1c14568..7da9af14 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 @@ -78,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/lazy_seq.py b/pixie/vm/lazy_seq.py index 7d052585..65cb744c 100644 --- a/pixie/vm/lazy_seq.py +++ b/pixie/vm/lazy_seq.py @@ -3,19 +3,18 @@ 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): _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 self._s = nil + @jit.jit_callback("lazy_seq_sval") def sval(self): if self._fn is None: return self._s @@ -24,6 +23,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 +55,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/libs/env.py b/pixie/vm/libs/env.py new file mode 100644 index 00000000..39b806df --- /dev/null +++ b/pixie/vm/libs/env.py @@ -0,0 +1,52 @@ +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 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/libs/ffi.py b/pixie/vm/libs/ffi.py index 15e13167..cdd670b4 100644 --- a/pixie/vm/libs/ffi.py +++ b/pixie/vm/libs/ffi.py @@ -4,11 +4,11 @@ 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 -from pixie.vm.numbers import Integer, Float +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 @@ -29,6 +29,9 @@ """ +class PointerType(object.Object): + pass + class CType(object.Type): def __init__(self, name): @@ -38,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 @@ -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) @@ -88,54 +89,51 @@ 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"] - - def type(self): - return FFIFn._type + _immutable_fields_ = ["_name", "_f_ptr", "_c_fn_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_libffi)) - 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, @@ -193,22 +191,28 @@ 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") +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)) + + -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") - def type(self): - return Buffer._type - def __init__(self, size): self._size = size self._used_size = 0 @@ -238,6 +242,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): @@ -328,6 +341,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") @@ -337,6 +370,7 @@ def ffi_get_value(self, ptr): return Float(casted[0]) def ffi_set_value(self, ptr, val): + val = to_float(val) casted = rffi.cast(rffi.DOUBLEP, ptr) casted[0] = rffi.cast(rffi.DOUBLE, val.float_val()) @@ -359,11 +393,29 @@ 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: + 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.CCHARP) @@ -412,7 +464,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() @@ -421,8 +479,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) @@ -431,9 +491,8 @@ def ffi_type(self): return clibffi.ffi_type_pointer cvoidp = CVoidP() -class VoidP(object.Object): - def type(self): - return cvoidp +class VoidP(PointerType): + _type = cvoidp def __init__(self, raw_data): self._raw_data = raw_data @@ -441,8 +500,28 @@ 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): + """(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,12 +529,19 @@ 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()) 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") @@ -481,6 +567,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()) @@ -494,7 +583,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): @@ -504,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 @@ -534,8 +620,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,12 +638,30 @@ def ffi_callback(args, ret_type): return CFunctionType(args_w, ret_type) -@as_var(u"ffi-prep-callback") + +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) + 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()) - unique_id = len(registered_callbacks) + 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, @@ -588,23 +695,30 @@ 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): + 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): - 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 @@ -617,7 +731,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 @@ -642,16 +756,27 @@ 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) 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): + """(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)) @@ -660,15 +785,19 @@ 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()) - 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): + """(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 +806,14 @@ 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") +@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))) - lltype.free(frm.raw_data(), flavor="raw") - - return nil + return rt.wrap(tp.get_size()) @extend(proto._val_at, CStructType.base_type) def val_at(self, k, not_found): @@ -692,14 +821,42 @@ 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) +@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") + + +def comp_ptrs(a, b): + assert isinstance(a, PointerType) + if not isinstance(b, PointerType): + return false + if a.raw_data() == b.raw_data(): + 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 -BIG_ENDIAN = sys.byteorder == 'big' USE_C_LIBFFI_MSVC = getattr(clibffi, 'USE_C_LIBFFI_MSVC', False) @@ -764,16 +921,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'), 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) diff --git a/pixie/vm/libs/path.py b/pixie/vm/libs/path.py index 854bedce..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) @@ -18,7 +15,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 +25,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 +58,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/pixie/vm/libs/pxic/reader.py b/pixie/vm/libs/pxic/reader.py index b4ec9cbb..2cc5d799 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 @@ -54,8 +55,18 @@ 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): - return rdr.read_cached_string() + s = rdr.read_cached_string() + return s def read_code(rdr): sz = read_raw_integer(rdr) @@ -129,7 +140,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): @@ -137,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: @@ -151,6 +163,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: @@ -171,6 +184,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 9b3e806d..0d2e511a 100644 --- a/pixie/vm/libs/pxic/writer.py +++ b/pixie/vm/libs/pxic/writer.py @@ -4,12 +4,13 @@ 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 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) @@ -72,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 @@ -99,6 +98,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)) @@ -107,6 +116,14 @@ def write_int(i, wtr): wtr.write(chr(INT_STRING)) write_string_raw(unicode(str(i)), wtr) +def write_bigint(i, 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) write_string_raw(unicode(str(f)), wtr) @@ -231,7 +248,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) @@ -246,6 +262,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): #TODO test + write_bigint(obj.bigint_val(), wtr) elif isinstance(obj, Float): write_float(obj.float_val(), wtr) elif isinstance(obj, Code): @@ -255,11 +273,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/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 fe06eafd..8e637365 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 @@ -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) @@ -107,8 +92,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): @@ -116,12 +105,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,15 +139,33 @@ 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) - 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 = "))") + 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 = "))") 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") 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}) @@ -156,9 +180,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() @@ -276,9 +301,11 @@ 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 + object.runtime_error(u"Cannot convert %s to float" %x.type().name()) def to_float_conv(c): if c == Float: diff --git a/pixie/vm/object.py b/pixie/vm/object.py index 2abf674e..2ef03de3 100644 --- a/pixie/vm/object.py +++ b/pixie/vm/object.py @@ -1,13 +1,36 @@ 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): + 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 """ _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): @@ -29,6 +52,10 @@ def hash(self): def promote(self): return self + + + + class TypeRegistry(object): def __init__(self): self._types = {} @@ -41,7 +68,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 @@ -67,21 +93,27 @@ def get_type_by_name(nm): return _type_registry.get_by_name(nm) class Type(Object): - def __init__(self, name, parent = None): + _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) 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 = [] + self._has_finalizer = False def name(self): return self._name - def type(self): - return Type._type + def parent(self): + return self._parent def add_subclass(self, tp): self._subclasses.append(tp) @@ -89,7 +121,16 @@ def add_subclass(self, tp): def subclasses(self): return self._subclasses -Type._type = Type(u"Type") + @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") @jit.elidable_promote() def istypeinstance(obj, t): @@ -109,13 +150,13 @@ 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 = [] - def type(self): - return RuntimeException._type - def __repr__(self): import pixie.vm.rt as rt s = [] @@ -124,8 +165,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) @@ -145,16 +186,29 @@ 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: + 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): - return ErrorInfo._type + def __init__(self): pass @@ -220,7 +274,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 @@ -239,9 +292,34 @@ 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")} tm[keyword(u"name")] = String(self._name) return tm + +class ExtraCodeInfo(ErrorInfo): + def __init__(self, str, data=None): + self._str = str + self._data = data + + 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"msg"): rt.wrap(self._str)} + + if self._data: + tm[keyword(u"data")] = self._data + + return tm + + +def add_info(ex, data): + assert isinstance(ex, WrappedException) + ex._ex._trace.append(ExtraCodeInfo(data)) + return ex diff --git a/pixie/vm/persistent_hash_map.py b/pixie/vm/persistent_hash_map.py index b2dc1563..7cab577c 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) @@ -20,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 @@ -59,23 +55,10 @@ 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") - def type(self): - return INode._type - def assoc_inode(self, shift, hash_val, key, val, added_leaf): pass @@ -185,9 +168,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 +196,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 +272,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 +316,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 +337,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..f2bd5d4a 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") @@ -13,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 @@ -32,9 +28,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 +95,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() diff --git a/pixie/vm/persistent_list.py b/pixie/vm/persistent_list.py index 91f76da8..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 @@ -82,6 +79,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) @@ -97,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 26517cd4..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 @@ -182,7 +176,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): @@ -210,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 @@ -438,7 +430,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 @@ -456,7 +448,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/primitives.py b/pixie/vm/primitives.py index acb37963..5924b6a5 100644 --- a/pixie/vm/primitives.py +++ b/pixie/vm/primitives.py @@ -1,22 +1,15 @@ import pixie.vm.object as object - class Nil(object.Object): _type = object.Type(u"pixie.stdlib.Nil") - def type(self): - return Nil._type - + def __repr__(self): + return u"nil" nil = Nil() - class Bool(object.Object): _type = object.Type(u"pixie.stdlib.Bool") - def type(self): - return Bool._type - - 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 3049ae2f..4a6ab292 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 @@ -9,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 @@ -20,6 +20,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") @@ -27,13 +31,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") @@ -41,13 +45,14 @@ class PlatformReader(object.Object): def read(self): assert False - def unread(self, ch): + def unread(self): pass def reset_line(self): return self class StringReader(PlatformReader): + _type = object.Type(u"pixie.stdlib.StringReader") def __init__(self, s): affirm(isinstance(s, unicode), u"StringReader requires unicode") @@ -61,17 +66,19 @@ def read(self): self._idx += 1 return ch - def unread(self, ch): + def unread(self): self._idx -= 1 -class PromptReader(PlatformReader): - def __init__(self): +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 = _readline(str(rt.name(rt.ns.deref())) + " => ") + 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) @@ -85,14 +92,19 @@ 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): + """(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): - return LinePromise._type def __init__(self): self._chrs = [] @@ -168,7 +180,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 +211,7 @@ def eat_whitespace(rdr): ch = rdr.read() if is_whitespace(ch): continue - rdr.unread(ch) + rdr.unread() return class ReaderHandler(py_object): @@ -210,8 +222,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,9 +235,12 @@ def invoke(self, rdr, ch): for x in range(len(lst) - 1, -1, -1): acc = cons(lst[x], acc) return acc + + rdr.unread() - rdr.unread(ch) - lst.append(read(rdr, True)) + itm = read_inner(rdr, True, always_return_form=False) + if itm != rdr: + lst.append(itm) class UnmatchedListReader(ReaderHandler): def invoke(self, rdr, ch): @@ -231,13 +250,21 @@ class VectorReader(ReaderHandler): def invoke(self, rdr, ch): acc = EMPTY_VECTOR while True: - eat_whitespace(rdr) + 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) - acc = rt.conj(acc, read(rdr, True)) + rdr.unread() + itm = read_inner(rdr, True, always_return_form=False) + if itm != rdr: + acc = rt.conj(acc, itm) + class UnmatchedVectorReader(ReaderHandler): def invoke(self, rdr, ch): @@ -247,42 +274,56 @@ 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) - k = read(rdr, True) - v = read(rdr, False) - acc = rt._assoc(acc, k, v) + rdr.unread() + itm = read_inner(rdr, True, always_return_form=False) + if itm != rdr: + k = itm + itm = rdr + while itm == rdr: + itm = read_inner(rdr, False, always_return_form=False) + v = itm + 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): - itm = read(rdr, True) + itm = read_inner(rdr, True) 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(rdr, True) - nms = rt.name(rt.ns.deref()) + ch = rdr.read() + itm = read_symbol(rdr, ch, False) + return self.fqd(itm) else: - rdr.unread(ch) - itm = read(rdr, True) + itm = read_symbol(rdr, ch, False) - 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): @@ -294,7 +335,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)) @@ -320,11 +361,11 @@ 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): - rdr.unread(ch) + rdr.unread() return acc acc += ch @@ -372,7 +413,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") @@ -382,20 +423,21 @@ 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) \ + 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 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) @@ -429,16 +471,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): @@ -456,15 +509,15 @@ def invoke(self, rdr, ch): if ch == "@": sym = UNQUOTE_SPLICING else: - rdr.unread(ch) + rdr.unread() - 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) @@ -472,7 +525,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 @@ -483,11 +536,11 @@ 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) - 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): @@ -523,8 +576,8 @@ def invoke(self, rdr, ch): try: ARG_ENV.set_value(rt.assoc(EMPTY_MAP, ARG_MAX, rt.wrap(-1))) - rdr.unread(ch) - form = read(rdr, True) + rdr.unread() + form = read_inner(rdr, True) args = EMPTY_VECTOR percent_args = ARG_ENV.deref() @@ -549,17 +602,28 @@ 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 - rdr.unread(ch) - acc = acc.conj(read(rdr, True)) + rdr.unread() + itm = read_inner(rdr, True, always_return_form=False) + 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): @@ -573,17 +637,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(), @@ -667,7 +727,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: @@ -679,25 +739,27 @@ 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: ch = rdr.read() if is_whitespace(ch) or is_terminating_macro(ch): - rdr.unread(ch) + rdr.unread() break acc.append(ch) except EOFError: 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): @@ -706,6 +768,7 @@ class EOF(object.Object): eof = EOF() +code.intern_var(u"pixie.stdlib", u"eof").set_root(eof) @@ -717,18 +780,18 @@ 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) - -def read(rdr, error_on_eof): +def read_inner(rdr, error_on_eof, always_return_form=True): try: 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 @@ -742,6 +805,9 @@ 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_inner(rdr, error_on_eof, always_return_form=always_return_form) + elif is_digit(ch): itm = read_number(rdr, ch) @@ -749,20 +815,42 @@ 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: 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 +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) + 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/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/rt.py b/pixie/vm/rt.py index 342708c3..c17389cb 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 @@ -64,13 +65,15 @@ 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 import pixie.vm.threads import pixie.vm.string_builder + import pixie.vm.stacklet - numbers.init() + import pixie.vm.c_api @specialize.argtype(0) def wrap(x): @@ -144,7 +147,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)) @@ -156,6 +159,12 @@ 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 + + numbers.init() + code.init() + + diff --git a/pixie/vm/stacklet.py b/pixie/vm/stacklet.py new file mode 100644 index 00000000..d4e8e5c4 --- /dev/null +++ b/pixie/vm/stacklet.py @@ -0,0 +1,53 @@ +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 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) diff --git a/pixie/vm/stdlib.py b/pixie/vm/stdlib.py index 07fdb380..d8611d72 100644 --- a/pixie/vm/stdlib.py +++ b/pixie/vm/stdlib.py @@ -1,15 +1,16 @@ # -*- coding: utf-8 -*- -from pixie.vm.object import Type, _type_registry, WrappedException, RuntimeException, affirm, InterpreterCodeInfo, istypeinstance, \ - runtime_error -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, 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 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 pixie.vm.interpreter import ShallowContinuation 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"]) @@ -43,6 +44,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")) @@ -55,10 +58,18 @@ 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!"]) +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 + + tp.set_finalizer() + +code.PolymorphicFn.maybe_mark_finalizer = maybe_mark_finalizer @as_var("pixie.stdlib.internal", "-defprotocol") def _defprotocol(name, methods): @@ -100,7 +111,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"") @@ -119,7 +129,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) @@ -129,7 +139,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: @@ -143,7 +153,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): @@ -151,7 +161,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) @@ -231,22 +241,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): @@ -264,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("+") @@ -284,7 +281,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): @@ -301,7 +298,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))) @@ -311,8 +307,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] @@ -333,19 +329,29 @@ 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 +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?") +@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 @@ -363,11 +369,14 @@ 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 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") @@ -413,14 +422,15 @@ 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 - from pixie.vm.persistent_vector import EMPTY as EMPTY_VECTOR - import os 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 @@ -457,7 +467,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" @@ -481,7 +490,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" @@ -501,12 +509,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" @@ -529,7 +557,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") @@ -547,11 +574,29 @@ def ns_map(ns): return nil +@as_var("ns-aliases") +def ns_aliases(ns): + 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 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)) @@ -572,9 +617,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 @@ -620,7 +665,11 @@ 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 + +@as_var("map?") +def map_QMARK_(a): + return true if rt._satisfies_QMARK_(rt.IMap.deref(), a) else false @returns(bool) @as_var("eq") @@ -638,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) @@ -653,18 +703,18 @@ 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: 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 raise - ex = RuntimeException(rt.wrap(u"Some error")) + 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]) @@ -674,13 +724,23 @@ 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): - 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 @@ -730,7 +790,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 @@ -785,6 +845,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() @@ -799,5 +860,91 @@ 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) + return rt.wrap(self._doc) + + +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 + + @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) + 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) + +@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 + +@as_var("-run-finalizers") +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/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/symbol.py b/pixie/vm/symbol.py index 1fb9bbc3..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 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..8d02de43 100644 --- a/pixie/vm/test/test_reader.py +++ b/pixie/vm/test/test_reader.py @@ -1,9 +1,12 @@ -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 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 import pixie.vm.rt as rt import unittest @@ -17,7 +20,18 @@ 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}, + u"(\\a)": (Character(ord("a")),), + u"(\\))": (Character(ord(")")),), + u"(\\()": (Character(ord("(")),), + u"(\\;)": (Character(ord(";")),)} class TestReader(unittest.TestCase): def _compare(self, frm, to): @@ -27,6 +41,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 +53,20 @@ 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)) + + 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))) diff --git a/pixie/vm/threads.py b/pixie/vm/threads.py index 6d8404b9..e42d7d18 100644 --- a/pixie/vm/threads.py +++ b/pixie/vm/threads.py @@ -1,9 +1,10 @@ +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 import rpython.rlib.rgil as rgil from pixie.vm.code import as_var - -from rpython.rlib.objectmodel import invoke_around_extcall +import pixie.vm.rt as rt class Bootstrapper(object): def __init__(self): @@ -12,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() @@ -39,7 +39,7 @@ def bootstrap(): rthread.gc_thread_start() fn = bootstrapper.fn() bootstrapper.release() - fn.invoke([]) + safe_invoke(fn, []) rthread.gc_thread_die() bootstrapper = Bootstrapper() @@ -52,48 +52,36 @@ def new_thread(fn): @as_var("-yield-thread") def yield_thread(): - do_yield_thread() + rgil.yield_thread() return nil -## 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_. +# Locks + +class Lock(Object): + _type = Type(u"pixie.stdlib.Lock") + def __init__(self, ll_lock): + self._ll_lock = ll_lock + + +@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()) + + # The *_external_call() functions are themselves called only from the rffi # module from a helper function that also has this hint. 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) 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/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." diff --git a/target.py b/target.py index a91a940b..71be1c7d 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, 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 @@ -18,10 +17,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 @@ -38,70 +39,22 @@ 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") - -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) +load_path = intern_var(u"pixie.stdlib", u"internal-load-path") class ReplFn(NativeFn): 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 "----------------------------" + from pixie.vm.code import intern_var + rt.load_ns(rt.wrap(u"pixie/repl.pxi")) + repl = intern_var(u"pixie.repl", u"repl") 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) + repl.invoke([]) - 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) +load_file = intern_var(u"pixie.stdlib", u"load-file") class BatchModeFn(NativeFn): def __init__(self, args): @@ -130,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() @@ -156,6 +111,18 @@ 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 + try: + rt.compile_file(rt.wrap(self._filename)) + except WrappedException as ex: + print "Error: ", ex._ex.__repr__() + os._exit(1) + class IsPreloadFlag(object): def __init__(self): @@ -177,22 +144,33 @@ 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 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: + + 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] @@ -213,7 +191,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 @@ -232,7 +210,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 @@ -249,9 +227,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__() @@ -260,6 +238,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) 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 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/data/test-json.pxi b/tests/pixie/tests/data/test-json.pxi new file mode 100644 index 00000000..098ad019 --- /dev/null +++ b/tests/pixie/tests/data/test-json.pxi @@ -0,0 +1,76 @@ +(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-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]}"] + (assert= (-> string json/read-string json/write-string) + string))) 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/io/test-tcp.pxi b/tests/pixie/tests/io/test-tcp.pxi new file mode 100644 index 00000000..a86439a2 --- /dev/null +++ b/tests/pixie/tests/io/test-tcp.pxi @@ -0,0 +1,40 @@ +(ns pixie.test.io.test-tcp + (:require [pixie.io.tcp :refer :all] + [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.uv :as uv] + [pixie.test :refer :all])) + +(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) + + (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)))) 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})) 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)))))) 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))) diff --git a/tests/pixie/tests/test-async.pxi b/tests/pixie/tests/test-async.pxi new file mode 100644 index 00000000..19fa3731 --- /dev/null +++ b/tests/pixie/tests/test-async.pxi @@ -0,0 +1,29 @@ +(ns pixie.tests.test-async + (:require [pixie.stacklets :as st] + [pixie.async :as async :refer :all] + [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))) + +(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))) diff --git a/tests/pixie/tests/test-buffers.pxi b/tests/pixie/tests/test-buffers.pxi new file mode 100644 index 00000000..1afd5326 --- /dev/null +++ b/tests/pixie/tests/test-buffers.pxi @@ -0,0 +1,41 @@ +(ns pixie.tests.test-buffers + (:require [pixie.test :refer :all] + [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)))))) + + +(def drain-buffer (partial into [])) + +(deftest test-dropping-buffer + (let [buf (dropping-buffer 4)] + (dotimes [x 5] + (add! buf x)) + (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))))) diff --git a/tests/pixie/tests/test-channels.pxi b/tests/pixie/tests/test-channels.pxi new file mode 100644 index 00000000..0cdebfd0 --- /dev/null +++ b/tests/pixie/tests/test-channels.pxi @@ -0,0 +1,87 @@ +(ns pixie.tests.test-channels + (:require [pixie.test :refer :all] + [pixie.channels :refer :all] + [pixie.async :refer :all] + [pixie.stacklets :as st])) + + +(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)))) + +(deftest closing-dispatches-future-takes-with-nil + (let [c (chan 1) + tp (promise)] + (-close! c) + (-take! c tp) + (assert= @tp nil))) + +(deftest closing-dispatches-past-takes-with-nil + (let [c (chan 1) + tp (promise)] + (-take! c tp) + (-close! c) + (assert= @tp nil))) + +(deftest closed-channels-return-false-on-future-puts + (let [c (chan 1) + pp (promise)] + (-close! c) + (assert= (-put! c 42 pp) false) + (assert= @pp false))) + +(deftest closing-allows-puts-to-flush + (let [c (chan) + tps (mapv (fn [_] (promise)) (range 3))] + (dotimes [x 2] + (-put! c x (fn [_] nil))) + (-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))) 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-compiler.pxi b/tests/pixie/tests/test-compiler.pxi index 052bafe2..751ee95e 100644 --- a/tests/pixie/tests/test-compiler.pxi +++ b/tests/pixie/tests/test-compiler.pxi @@ -20,3 +20,54 @@ (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))) + +(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)) diff --git a/tests/pixie/tests/test-csp.pxi b/tests/pixie/tests/test-csp.pxi new file mode 100644 index 00000000..94a241bd --- /dev/null +++ b/tests/pixie/tests/test-csp.pxi @@ -0,0 +1,48 @@ +(ns pixie.tests.test-buffers + (require pixie.test :refer :all) + (require pixie.csp :refer :all)) + + +(deftest test-go-blocks-return-values + (assert= (! c) (range 10)) + (close! c))] + (assert= (vec c) (range 10)) + (assert= (! c1 1) + (>! c2 2) + (assert (not (= c1 c2))) + (assert= (! 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)))))) + 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))) + + +(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))) + +(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)))) 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-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))))))) diff --git a/tests/pixie/tests/test-ffi.pxi b/tests/pixie/tests/test-ffi.pxi index 71502c8e..4cc486dd 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,14 +37,29 @@ (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-invalid-float-argument + (t/assert-throws? (m/sin "nil")) + (t/assert-throws? (m/sin nil)) + ) (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 @@ -55,3 +71,13 @@ (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)) + + +(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))))) 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) diff --git a/tests/pixie/tests/test-fs.pxi b/tests/pixie/tests/test-fs.pxi index c56143cd..c02d664a 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,10 +28,12 @@ (fs/file file-b) (fs/file file-c)])) 1))) + (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))) + (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")) @@ -39,15 +41,23 @@ (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))) + (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))) + (t/assert= (set (fs/walk-dirs (fs/dir dir-a))) #{(fs/dir (str dir-a "/parent")) - (fs/dir (str dir-a "/parent/child"))})))) + (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 +101,25 @@ (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))) + +(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)))) 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 36ffa040..07a3606b 100644 --- a/tests/pixie/tests/test-io.pxi +++ b/tests/pixie/tests/test-io.pxi @@ -1,31 +1,190 @@ (ns pixie.tests.test-io (require pixie.test :as t) - (require pixie.io :as io)) + (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 (let [f (io/open-read "tests/pixie/tests/test-io.txt")] (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-line +(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/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-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/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."))) -(comment +(t/deftest test-seek + (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) + (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-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/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"))] + (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... + (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 128))] - (t/assert= val (read-string (io/slurp "test.tmp" (io/spit "test.tmp" val)))))) -) + (let [val (vec (range 1280))] + (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= "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 "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 + (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")))) diff --git a/tests/pixie/tests/test-keywords.pxi b/tests/pixie/tests/test-keywords.pxi index 5156d27a..1094cf45 100644 --- a/tests/pixie/tests/test-keywords.pxi +++ b/tests/pixie/tests/test-keywords.pxi @@ -6,20 +6,64 @@ (t/assert= (:a m) 1) (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") (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) (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 "foo/bar") :foo/bar)) + (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)) + (t/assert-throws? (keyword nil)) + (t/assert-throws? (keyword true))) diff --git a/tests/pixie/tests/test-macros.pxi b/tests/pixie/tests/test-macros.pxi new file mode 100644 index 00000000..238408d3 --- /dev/null +++ b/tests/pixie/tests/test-macros.pxi @@ -0,0 +1,52 @@ +(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))) + +(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))))) diff --git a/tests/pixie/tests/test-numbers.pxi b/tests/pixie/tests/test-numbers.pxi index 1d88d9d0..270ba742 100644 --- a/tests/pixie/tests/test-numbers.pxi +++ b/tests/pixie/tests/test-numbers.pxi @@ -49,3 +49,31 @@ (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= 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))) + (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)))) + +(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)))) + +(t/deftest test-wrap-around + (t/assert= Integer (type (unchecked-add 9223372036854775807 1))) + (t/assert (-num-eq -9223372036854775808 (unchecked-add 9223372036854775807 1)))) 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))) diff --git a/tests/pixie/tests/test-parser.pxi b/tests/pixie/tests/test-parser.pxi new file mode 100644 index 00000000..af21a1b7 --- /dev/null +++ b/tests/pixie/tests/test-parser.pxi @@ -0,0 +1,46 @@ +(ns pixie.tests.test-parser + (:require [pixie.test :refer :all] + [pixie.parser :refer :all])) + +(deftest test-and + (let [p (parser [] + ENTRY (and \a \b <- [\a \b])) + c (string-cursor "abc")] + (assert= ((:ENTRY p) c) [\a \b]) + (assert= (current c) \c) + (assert= 2 (snapshot c)))) + +(deftest test-or + (let [p (parser [] + ENTRY (or \b \a)) + c (string-cursor "abc")] + (assert= ((:ENTRY p) c) \a) + (assert= (current c) \b) + (assert= 1 (snapshot c)))) + + +(defparser as-and-bs [] + ENTRY (and S -> value + end + <- value) + S (one+ AB) <- `[:S ~@value] + AB (and A -> a + B -> b + <- [:AB a b]) + A (one+ \a) <- `[:A ~@value] + B (one+ \b) <- `[:B ~@value]) + +(deftest test-as-and-bs + (let [c (string-cursor "aabbaa")] + (assert= ((:S as-and-bs) c) [:S [:AB + [:A \a \a] + [:B \b \b]]]) + (assert (not (at-end? c))) + (assert= (snapshot c) 4) + + (assert (failure? ((:S as-and-bs) c)))) + + (let [c (string-cursor "aabbaa")] + (assert (failure? ((:ENTRY as-and-bs) c)) ) + (assert (not (at-end? c))) + (assert= (snapshot c) 0))) diff --git a/tests/pixie/tests/test-readeval.pxi b/tests/pixie/tests/test-readeval.pxi index 01be1a3d..636dca23 100644 --- a/tests/pixie/tests/test-readeval.pxi +++ b/tests/pixie/tests/test-readeval.pxi @@ -14,4 +14,60 @@ (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 + (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"))) + +(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 :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))) diff --git a/tests/pixie/tests/test-sets.pxi b/tests/pixie/tests/test-sets.pxi new file mode 100644 index 00000000..bccc8041 --- /dev/null +++ b/tests/pixie/tests/test-sets.pxi @@ -0,0 +1,69 @@ +(ns pixie.test.test-sets + (require pixie.test :as t) + (require pixie.set :as s)) + +(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) + (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]))) + + (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])))) diff --git a/tests/pixie/tests/test-stdlib.pxi b/tests/pixie/tests/test-stdlib.pxi index c0c0b711..9b2174e0 100644 --- a/tests/pixie/tests/test-stdlib.pxi +++ b/tests/pixie/tests/test-stdlib.pxi @@ -6,10 +6,59 @@ (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]) + (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]))) + (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])) +(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= (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 [: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) + [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") @@ -28,7 +77,9 @@ (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 (repeat 3 7)) "(7 7 7)") + (t/assert= (str (range 3)) "(0 1 2)")) (t/deftest test-repr (t/assert= (-repr nil) "nil") @@ -50,13 +101,16 @@ (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 (repeat 3 7)) "(7 7 7)") + (t/assert= (-repr (range 3)) "(0 1 2)")) (t/deftest test-nth ;; works if the index is found (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) @@ -82,6 +136,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"))) @@ -90,21 +147,34 @@ (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)) +(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) (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 {: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) @@ -120,6 +190,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) @@ -143,6 +214,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) @@ -159,6 +231,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) @@ -179,6 +252,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)) '()) @@ -190,6 +273,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)] @@ -235,10 +340,20 @@ (t/assert= (fn? #(%)) true) (t/assert= (fn? :foo) true) (t/assert= (fn? 1) false) - (t/assert= (fn? and) false) + (t/assert= (fn? and) true) (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) @@ -263,13 +378,22 @@ (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))) + (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) (t/assert= (some odd? [2 4 6 8]) false) (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) [])) []) @@ -285,7 +409,12 @@ (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= (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)) @@ -323,17 +452,59 @@ (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)] + (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]]))) (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-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)) - (-seq (-iterator (range 10))) '(0 1 2 3 4 5 6 7 8 9)) true)) @@ -344,44 +515,137 @@ (defn baz [x y] (+ x y)) ;; Back into the text namespace (in-ns :pixie.tests.test-stdlib) - (t/assert= (set (keys (ns-map 'foo))) + (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) (t/assert= 0 (let [x (atom 10) - cnt (atom 0)] + cnt (atom 0)] (while (pos? @x) (do (swap! x dec) (swap! cnt inc))) @x)) (t/assert= 10 (let [x (atom 10) - cnt (atom 0)] + cnt (atom 0)] (while (pos? @x) (do (swap! x dec) (swap! cnt inc))) @cnt))) +(t/deftest test-loop + (t/assert= + [3 -3] + (loop [[a b :as vs] [0 0]] + (if (> a 2) + vs + (recur [(inc a) (dec b)])))) + (t/assert= + 3 + (loop [a 1] + (if (> a 2) + 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/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]) + (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/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 ()) ()) + (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-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 + (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) + (seq (eduction cat [[1 2 3 nil] [4 5 6 nil]])))) (t/deftest test-trace (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 @@ -397,7 +661,7 @@ (t/assert= (group-by :age [{:name "banjo" :age 3} {:name "mary" :age 3} {:name "boris" :age 7}]) - {3 [{:name "banjo" :age 3} + {3 [{:name "banjo" :age 3} {:name "mary" :age 3}] 7 [{:name "boris" :age 7}]}) (t/assert= (group-by even? (range 1 5)) @@ -408,3 +672,173 @@ (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-throws? RuntimeException + "No matching clause!" + (condp :dont-call-me :dont-use-me)) + (let [f (fn [x] + (condp = x + 1 :one + 2 :two + :whatever))] + (t/assert= (f 1) :one) + (t/assert= (f 2) :two) + (t/assert= (f 9) :whatever))) + +(t/deftest test-case + (t/assert-throws? RuntimeException + "No matching clause!" + (case :no-matter-what)) + (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))) + +(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-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) + (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])) + (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= 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)))) + +(t/deftest test-comp + (t/assert= 5 ((comp inc inc inc inc) 1)) + (t/assert= :xyz ((comp) :xyz))) + +(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= :bar (-> a (with-meta {:foo :bar}) meta :foo)))) + +(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)))] + (t/assert= 6 (f 12)) + (t/assert-throws? RuntimeException + "Assert failed: (even? a)" + (f 13)) + (t/assert-throws? RuntimeException + "Assert failed: (= % 6)" + (f 14)) + (t/assert= 15 (f 7 8)) + (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))) + +(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)))) + +(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)))) + +(t/deftest test-iterate + (t/assert= (take 5 (iterate inc 5)) '(5 6 7 8 9)) + (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})))))) + +(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]))) diff --git a/tests/pixie/tests/test-strings.pxi b/tests/pixie/tests/test-strings.pxi index 248d8ca2..0013f6e2 100644 --- a/tests/pixie/tests/test-strings.pxi +++ b/tests/pixie/tests/test-strings.pxi @@ -27,19 +27,40 @@ (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) (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"] @@ -89,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") @@ -101,6 +132,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") @@ -141,3 +178,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)) 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= 🍺 "🍺=👍"))) diff --git a/tests/pixie/tests/test-uv.pxi b/tests/pixie/tests/test-uv.pxi deleted file mode 100644 index 3998ab37..00000000 --- a/tests/pixie/tests/test-uv.pxi +++ /dev/null @@ -1,20 +0,0 @@ -(ns pixie.test-uv - (require pixie.uv :as uv) - (require pixie.test :as t)) - - -(t/deftest timer-tests - (let [cb (atom nil) - result (atom false) - loop (uv/uv_loop_t) - timer (uv/uv_timer_t)] - (reset! cb (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))) 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})))