Fix butlast and test for disassemble. Conflicts: hy/core/language.hy
This commit is contained in:
commit
01ee54cf62
13
.travis.yml
13
.travis.yml
@ -1,19 +1,18 @@
|
||||
language: python
|
||||
python:
|
||||
- "pypy"
|
||||
- "2.6"
|
||||
- "2.7"
|
||||
- "3.2"
|
||||
- "3.3"
|
||||
- "2.6"
|
||||
- "3.4"
|
||||
# command to install dependencies
|
||||
install:
|
||||
- pip install -r requirements.txt
|
||||
- pip install -r requirements-dev.txt
|
||||
- pip install coveralls
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install argparse importlib unittest2 astor; fi
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install astor; fi
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install astor; fi
|
||||
- python setup.py -q install
|
||||
# # command to run tests
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi # needs for running tests
|
||||
- pip install --allow-all-external -e .
|
||||
# command to run tests
|
||||
script: make travis
|
||||
after_success: coveralls
|
||||
notifications:
|
||||
|
3
AUTHORS
3
AUTHORS
@ -43,3 +43,6 @@
|
||||
* Richard Parsons <richard.lee.parsons@gmail.com>
|
||||
* han semaj <sangho.nah@gmail.com>
|
||||
* kirbyfan64 <kirbyfan64@users.noreply.github.com>
|
||||
* Brendan Curran-Johnson <brendan@bcjbcj.ca>
|
||||
* Ivan Kozik <ivan@ludios.org>
|
||||
* Allison Kaptur <allison.kaptur@gmail.com>
|
||||
|
80
NEWS
80
NEWS
@ -1,3 +1,83 @@
|
||||
Changes from 0.9.12
|
||||
|
||||
0.10.0 - the "oh man I'm late for PyCon" release
|
||||
|
||||
Thanks to theanalyst (Abhi) for getting the release notes
|
||||
together. You're the best!
|
||||
- Hy Society
|
||||
|
||||
[ Breaking Changes ]
|
||||
|
||||
We're calling this release 0.10 because we broke
|
||||
API. Sorry about that. We've removed kwapply in
|
||||
favor of using `apply`. Please be sure to upgrade
|
||||
all code to work with `apply`.
|
||||
|
||||
(apply function-call args kwargs) ; is the signature
|
||||
|
||||
[Thanks]
|
||||
|
||||
Major shoutout to Clinton Dreisbach for implementing loop/recur.
|
||||
As always, massive hugs to olasd for the constant reviews and for
|
||||
implementing HyCons cells. Thanks to @kenanb for redesigning the
|
||||
new Hy logo.
|
||||
|
||||
Many thanks to algernon for working on adderall, which helped
|
||||
push Hy further this cycle. Adderall is an implementation of miniKanren
|
||||
in Hy. If you're interested in using Adderall, check out hydiomatic,
|
||||
which prettfies Hy source using Adderall rules.
|
||||
|
||||
This release saw an increase of about 11 contributors for a point
|
||||
release, you guys rock!
|
||||
|
||||
-Hy Society
|
||||
|
||||
[ Language Changes ]
|
||||
|
||||
* `for' revamped again (Last time, we hope!), this time using a saner
|
||||
itertools.product when nesting
|
||||
* `lisp-if'/`lif' added for the lisp-like everything is true if, giving
|
||||
seasoned lispers a better if check (0 is a value, etc)
|
||||
* Reader Macros are macros now!
|
||||
* yield-from is now a proper yield from on Python 3. It also now breaks on
|
||||
Python 2.x.
|
||||
* Added if-not macro
|
||||
* We finally have a lisp like cons cells
|
||||
* Generator expressions, set & dict comprehensions are now supported
|
||||
* (.) is a mini DSL for attribute access
|
||||
* `macroexpand' & `macroexpand-1' added to core
|
||||
* `disassemble' added to core, which dumps the AST or equivalent python code
|
||||
* `coll?' added to core to check for a collection
|
||||
* `identity' function added to core
|
||||
|
||||
[ Misc. Fixes ]
|
||||
* Lots of doc fixes. Reorganization as well as better docs on Hy internals
|
||||
* Universal Wheel Support
|
||||
* Pygments > 1.6 supports Hy now. All codeblocks in docs have been changed
|
||||
from clojure to hy
|
||||
* Hy REPL supports invoking with --spy & -i options [reword]
|
||||
* `first' and `rest' are functions and not macros anymore
|
||||
* "clean" target added to Makefile
|
||||
* hy2py supports a bunch of commandline options to show AST, source etc.
|
||||
* Sub-object mangling: every identifier is split along the dots & mangled
|
||||
seperately
|
||||
|
||||
[ Bug Fixes ]
|
||||
* Empty MacroExpansions work as expected
|
||||
* Python 3.4 port. Sorry this wasn't in a 3.4 release time, we forgot to do
|
||||
a release. Whoops.
|
||||
* eg/lxml/parse-tumblr.hy works with Python 3
|
||||
* hy2py works on Windows
|
||||
* Fixed unicode encoding issue in REPL during unicode exceptions
|
||||
* Fixed handling of comments at end of input (#382)
|
||||
|
||||
[ Contrib changes ]
|
||||
* Curry module added to contrib
|
||||
* Loop/recur module added which provides TCO at tail position
|
||||
* defmulti has been added - check out more in the docs -- thanks to Foxboron for this one!
|
||||
* Walk module for walking the Hy AST, features a `macroexpand-all` as well
|
||||
|
||||
|
||||
Changes from Hy 0.9.11
|
||||
|
||||
tl;dr:
|
||||
|
39
bin/hy2py
39
bin/hy2py
@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
from __future__ import print_function
|
||||
from hy.importer import (import_file_to_ast, import_file_to_hst)
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
import astor.codegen
|
||||
|
||||
module_name = "<STDIN>"
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="hy2py",
|
||||
usage="%(prog)s [options] FILE",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--with-source", "-s", action="store_true",
|
||||
help="Show the parsed source structure")
|
||||
parser.add_argument("--with-ast", "-a", action="store_true",
|
||||
help="Show the generated AST")
|
||||
parser.add_argument("--without-python", "-np", action="store_true",
|
||||
help="Do not show the python code generated from the AST")
|
||||
parser.add_argument('args', nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
|
||||
|
||||
options = parser.parse_args(sys.argv[1:])
|
||||
|
||||
if options.with_source:
|
||||
hst = import_file_to_hst(options.args[0])
|
||||
print(str(hst).encode("utf-8"))
|
||||
print()
|
||||
print()
|
||||
|
||||
_ast = import_file_to_ast(options.args[0], module_name)
|
||||
if options.with_ast:
|
||||
print(astor.dump(_ast).encode("utf-8"))
|
||||
print()
|
||||
print()
|
||||
|
||||
if not options.without_python:
|
||||
print(astor.codegen.to_source(_ast).encode("utf-8"))
|
@ -96,7 +96,13 @@ pygments_style = 'sphinx'
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
try:
|
||||
import sphinx_rtd_theme
|
||||
except ImportError:
|
||||
html_theme = 'default'
|
||||
else:
|
||||
html_theme = 'sphinx_rtd_theme'
|
||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
|
@ -48,7 +48,7 @@ Usage: ``(ap-each-while list pred body)``
|
||||
Evaluate the form for each element where the predicate form returns
|
||||
True.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (ap-each-while [1 2 3 4 5 6] (< it 4) (print it))
|
||||
1
|
||||
@ -66,7 +66,7 @@ The anaphoric form of map works just like regular map except that
|
||||
instead of a function object it takes a Hy form. The special name,
|
||||
``it`` is bound to the current object from the list in the iteration.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (ap-map (* it 2) [1 2 3]))
|
||||
[2, 4, 6]
|
||||
@ -82,7 +82,7 @@ Usage: ``(ap-map-when predfn rep list)``
|
||||
Evaluate a mapping over the list using a predicate function to
|
||||
determin when to apply the form.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (ap-map-when odd? (* it 2) [1 2 3 4]))
|
||||
[2, 2, 6, 4]
|
||||
@ -102,7 +102,7 @@ As with ``ap-map`` we take a special form instead of a function to
|
||||
filter the elements of the list. The special name ``it`` is bound to
|
||||
the current element in the iteration.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (ap-filter (> (* it 2) 6) [1 2 3 4 5]))
|
||||
[4, 5]
|
||||
@ -119,7 +119,7 @@ This function does the opposite of ``ap-filter``, it rejects the
|
||||
elements passing the predicate . The special name ``it`` is bound to
|
||||
the current element in the iteration.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (ap-reject (> (* it 2) 6) [1 2 3 4 5]))
|
||||
[1, 2, 3]
|
||||
@ -135,7 +135,7 @@ Usage ``(ap-dotimes n body)``
|
||||
This function evaluates the body *n* times, with the special
|
||||
variable ``it`` bound from *0* to *1-n*. It is useful for side-effects.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (setv n [])
|
||||
=> (ap-dotimes 3 (.append n it))
|
||||
@ -154,7 +154,7 @@ This function returns the first element that passes the predicate or
|
||||
``None``, with the special variable ``it`` bound to the current element in
|
||||
iteration.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=>(ap-first (> it 5) (range 10))
|
||||
6
|
||||
@ -171,7 +171,7 @@ This function returns the last element that passes the predicate or
|
||||
``None``, with the special variable ``it`` bound to the current element in
|
||||
iteration.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=>(ap-last (> it 5) (range 10))
|
||||
9
|
||||
@ -191,7 +191,7 @@ supplied so the function will be applied to initial value and the
|
||||
first element instead. This exposes the element being iterated as
|
||||
``it`` and the current accumulated value as ``acc``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=>(ap-reduce (+ it acc) (range 10))
|
||||
45
|
||||
|
@ -2,7 +2,7 @@
|
||||
loop/recur
|
||||
==========
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
The loop/recur macro gives programmers a simple way to use tail-call
|
||||
optimization (TCO) in their Hy code.
|
||||
@ -43,7 +43,7 @@ Usage: `(loop bindings &rest body)`
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(require hy.contrib.loop)
|
||||
|
||||
|
@ -2,7 +2,7 @@
|
||||
defmulti
|
||||
========
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
`defmulti` lets you arity-overload a function by the given number of
|
||||
args and/or kwargs. Inspired by clojures take on `defn`.
|
||||
|
@ -92,6 +92,12 @@ Write docs---docs are good! Even this doc!
|
||||
Core Development Rules
|
||||
======================
|
||||
|
||||
Pull requests are good!
|
||||
|
||||
Before you submit a PR, please run the tests and check your code against the style guide. You can do both these things at once::
|
||||
|
||||
$ make d
|
||||
|
||||
All incoming changes need to be acked by 2 different members of Hylang's
|
||||
core team. Additional review is clearly welcome, but we need a minimum of
|
||||
2 signoffs for any change.
|
||||
|
@ -43,7 +43,7 @@ behavior that's slightly unexpected in some situations.
|
||||
.
|
||||
-
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
|
||||
`.` is used to perform attribute access on objects. It uses a small DSL
|
||||
@ -151,20 +151,14 @@ case the first false value will be returned. Examples of usage:
|
||||
=> (and True [] False True)
|
||||
[]
|
||||
|
||||
.. note:: `and` shortcuts and stops evaluating parameters as soon as the first
|
||||
false is encountered. However, in the current implementation of Hy
|
||||
statements are executed as soon as they are converted to expressions.
|
||||
The following two examples demonstrates the difference.
|
||||
.. note::
|
||||
|
||||
`and` shortcuts and stops evaluating parameters as soon as the first
|
||||
false is encountered.
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (and False (print "hello"))
|
||||
hello
|
||||
False
|
||||
|
||||
=> (defn side-effects [x] (print "I can has" x) x)
|
||||
=> (and (side-effects false) (side-effects 42))
|
||||
I can has False
|
||||
False
|
||||
|
||||
|
||||
@ -277,6 +271,21 @@ however is called only for every other value in the list.
|
||||
(side-effect2 x)))
|
||||
|
||||
|
||||
dict-comp
|
||||
---------
|
||||
|
||||
`dict-comp` is used to create dictionaries. It takes three or four parameters.
|
||||
The first two parameters are for controlling the return value
|
||||
(key-value pair), while the third is used to select items from a sequence. The
|
||||
fourth and optional parameter can be used to filter out some of the items in
|
||||
the sequence based on a conditional expression.
|
||||
|
||||
.. code-block:: hy
|
||||
|
||||
=> (dict-comp x (* x 2) [x (range 10)] (odd? x))
|
||||
{1: 2, 3: 6, 9: 18, 5: 10, 7: 14}
|
||||
|
||||
|
||||
do / progn
|
||||
----------
|
||||
|
||||
@ -398,7 +407,7 @@ Parameters may have following keywords in front of them:
|
||||
=> (defn print-parameters [&kwargs kwargs]
|
||||
... (for [(, k v) (.items kwargs)] (print k v)))
|
||||
|
||||
=> (kwapply (print-parameters) {"parameter-1" 1 "parameter-2" 2})
|
||||
=> (apply print-parameters [] {"parameter-1" 1 "parameter-2" 2})
|
||||
parameter-2 2
|
||||
parameter-1 1
|
||||
|
||||
@ -429,7 +438,7 @@ Parameters may have following keywords in front of them:
|
||||
defn-alias / defun-alias
|
||||
------------------------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
The `defn-alias` and `defun-alias` macros are much like `defn`_ above,
|
||||
with the difference that instead of defining a function with a single
|
||||
@ -447,6 +456,44 @@ symbols for function names as the first parameter, `defn-alias` and
|
||||
=> (alias)
|
||||
"Hello!"
|
||||
|
||||
|
||||
defmain
|
||||
-------
|
||||
|
||||
.. versionadded:: 0.10.1
|
||||
|
||||
The `defmain` macro defines a main function that is immediately called
|
||||
with sys.argv as arguments if and only if this file is being executed
|
||||
as a script. In other words this:
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
(defmain [&rest args]
|
||||
(do-something-with args))
|
||||
|
||||
is the equivalent of::
|
||||
|
||||
def main(*args):
|
||||
do_something_with(args)
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
retval = main(*sys.arg)
|
||||
|
||||
if isinstance(retval, int):
|
||||
sys.exit(retval)
|
||||
|
||||
Note, as you can see above, if you return an integer from this
|
||||
function, this will be used as the exit status for your script.
|
||||
(Python defaults to exit status 0 otherwise, which means everything's
|
||||
okay!)
|
||||
|
||||
(Since (sys.exit 0) is not run explicitly in case of a non-integer
|
||||
return from defmain, it's good to put (defmain) as the last bit of
|
||||
code in your file.)
|
||||
|
||||
|
||||
.. _defmacro:
|
||||
|
||||
defmacro
|
||||
@ -635,6 +682,24 @@ normally. If the execution is halted with `break`, the `else` does not execute.
|
||||
loop finished
|
||||
|
||||
|
||||
genexpr
|
||||
-------
|
||||
|
||||
`genexpr` is used to create generator expressions. It takes two or three parameters.
|
||||
The first parameter is the expression controlling the return value, while
|
||||
the second is used to select items from a list. The third and optional
|
||||
parameter can be used to filter out some of the items in the list based on a
|
||||
conditional expression. `genexpr` is similar to `list-comp`, except that it returns
|
||||
an iterable that evaluates values one by one instead of evaluating them immediately.
|
||||
|
||||
.. code-block:: hy
|
||||
|
||||
=> (def collection (range 10))
|
||||
=> (def filtered (genexpr x [x collection] (even? x)))
|
||||
=> (list filtered)
|
||||
[0, 2, 4, 6, 8]
|
||||
|
||||
|
||||
.. _gensym:
|
||||
|
||||
gensym
|
||||
@ -711,7 +776,7 @@ the `if` form is used to conditionally select code to be executed. It has to
|
||||
contain the condition block and the block to be executed if the condition
|
||||
evaluates `True`. Optionally it may contain a block that is executed in case
|
||||
the evaluation of the condition is `False`. The `if-not` form (*new in
|
||||
0.9.13*) is similar, but the first block after the test will be
|
||||
0.10.0*) is similar, but the first block after the test will be
|
||||
executed when the test fails, while the other, conditional one, when
|
||||
the test succeeds - opposite of the order of the `if` form.
|
||||
|
||||
@ -732,6 +797,36 @@ any numeric type, empty sequence and empty dictionary are considered `False`.
|
||||
Everything else is considered `True`.
|
||||
|
||||
|
||||
lisp-if / lif
|
||||
-------------
|
||||
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
For those that prefer a more lisp-y if clause, we have lisp-if, or lif. This
|
||||
*only* considers None/nil as false! All other values of python
|
||||
"falseiness" are considered true.
|
||||
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (lisp-if True "true" "false")
|
||||
"true"
|
||||
=> (lisp-if False "true" "false")
|
||||
"true"
|
||||
=> (lisp-if 0 "true" "false")
|
||||
"true"
|
||||
=> (lisp-if nil "true" "false")
|
||||
"false"
|
||||
=> (lisp-if None "true" "false")
|
||||
"false"
|
||||
|
||||
; And, same thing
|
||||
=> (lif True "true" "false")
|
||||
"true"
|
||||
=> (lif nil "true" "false")
|
||||
"false"
|
||||
|
||||
|
||||
import
|
||||
------
|
||||
|
||||
@ -766,32 +861,6 @@ of import you can use.
|
||||
(import [sys [*]])
|
||||
|
||||
|
||||
kwapply
|
||||
-------
|
||||
|
||||
`kwapply` can be used to supply keyword arguments to a function.
|
||||
|
||||
For example:
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (defn rent-car [&kwargs kwargs]
|
||||
... (cond [(in :brand kwargs) (print "brand:" (:brand kwargs))]
|
||||
... [(in :model kwargs) (print "model:" (:model kwargs))]))
|
||||
|
||||
=> (kwapply (rent-car) {:model "T-Model"})
|
||||
model: T-Model
|
||||
|
||||
=> (defn total-purchase [price amount &optional [fees 1.05] [vat 1.1]]
|
||||
... (* price amount fees vat))
|
||||
|
||||
=> (total-purchase 10 15)
|
||||
173.25
|
||||
|
||||
=> (kwapply (total-purchase 10 15) {"vat" 1.05})
|
||||
165.375
|
||||
|
||||
|
||||
lambda / fn
|
||||
-----------
|
||||
|
||||
@ -818,11 +887,15 @@ Just as in normal function definitions, if the first element of the
|
||||
body is a string, it serves as docstring. This is useful for giving
|
||||
class methods docstrings.
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (setv times-three
|
||||
... (fn [x]
|
||||
... "Multiplies input by three and returns the result."
|
||||
... (* x 3)))
|
||||
|
||||
Then test it via the Python built-in ``help`` function::
|
||||
|
||||
=> (help times-three)
|
||||
Help on function times_three:
|
||||
|
||||
@ -919,21 +992,13 @@ parameter will be returned.
|
||||
1
|
||||
|
||||
.. note:: `or` shortcuts and stops evaluating parameters as soon as the first
|
||||
true is encountered. However, in the current implementation of Hy
|
||||
statements are executed as soon as they are converted to expressions.
|
||||
The following two examples demonstrates the difference.
|
||||
true is encountered.
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (or True (print "hello"))
|
||||
hello
|
||||
True
|
||||
|
||||
=> (defn side-effects [x] (print "I can has" x) x)
|
||||
=> (or (side-effects 42) (side-effects False))
|
||||
I can has 42
|
||||
42
|
||||
|
||||
|
||||
print
|
||||
-----
|
||||
@ -1009,6 +1074,22 @@ element:
|
||||
[1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
||||
|
||||
set-comp
|
||||
--------
|
||||
|
||||
`set-comp` is used to create sets. It takes two or three parameters.
|
||||
The first parameter is for controlling the return value, while the second is
|
||||
used to select items from a sequence. The third and optional parameter can be
|
||||
used to filter out some of the items in the sequence based on a conditional
|
||||
expression.
|
||||
|
||||
.. code-block:: hy
|
||||
|
||||
=> (setv data [1 2 3 4 5 2 3 4 5 3 4 5])
|
||||
=> (set-comp x [x data] (odd? x))
|
||||
{1, 3, 5}
|
||||
|
||||
|
||||
slice
|
||||
-----
|
||||
|
||||
@ -1220,14 +1301,14 @@ with-gensyms
|
||||
`with-gensym` form is used to generate a set of :ref:`gensym` for use
|
||||
in a macro.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(with-gensyms [a b c]
|
||||
...)
|
||||
|
||||
expands to:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(let [[a (gensym)
|
||||
[b (gensym)
|
||||
@ -1267,23 +1348,15 @@ infinite series without consuming infinite amount of memory.
|
||||
=> (list-comp x [x (take 15 (random-numbers 1 50))])])
|
||||
[7, 41, 6, 22, 32, 17, 5, 38, 18, 38, 17, 14, 23, 23, 19]
|
||||
|
||||
.. _zipwith:
|
||||
|
||||
zipwith
|
||||
-------
|
||||
yield-from
|
||||
----------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
|
||||
`zipwith` zips multiple lists and maps the given function over the result. It is
|
||||
equilavent to calling ``zip``, followed by calling ``map`` on the result.
|
||||
**PYTHON 3.3 AND UP ONLY!**
|
||||
|
||||
In the following example, `zipwith` is used to add the contents of two lists
|
||||
together. The equilavent ``map`` and ``zip`` calls follow.
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
=> (import operator.add)
|
||||
=> (zipwith operator.add [1 2 3] [4 5 6]) ; using zipwith
|
||||
[5, 7, 9]
|
||||
=> (map operator.add (zip [1 2 3] [4 5 6])) ; using map+zip
|
||||
[5, 7, 9]
|
||||
`yield-from` is used to call a subgenerator. This is useful if you
|
||||
want your coroutine to be able to delegate its processes to another
|
||||
coroutine, say if using something fancy like
|
||||
`asyncio <http://docs.python.org/3.4/library/asyncio.html>`_.
|
||||
|
@ -2,6 +2,8 @@
|
||||
Command Line Interface
|
||||
======================
|
||||
|
||||
.. _hy:
|
||||
|
||||
hy
|
||||
--
|
||||
|
||||
@ -46,6 +48,8 @@ Command line options
|
||||
Print the Hy version number and exit.
|
||||
|
||||
|
||||
.. _hyc:
|
||||
|
||||
hyc
|
||||
---
|
||||
|
||||
@ -57,7 +61,7 @@ Command line options
|
||||
Compile Hy code to Python bytecode. For example, save the
|
||||
following code as ``hyname.hy``:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defn hy-hy [name]
|
||||
(print (+ "Hy " name "!")))
|
||||
@ -71,3 +75,29 @@ Command line options
|
||||
$ hyc hyname.hy
|
||||
$ python hyname.pyc
|
||||
Hy Afroman!
|
||||
|
||||
|
||||
.. _hy2py:
|
||||
|
||||
hy2py
|
||||
-----
|
||||
|
||||
.. versionadded:: 0.10.1
|
||||
|
||||
Command line options
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. cmdoption:: -s
|
||||
--with-source
|
||||
|
||||
Show the parsed source structure.
|
||||
|
||||
.. cmdoption:: -a
|
||||
--with-ast
|
||||
|
||||
Show the generated AST.
|
||||
|
||||
.. cmdoption:: -np
|
||||
--without-python
|
||||
|
||||
Do not show the Python code generated from the AST.
|
||||
|
@ -11,13 +11,13 @@ Core Functions
|
||||
coll?
|
||||
-----
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(coll? x)``
|
||||
|
||||
Returns true if argument is iterable and not a string.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (coll? [1 2 3 4])
|
||||
True
|
||||
@ -32,13 +32,13 @@ Returns true if argument is iterable and not a string.
|
||||
cons
|
||||
----
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(cons a b)``
|
||||
|
||||
Returns a fresh :ref:`cons cell <hycons>` with car `a` and cdr `b`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (setv a (cons 'hd 'tl))
|
||||
|
||||
@ -52,13 +52,13 @@ Returns a fresh :ref:`cons cell <hycons>` with car `a` and cdr `b`.
|
||||
cons?
|
||||
-----
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(cons? foo)``
|
||||
|
||||
Checks whether ``foo`` is a :ref:`cons cell <hycons>`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (setv a (cons 'hd 'tl))
|
||||
|
||||
@ -82,7 +82,7 @@ Return one less than x. Equivalent to ``(- x 1)``.
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (dec 3)
|
||||
2
|
||||
@ -99,14 +99,14 @@ Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
disassemble
|
||||
-----------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(disassemble tree &optional [codegen false])``
|
||||
|
||||
Dump the Python AST for given Hy ``tree`` to standard output. If *codegen*
|
||||
is ``true`` function prints Python code instead.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (disassemble '(print "Hello World!"))
|
||||
Module(
|
||||
@ -126,7 +126,7 @@ Usage: ``(empty? coll)``
|
||||
|
||||
Return True if ``coll`` is empty, i.e. ``(= 0 (len coll))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (empty? [])
|
||||
True
|
||||
@ -143,13 +143,13 @@ Return True if ``coll`` is empty, i.e. ``(= 0 (len coll))``.
|
||||
every?
|
||||
------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(every? pred coll)``
|
||||
|
||||
Return True if ``(pred x)`` is logical true for every ``x`` in ``coll``, otherwise False. Return True if ``coll`` is empty.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (every? even? [2 4 6])
|
||||
True
|
||||
@ -173,7 +173,7 @@ Usage: ``(float? x)``
|
||||
|
||||
Return True if x is a float.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (float? 3.2)
|
||||
True
|
||||
@ -193,7 +193,7 @@ Return True if x is even.
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (even? 2)
|
||||
True
|
||||
@ -214,7 +214,7 @@ Usage: ``(identity x)``
|
||||
|
||||
Returns argument supplied to the function
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (identity 4)
|
||||
4
|
||||
@ -234,7 +234,7 @@ Return one more than x. Equivalent to ``(+ x 1)``.
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (inc 3)
|
||||
4
|
||||
@ -255,7 +255,7 @@ Usage: ``(instance? CLASS x)``
|
||||
|
||||
Return True if x is an instance of CLASS.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (instance? float 1.0)
|
||||
True
|
||||
@ -281,7 +281,7 @@ Usage: ``(integer? x)``
|
||||
Return True if x is an integer. For Python 2, this is
|
||||
either ``int`` or ``long``. For Python 3, this is ``int``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (integer? 3)
|
||||
True
|
||||
@ -300,7 +300,7 @@ Usage: ``(iterable? x)``
|
||||
Return True if x is iterable. Iterable objects return a new iterator
|
||||
when ``(iter x)`` is called. Contrast with :ref:`iterator?-fn`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> ;; works for strings
|
||||
=> (iterable? (str "abcde"))
|
||||
@ -334,7 +334,7 @@ Return True if x is an iterator. Iterators are objects that return
|
||||
themselves as an iterator when ``(iter x)`` is called.
|
||||
Contrast with :ref:`iterable?-fn`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> ;; doesn't work for a list
|
||||
=> (iterator? [1 2 3 4 5])
|
||||
@ -360,7 +360,7 @@ Usage: ``(list* head &rest tail)``
|
||||
Generate a chain of nested cons cells (a dotted list) containing the
|
||||
arguments. If the argument list only has one element, return it.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list* 1 2 3 4)
|
||||
(1 2 3 . 4)
|
||||
@ -379,13 +379,13 @@ arguments. If the argument list only has one element, return it.
|
||||
macroexpand
|
||||
-----------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(macroexpand form)``
|
||||
|
||||
Returns the full macro expansion of form.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (macroexpand '(-> (a b) (x y)))
|
||||
(u'x' (u'a' u'b') u'y')
|
||||
@ -398,13 +398,13 @@ Returns the full macro expansion of form.
|
||||
macroexpand-1
|
||||
-------------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(macroexpand-1 form)``
|
||||
|
||||
Returns the single step macro expansion of form.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (macroexpand-1 '(-> (a b) (-> (c d) (e f))))
|
||||
(u'_>' (u'a' u'b') (u'c' u'd') (u'e' u'f'))
|
||||
@ -420,7 +420,7 @@ Return True if x is less than zero (0).
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (neg? -2)
|
||||
True
|
||||
@ -441,7 +441,7 @@ Usage: ``(nil? x)``
|
||||
|
||||
Return True if x is nil/None.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (nil? nil)
|
||||
True
|
||||
@ -470,7 +470,7 @@ Usage: ``(none? x)``
|
||||
|
||||
Return True if x is None.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (none? None)
|
||||
True
|
||||
@ -495,10 +495,10 @@ nth
|
||||
Usage: ``(nth coll n)``
|
||||
|
||||
Return the `nth` item in a collection, counting from 0. Unlike
|
||||
``get``, ``nth`` works on both iterators and iterables. Returns ``None``
|
||||
if the `n` is outside the range of `coll`.
|
||||
``get``, ``nth`` works on both iterators and iterables. Raises ``IndexError``
|
||||
if the `n` is outside the range of ``coll`` or ``ValueError`` if it's negative.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (nth [1 2 4 7] 1)
|
||||
2
|
||||
@ -506,8 +506,10 @@ if the `n` is outside the range of `coll`.
|
||||
=> (nth [1 2 4 7] 3)
|
||||
7
|
||||
|
||||
=> (none? (nth [1 2 4 7] 5))
|
||||
True
|
||||
=> (nth [1 2 4 7] 5)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
IndexError: 5
|
||||
|
||||
=> (nth (take 3 (drop 2 [1 2 3 4 5 6])) 2))
|
||||
5
|
||||
@ -522,7 +524,7 @@ Usage: ``(numeric? x)``
|
||||
Return True if x is a numeric, as defined in the Python
|
||||
numbers module class ``numbers.Number``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (numeric? -2)
|
||||
True
|
||||
@ -545,7 +547,7 @@ Return True if x is odd.
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (odd? 13)
|
||||
True
|
||||
@ -568,7 +570,7 @@ Return True if x is greater than zero (0).
|
||||
|
||||
Raises ``TypeError`` if ``(not (numeric? x))``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (pos? 3)
|
||||
True
|
||||
@ -590,7 +592,7 @@ Usage: ``(second coll)``
|
||||
Return the second member of ``coll``. Equivalent to
|
||||
``(get coll 1)``
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (second [0 1 2])
|
||||
1
|
||||
@ -601,13 +603,13 @@ Return the second member of ``coll``. Equivalent to
|
||||
some
|
||||
----
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
.. versionadded:: 0.10.0
|
||||
|
||||
Usage: ``(some pred coll)``
|
||||
|
||||
Return True if ``(pred x)`` is logical true for any ``x`` in ``coll``, otherwise False. Return False if ``coll`` is empty.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (some even? [2 4 6])
|
||||
True
|
||||
@ -631,7 +633,7 @@ Usage: ``(string? x)``
|
||||
|
||||
Return True if x is a string.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (string? "foo")
|
||||
True
|
||||
@ -648,7 +650,7 @@ Usage: ``(zero? x)``
|
||||
|
||||
Return True if x is zero (0).
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (zero? 3)
|
||||
False
|
||||
@ -671,7 +673,7 @@ iterator.
|
||||
We can use the canonical infinite Fibonacci number generator
|
||||
as an example of how to use some of these functions.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defn fib []
|
||||
(setv a 0)
|
||||
@ -683,7 +685,7 @@ as an example of how to use some of these functions.
|
||||
|
||||
Note the ``(while true ...)`` loop. If we run this in the REPL,
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (fib)
|
||||
<generator object fib at 0x101e642d0>
|
||||
@ -694,7 +696,7 @@ work until we consume it. Trying something like this is not recommend as
|
||||
the infinite loop will run until it consumes all available RAM, or
|
||||
in this case until I killed it.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (fib))
|
||||
[1] 91474 killed hy
|
||||
@ -703,7 +705,7 @@ in this case until I killed it.
|
||||
To get the first 10 Fibonacci numbers, use :ref:`take-fn`. Note that
|
||||
:ref:`take-fn` also returns a generator, so I create a list from it.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take 10 (fib)))
|
||||
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
||||
@ -711,7 +713,7 @@ To get the first 10 Fibonacci numbers, use :ref:`take-fn`. Note that
|
||||
|
||||
To get the Fibonacci number at index 9, (starting from 0):
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (nth (fib) 9)
|
||||
34
|
||||
@ -744,7 +746,7 @@ Usage: ``(distinct coll)``
|
||||
|
||||
Returns an iterator containing only the unique members in ``coll``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (distinct [ 1 2 3 4 3 5 2 ]))
|
||||
[1, 2, 3, 4, 5]
|
||||
@ -764,8 +766,9 @@ drop
|
||||
Usage: ``(drop n coll)``
|
||||
|
||||
Return an iterator, skipping the first ``n`` members of ``coll``
|
||||
Raises ``ValueError`` if ``n`` is negative.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (drop 2 [1 2 3 4 5]))
|
||||
[3, 4, 5]
|
||||
@ -789,7 +792,7 @@ Usage: ``(drop-while pred coll)``
|
||||
Return an iterator, skipping members of ``coll`` until ``pred``
|
||||
is False.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (drop-while even? [2 4 7 8 9]))
|
||||
[7, 8, 9]
|
||||
@ -812,7 +815,7 @@ Return an iterator for all items in ``coll`` that pass the predicate ``pred``.
|
||||
|
||||
See also :ref:`remove-fn`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (filter pos? [1 2 3 -4 5 -7]))
|
||||
[1, 2, 3, 5]
|
||||
@ -832,7 +835,7 @@ Usage: ``(flatten coll)``
|
||||
Return a single list of all the items in ``coll``, by flattening all
|
||||
contained lists and/or tuples.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (flatten [1 2 [3 4] 5])
|
||||
[1, 2, 3, 4, 5]
|
||||
@ -850,7 +853,7 @@ Usage: ``(iterate fn x)``
|
||||
|
||||
Return an iterator of `x`, `fn(x)`, `fn(fn(x))`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take 5 (iterate inc 5)))
|
||||
[5, 6, 7, 8, 9]
|
||||
@ -871,7 +874,7 @@ predicate, ``pred``, removed.
|
||||
|
||||
See also :ref:`filter-fn`.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (remove odd? [1 2 3 4 5 6 7]))
|
||||
[2, 4, 6]
|
||||
@ -893,7 +896,7 @@ Usage: ``(repeat x)``
|
||||
|
||||
Return an iterator (infinite) of ``x``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take 6 (repeat "s")))
|
||||
[u's', u's', u's', u's', u's', u's']
|
||||
@ -908,7 +911,7 @@ Usage: ``(repeatedly fn)``
|
||||
|
||||
Return an iterator by calling ``fn`` repeatedly.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (import [random [randint]])
|
||||
|
||||
@ -924,8 +927,9 @@ take
|
||||
Usage: ``(take n coll)``
|
||||
|
||||
Return an iterator containing the first ``n`` members of ``coll``.
|
||||
Raises ``ValueError`` if ``n`` is negative.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take 3 [1 2 3 4 5]))
|
||||
[1, 2, 3]
|
||||
@ -945,7 +949,7 @@ Usage: ``(take-nth n coll)``
|
||||
|
||||
Return an iterator containing every ``nth`` member of ``coll``.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take-nth 2 [1 2 3 4 5 6 7]))
|
||||
[1, 3, 5, 7]
|
||||
@ -969,7 +973,7 @@ Usage: ``(take-while pred coll)``
|
||||
|
||||
Return an iterator from ``coll`` as long as predicate, ``pred`` returns True.
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
=> (list (take-while pos? [ 1 2 3 -4 5]))
|
||||
[1, 2, 3]
|
||||
@ -979,3 +983,21 @@ Return an iterator from ``coll`` as long as predicate, ``pred`` returns True.
|
||||
|
||||
=> (list (take-while neg? [ 1 2 3 -4 5]))
|
||||
[]
|
||||
|
||||
.. _zipwith:
|
||||
|
||||
zipwith
|
||||
-------
|
||||
|
||||
.. versionadded:: 0.9.13
|
||||
|
||||
Usage: ``(zipwith fn coll ...)``
|
||||
|
||||
Equivalent to ``zip``, but uses a multi-argument function instead of creating a tuple.
|
||||
If ``zipwith`` is called with N collections, then ``fn`` must accept N arguments.
|
||||
|
||||
.. code-block:: clojure
|
||||
|
||||
=> (import operator)
|
||||
=> (list (zipwith operator.add [1 2 3] [4 5 6]))
|
||||
[5, 7, 9]
|
||||
|
@ -84,7 +84,7 @@ In the input stream, double-quoted strings, respecting the Python
|
||||
notation for strings, are parsed as a single token, which is directly
|
||||
parsed as a :ref:`HyString`.
|
||||
|
||||
An ininterrupted string of characters, excluding spaces, brackets,
|
||||
An uninterrupted string of characters, excluding spaces, brackets,
|
||||
quotes, double-quotes and comments, is parsed as an identifier.
|
||||
|
||||
Identifiers are resolved to atomic models during the parsing phase in
|
||||
@ -231,14 +231,14 @@ from source to runtime.
|
||||
Steps 1 and 2: Tokenizing and parsing
|
||||
-------------------------------------
|
||||
|
||||
The first stage of compiling hy is to lex the source into tokens that we can
|
||||
The first stage of compiling Hy is to lex the source into tokens that we can
|
||||
deal with. We use a project called rply, which is a really nice (and fast)
|
||||
parser, written in a subset of Python called rpython.
|
||||
|
||||
The lexing code is all defined in ``hy.lex.lexer``. This code is mostly just
|
||||
defining the Hy grammer, and all the actual hard parts are taken care of by
|
||||
rply -- we just define "callbacks" for rply in ``hy.lex.parser``, which take
|
||||
the tokens generated, and return the Hy models.
|
||||
defining the Hy grammar, and all the actual hard parts are taken care of by
|
||||
rply -- we just define "callbacks" for rply in ``hy.lex.parser``, which takes
|
||||
the tokens generated, and returns the Hy models.
|
||||
|
||||
You can think of the Hy models as the "AST" for Hy, it's what Macros operate
|
||||
on (directly), and it's what the compiler uses when it compiles Hy down.
|
||||
@ -389,7 +389,7 @@ expression is positive, zero or negative.
|
||||
|
||||
A first pass might be someting like:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defmacro nif [expr pos-form zero-form neg-form]
|
||||
`(let [[obscure-name ~expr]]
|
||||
@ -404,7 +404,7 @@ this is no guarantee.
|
||||
The method :ref:`gensym` is designed to generate a new, unique symbol for just
|
||||
such an occasion. A much better version of ``nif`` would be:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defmacro nif [expr pos-form zero-form neg-form]
|
||||
(let [[g (gensym)]]
|
||||
@ -417,14 +417,14 @@ This is an easy case, since there is only one symbol. But if there is
|
||||
a need for several gensym's there is a second macro :ref:`with-gensyms` that
|
||||
basically expands to a series of ``let`` statements:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(with-gensyms [a b c]
|
||||
...)
|
||||
|
||||
expands to:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(let [[a (gensym)
|
||||
[b (gensym)
|
||||
@ -433,7 +433,7 @@ expands to:
|
||||
|
||||
so our re-written ``nif`` would look like:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defmacro nif [expr pos-form zero-form neg-form]
|
||||
(with-gensyms [g]
|
||||
@ -448,7 +448,7 @@ remainder of the symbol. So ``g!a`` would become ``(gensym "a")``.
|
||||
|
||||
Our final version of ``nif``, built with ``defmacro/g!`` becomes:
|
||||
|
||||
.. code-block:: clojure
|
||||
.. code-block:: hy
|
||||
|
||||
(defmacro/g! nif [expr pos-form zero-form neg-form]
|
||||
`(let [[~g!res ~expr]]
|
||||
|
242
docs/make.bat
Normal file
242
docs/make.bat
Normal file
@ -0,0 +1,242 @@
|
||||
@ECHO OFF
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set BUILDDIR=_build
|
||||
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
|
||||
set I18NSPHINXOPTS=%SPHINXOPTS% .
|
||||
if NOT "%PAPER%" == "" (
|
||||
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
|
||||
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
if "%1" == "help" (
|
||||
:help
|
||||
echo.Please use `make ^<target^>` where ^<target^> is one of
|
||||
echo. html to make standalone HTML files
|
||||
echo. dirhtml to make HTML files named index.html in directories
|
||||
echo. singlehtml to make a single large HTML file
|
||||
echo. pickle to make pickle files
|
||||
echo. json to make JSON files
|
||||
echo. htmlhelp to make HTML files and a HTML help project
|
||||
echo. qthelp to make HTML files and a qthelp project
|
||||
echo. devhelp to make HTML files and a Devhelp project
|
||||
echo. epub to make an epub
|
||||
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
|
||||
echo. text to make text files
|
||||
echo. man to make manual pages
|
||||
echo. texinfo to make Texinfo files
|
||||
echo. gettext to make PO message catalogs
|
||||
echo. changes to make an overview over all changed/added/deprecated items
|
||||
echo. xml to make Docutils-native XML files
|
||||
echo. pseudoxml to make pseudoxml-XML files for display purposes
|
||||
echo. linkcheck to check all external links for integrity
|
||||
echo. doctest to run all doctests embedded in the documentation if enabled
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "clean" (
|
||||
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
|
||||
del /q /s %BUILDDIR%\*
|
||||
goto end
|
||||
)
|
||||
|
||||
|
||||
%SPHINXBUILD% 2> nul
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||
echo.may add the Sphinx directory to PATH.
|
||||
echo.
|
||||
echo.If you don't have Sphinx installed, grab it from
|
||||
echo.http://sphinx-doc.org/
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if "%1" == "html" (
|
||||
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "dirhtml" (
|
||||
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "singlehtml" (
|
||||
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pickle" (
|
||||
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the pickle files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "json" (
|
||||
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the JSON files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "htmlhelp" (
|
||||
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run HTML Help Workshop with the ^
|
||||
.hhp project file in %BUILDDIR%/htmlhelp.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "qthelp" (
|
||||
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run "qcollectiongenerator" with the ^
|
||||
.qhcp project file in %BUILDDIR%/qthelp, like this:
|
||||
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\hy.qhcp
|
||||
echo.To view the help file:
|
||||
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\hy.ghc
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "devhelp" (
|
||||
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "epub" (
|
||||
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The epub file is in %BUILDDIR%/epub.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latex" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdf" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdfja" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf-ja
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "text" (
|
||||
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The text files are in %BUILDDIR%/text.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "man" (
|
||||
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The manual pages are in %BUILDDIR%/man.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "texinfo" (
|
||||
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "gettext" (
|
||||
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "changes" (
|
||||
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.The overview file is in %BUILDDIR%/changes.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "linkcheck" (
|
||||
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Link check complete; look for any errors in the above output ^
|
||||
or in %BUILDDIR%/linkcheck/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "doctest" (
|
||||
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Testing of doctests in the sources finished, look at the ^
|
||||
results in %BUILDDIR%/doctest/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "xml" (
|
||||
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The XML files are in %BUILDDIR%/xml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pseudoxml" (
|
||||
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
|
||||
goto end
|
||||
)
|
||||
|
||||
:end
|
@ -181,14 +181,14 @@ for python programmers... now you too can make use of macros'
|
||||
incredible power (just be careful to not aim them footward)!
|
||||
|
||||
|
||||
Hy is python flavored lisp (or vice versa?)
|
||||
===========================================
|
||||
Hy is a Lisp flavored Python
|
||||
============================
|
||||
|
||||
Hy converts to python's own abstract syntax tree, so you'll soon start
|
||||
Hy converts to Python's own abstract syntax tree, so you'll soon start
|
||||
to find that all the familiar power of python is at your fingertips.
|
||||
|
||||
You have full access to python's data types and standard library in
|
||||
hy. Let's experiment with this in the hy interpreter::
|
||||
You have full access to Python's data types and standard library in
|
||||
Hy. Let's experiment with this in the hy interpreter::
|
||||
|
||||
=> [1 2 3]
|
||||
[1, 2, 3]
|
||||
@ -199,14 +199,13 @@ hy. Let's experiment with this in the hy interpreter::
|
||||
=> (, 1 2 3)
|
||||
(1, 2, 3)
|
||||
|
||||
(You may notice that at present, the common lisp method of quoting
|
||||
things like so:
|
||||
If you are familiar with other lisps, you may be interested that Hy
|
||||
supports the Common Lisp method of quoting:
|
||||
|
||||
.. code-block:: clj
|
||||
|
||||
'(1 2 3)
|
||||
|
||||
does not work. Instead, use square brackets as above.)
|
||||
=> '(1 2 3)
|
||||
(1L 2L 3L)
|
||||
|
||||
You also have access to all the builtin types' nice methods::
|
||||
|
||||
@ -397,7 +396,7 @@ The same thing in Hy::
|
||||
[1 2 None 42]
|
||||
=> (optional_arg 1 2 3 4)
|
||||
[1 2 3 4]
|
||||
=> (kwapply (optional_arg)
|
||||
=> (apply optional_arg []
|
||||
... {"keyword1" 1
|
||||
... "pos2" 2
|
||||
... "pos1" 3
|
||||
@ -405,7 +404,7 @@ The same thing in Hy::
|
||||
...
|
||||
[3, 2, 1, 4]
|
||||
|
||||
See how we use kwapply to handle the fancy passing? :)
|
||||
See how we use apply to handle the fancy passing? :)
|
||||
|
||||
There's also a dictionary-style keyword arguments construction that
|
||||
looks like:
|
||||
@ -480,7 +479,7 @@ In Hy:
|
||||
.. code-block:: clj
|
||||
|
||||
(defclass Customer [models.Model]
|
||||
[[name (kwapply (models.CharField) {"max_length" 255})]
|
||||
[[name (apply models.CharField [] {"max_length" 255})]
|
||||
[address (models.TextField)]
|
||||
[notes (models.TextField)]])
|
||||
|
||||
|
12
eg/curry/ski.hy
Normal file
12
eg/curry/ski.hy
Normal file
@ -0,0 +1,12 @@
|
||||
(require hy.contrib.curry)
|
||||
|
||||
|
||||
(defnc s [x y z] ((x z) (y z))) ; λxyz.xz(yz)
|
||||
(defnc k [x] (fn [y] x)) ; λx.λy.x
|
||||
(defnc i [x] x) ;; λx.x
|
||||
|
||||
(defnc succ [n] (+ n 1))
|
||||
|
||||
|
||||
(print (((((s ((((k s) k) i) i)) (i i)) ((i (i i))
|
||||
((((k s) i) ((s (k s)) k)) i))) succ) 0))
|
@ -2,13 +2,16 @@
|
||||
;;; Copyright (c) Paul R. Tagliamonte, 2013, MIT/Expat license.
|
||||
|
||||
|
||||
(import [urllib2 [urlopen]]
|
||||
[lxml [etree]]
|
||||
(import [lxml [etree]]
|
||||
[sys [argv]])
|
||||
|
||||
(try
|
||||
(import [urllib.request [urlopen]])
|
||||
(catch [ImportError]
|
||||
(import [urllib2 [urlopen]])))
|
||||
|
||||
(defn get-rss-feed-name [tumblr]
|
||||
(kwapply (.format "http://{tumblr}.tumblr.com/rss") {"tumblr" tumblr}))
|
||||
(.format "http://{0}.tumblr.com/rss" tumblr))
|
||||
|
||||
(defn get-rss-feed [tumblr]
|
||||
(.parse etree (urlopen (get-rss-feed-name tumblr))))
|
||||
|
@ -12,7 +12,7 @@
|
||||
|
||||
|
||||
(defn get-legislators [state]
|
||||
(kwapply (.legislators openstates) {"state" state}))
|
||||
(apply openstates.legislators [] {"state" state}))
|
||||
|
||||
|
||||
(defn get-party-breakdown [state]
|
||||
|
@ -23,7 +23,7 @@ import imp
|
||||
import sys
|
||||
|
||||
# This just mocks the normalish behavior of the Python interp. Helpful to aid
|
||||
# with shiming existing apps that don't really "work" with Hy.
|
||||
# with shimming existing apps that don't really "work" with Hy.
|
||||
#
|
||||
# You could say this script helps Hyjack a file.
|
||||
#
|
||||
|
@ -25,16 +25,21 @@
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
# DEALINGS IN THE SOFTWARE.
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import argparse
|
||||
import code
|
||||
import ast
|
||||
import sys
|
||||
|
||||
import astor.codegen
|
||||
|
||||
import hy
|
||||
|
||||
from hy.lex import LexException, PrematureEndOfInput, tokenize
|
||||
from hy.compiler import hy_compile, HyTypeError
|
||||
from hy.importer import ast_compile, import_buffer_to_module
|
||||
from hy.importer import (ast_compile, import_buffer_to_module,
|
||||
import_file_to_ast, import_file_to_hst)
|
||||
from hy.completer import completion
|
||||
|
||||
from hy.macros import macro, require
|
||||
@ -66,7 +71,6 @@ builtins.exit = HyQuitter('exit')
|
||||
|
||||
|
||||
def print_python_code(_ast):
|
||||
import astor.codegen
|
||||
# astor cannot handle ast.Interactive, so disguise it as a module
|
||||
_ast_for_print = ast.Module()
|
||||
_ast_for_print.body = _ast.body
|
||||
@ -313,3 +317,43 @@ def hyc_main():
|
||||
sys.stderr.write("hyc: Can't open file '%s': [Errno %d] %s\n" %
|
||||
(x.filename, x.errno, x.strerror))
|
||||
sys.exit(x.errno)
|
||||
|
||||
|
||||
# entry point for cmd line script "hy2py"
|
||||
def hy2py_main():
|
||||
module_name = "<STDIN>"
|
||||
|
||||
options = dict(prog="hy2py", usage="%(prog)s [options] FILE",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser = argparse.ArgumentParser(**options)
|
||||
parser.add_argument("--with-source", "-s", action="store_true",
|
||||
help="Show the parsed source structure")
|
||||
parser.add_argument("--with-ast", "-a", action="store_true",
|
||||
help="Show the generated AST")
|
||||
parser.add_argument("--without-python", "-np", action="store_true",
|
||||
help=("Do not show the Python code generated "
|
||||
"from the AST"))
|
||||
parser.add_argument('args', nargs=argparse.REMAINDER,
|
||||
help=argparse.SUPPRESS)
|
||||
|
||||
options = parser.parse_args(sys.argv[1:])
|
||||
|
||||
if not options.args:
|
||||
parser.exit(1, parser.format_help())
|
||||
|
||||
if options.with_source:
|
||||
hst = import_file_to_hst(options.args[0])
|
||||
print(hst)
|
||||
print()
|
||||
print()
|
||||
|
||||
_ast = import_file_to_ast(options.args[0], module_name)
|
||||
if options.with_ast:
|
||||
print(astor.dump(_ast))
|
||||
print()
|
||||
print()
|
||||
|
||||
if not options.without_python:
|
||||
print(astor.codegen.to_source(_ast))
|
||||
|
||||
parser.exit(0)
|
||||
|
@ -732,25 +732,10 @@ class HyASTCompiler(object):
|
||||
handler_results += self._compile_catch_expression(e, name)
|
||||
handlers.append(handler_results.stmts.pop())
|
||||
elif e[0] == HySymbol("else"):
|
||||
if orelse:
|
||||
raise HyTypeError(
|
||||
e,
|
||||
"`try' cannot have more than one `else'")
|
||||
else:
|
||||
orelse = self._compile_branch(e[1:])
|
||||
# XXX tempvar magic
|
||||
orelse += orelse.expr_as_stmt()
|
||||
orelse = orelse.stmts
|
||||
orelse = self.try_except_helper(e, HySymbol("else"), orelse)
|
||||
elif e[0] == HySymbol("finally"):
|
||||
if finalbody:
|
||||
raise HyTypeError(
|
||||
e,
|
||||
"`try' cannot have more than one `finally'")
|
||||
else:
|
||||
finalbody = self._compile_branch(e[1:])
|
||||
# XXX tempvar magic
|
||||
finalbody += finalbody.expr_as_stmt()
|
||||
finalbody = finalbody.stmts
|
||||
finalbody = self.try_except_helper(e, HySymbol("finally"),
|
||||
finalbody)
|
||||
else:
|
||||
raise HyTypeError(e, "Unknown expression in `try'")
|
||||
|
||||
@ -768,8 +753,8 @@ class HyASTCompiler(object):
|
||||
col_offset=expr.start_column,
|
||||
type=None,
|
||||
name=None,
|
||||
body=[ast.Pass(lineno=expr.start_line,
|
||||
col_offset=expr.start_column)])]
|
||||
body=[ast.Raise(lineno=expr.start_line,
|
||||
col_offset=expr.start_column)])]
|
||||
|
||||
ret = handler_results
|
||||
|
||||
@ -809,6 +794,17 @@ class HyASTCompiler(object):
|
||||
body=body,
|
||||
orelse=orelse) + returnable
|
||||
|
||||
def try_except_helper(self, hy_obj, symbol, accumulated):
|
||||
if accumulated:
|
||||
raise HyTypeError(
|
||||
hy_obj,
|
||||
"`try' cannot have more than one `%s'" % symbol)
|
||||
else:
|
||||
accumulated = self._compile_branch(hy_obj[1:])
|
||||
accumulated += accumulated.expr_as_stmt()
|
||||
accumulated = accumulated.stmts
|
||||
return accumulated
|
||||
|
||||
@builds("except")
|
||||
@builds("catch")
|
||||
def magic_internal_form(self, expr):
|
||||
@ -1017,6 +1013,28 @@ class HyASTCompiler(object):
|
||||
|
||||
return ret
|
||||
|
||||
@builds("yield_from")
|
||||
@checkargs(max=1)
|
||||
def compile_yield_from_expression(self, expr):
|
||||
if not PY33:
|
||||
raise HyCompileError(
|
||||
"yield-from only supported in python 3.3+!")
|
||||
|
||||
expr.pop(0)
|
||||
ret = Result(contains_yield=True)
|
||||
|
||||
value = None
|
||||
if expr != []:
|
||||
ret += self.compile(expr.pop(0))
|
||||
value = ret.force_expr
|
||||
|
||||
ret += ast.YieldFrom(
|
||||
value=value,
|
||||
lineno=expr.start_line,
|
||||
col_offset=expr.start_column)
|
||||
|
||||
return ret
|
||||
|
||||
@builds("import")
|
||||
def compile_import_expression(self, expr):
|
||||
def _compile_import(expr, module, names=None, importer=ast.Import):
|
||||
@ -1494,7 +1512,7 @@ class HyASTCompiler(object):
|
||||
def compile_require(self, expression):
|
||||
"""
|
||||
TODO: keep track of what we've imported in this run and then
|
||||
"unimport" it after we've completed `thing' so that we don't polute
|
||||
"unimport" it after we've completed `thing' so that we don't pollute
|
||||
other envs.
|
||||
"""
|
||||
expression.pop(0)
|
||||
|
20
hy/contrib/curry.hy
Normal file
20
hy/contrib/curry.hy
Normal file
@ -0,0 +1,20 @@
|
||||
(import inspect functools sys)
|
||||
|
||||
|
||||
(defn curry [func]
|
||||
(let [[sig (.getargspec inspect func)]
|
||||
[count (len sig.args)]]
|
||||
|
||||
(fn [&rest args]
|
||||
(if (< (len args) count)
|
||||
(apply functools.partial (+ [(curry func)] (list args)))
|
||||
(apply func args)))))
|
||||
|
||||
|
||||
(defmacro fnc [args &rest body]
|
||||
`(do (import hy.contrib.curry)
|
||||
(with-decorator hy.contrib.curry.curry (fn [~@args] ~@body))))
|
||||
|
||||
|
||||
(defmacro defnc [name args &rest body]
|
||||
`(def ~name (fnc [~@args] ~@body)))
|
@ -3,7 +3,7 @@
|
||||
|
||||
(defmacro route-with-methods [name path methods params &rest code]
|
||||
"Same as route but with an extra methods array to specify HTTP methods"
|
||||
`(let [[deco (kwapply (.route app ~path)
|
||||
`(let [[deco (apply app.route [~path]
|
||||
{"methods" ~methods})]]
|
||||
(with-decorator deco
|
||||
(defn ~name ~params
|
||||
|
@ -46,6 +46,6 @@
|
||||
(.disable ~g!hy-pr)
|
||||
(setv ~g!hy-s (StringIO))
|
||||
(setv ~g!hy-ps
|
||||
(.sort-stats (kwapply (.Stats pstats ~g!hy-pr) {"stream" ~g!hy-s})))
|
||||
(.sort-stats (apply pstats.Stats [~g!hy-pr] {"stream" ~g!hy-s})))
|
||||
(.print-stats ~g!hy-ps)
|
||||
(print (.getvalue ~g!hy-s))))
|
||||
|
@ -23,7 +23,9 @@
|
||||
;;;; to make functional programming slightly easier.
|
||||
;;;;
|
||||
|
||||
|
||||
(import itertools)
|
||||
(import functools)
|
||||
(import collections)
|
||||
(import [hy._compat [long-type]]) ; long for python2, int for python3
|
||||
(import [hy.models.cons [HyCons]])
|
||||
|
||||
@ -34,7 +36,7 @@
|
||||
|
||||
(defn butlast [coll]
|
||||
"Returns coll except of last element."
|
||||
(slice coll 0 (dec (len coll))))
|
||||
(itertools.islice coll 0 (dec (len coll))))
|
||||
|
||||
(defn coll? [coll]
|
||||
"Checks whether item is a collection"
|
||||
@ -48,15 +50,11 @@
|
||||
"Check whether c can be used as a cons object"
|
||||
(instance? HyCons c))
|
||||
|
||||
(defn cycle [coll]
|
||||
"Yield an infinite repetition of the items in coll"
|
||||
(setv seen [])
|
||||
(for* [x coll]
|
||||
(yield x)
|
||||
(.append seen x))
|
||||
(while seen
|
||||
(for* [x seen]
|
||||
(yield x))))
|
||||
(defn keyword? [k]
|
||||
"Check whether k is a keyword"
|
||||
(and (instance? (type :foo) k)
|
||||
(.startswith k (get :foo 0))))
|
||||
|
||||
|
||||
(defn dec [n]
|
||||
"Decrement n by 1"
|
||||
@ -86,22 +84,36 @@
|
||||
(yield val)
|
||||
(.add seen val))))))
|
||||
|
||||
(if-python2
|
||||
(do
|
||||
(setv filterfalse itertools.ifilterfalse)
|
||||
(setv zip_longest itertools.izip_longest)
|
||||
(setv filter itertools.ifilter)
|
||||
(setv map itertools.imap)
|
||||
(setv zip itertools.izip)
|
||||
(setv range xrange)
|
||||
(setv input raw_input))
|
||||
(do
|
||||
(setv reduce functools.reduce)
|
||||
(setv filterfalse itertools.filterfalse)
|
||||
(setv zip_longest itertools.zip_longest)
|
||||
; Someone can import these directly from `hy.core.language`;
|
||||
; we'll make some duplicates.
|
||||
(setv filter filter)
|
||||
(setv map map)
|
||||
(setv zip zip)
|
||||
(setv range range)
|
||||
(setv input input)))
|
||||
|
||||
(setv cycle itertools.cycle)
|
||||
(setv repeat itertools.repeat)
|
||||
(setv drop-while itertools.dropwhile)
|
||||
(setv take-while itertools.takewhile)
|
||||
(setv zipwith map)
|
||||
|
||||
(defn drop [count coll]
|
||||
"Drop `count` elements from `coll` and yield back the rest"
|
||||
(let [[citer (iter coll)]]
|
||||
(try (for* [i (range count)]
|
||||
(next citer))
|
||||
(catch [StopIteration]))
|
||||
citer))
|
||||
|
||||
(defn drop-while [pred coll]
|
||||
"Drop all elements of `coll` until `pred` is False"
|
||||
(let [[citer (iter coll)]]
|
||||
(for* [val citer]
|
||||
(if (not (pred val))
|
||||
(do (yield val) (break))))
|
||||
(for* [val citer]
|
||||
(yield val))))
|
||||
(itertools.islice coll count nil))
|
||||
|
||||
(defn empty? [coll]
|
||||
"Return True if `coll` is empty"
|
||||
@ -118,20 +130,13 @@
|
||||
|
||||
(defn fake-source-positions [tree]
|
||||
"Fake the source positions for a given tree"
|
||||
(if (and (iterable? tree) (not (string? tree)))
|
||||
(if (coll? tree)
|
||||
(for* [subtree tree]
|
||||
(fake-source-positions subtree)))
|
||||
(for* [attr '[start-line end-line start-column end-column]]
|
||||
(if (not (hasattr tree attr))
|
||||
(setattr tree attr 1))))
|
||||
|
||||
(defn filter [pred coll]
|
||||
"Return all elements from `coll` that pass `pred`"
|
||||
(let [[citer (iter coll)]]
|
||||
(for* [val citer]
|
||||
(if (pred val)
|
||||
(yield val)))))
|
||||
|
||||
(defn flatten [coll]
|
||||
"Return a single flat list expanding all members of coll"
|
||||
(if (coll? coll)
|
||||
@ -139,7 +144,7 @@
|
||||
(raise (TypeError (.format "{0!r} is not a collection" coll)))))
|
||||
|
||||
(defn _flatten [coll result]
|
||||
(if (and (iterable? coll) (not (string? coll)))
|
||||
(if (coll? coll)
|
||||
(do (for* [b coll]
|
||||
(_flatten b result)))
|
||||
(.append result coll))
|
||||
@ -173,7 +178,7 @@
|
||||
|
||||
(defn first [coll]
|
||||
"Return first item from `coll`"
|
||||
(get coll 0))
|
||||
(nth coll 0))
|
||||
|
||||
(defn identity [x]
|
||||
"Returns the argument unchanged"
|
||||
@ -198,14 +203,13 @@
|
||||
(defn integer-char? [x]
|
||||
"Return True if char `x` parses as an integer"
|
||||
(try
|
||||
(integer? (int x))
|
||||
(catch [e ValueError] False)
|
||||
(catch [e TypeError] False)))
|
||||
(integer? (int x))
|
||||
(catch [e ValueError] False)
|
||||
(catch [e TypeError] False)))
|
||||
|
||||
(defn iterable? [x]
|
||||
"Return true if x is iterable"
|
||||
(try (do (iter x) true)
|
||||
(catch [Exception] false)))
|
||||
(isinstance x collections.Iterable))
|
||||
|
||||
(defn iterate [f x]
|
||||
(setv val x)
|
||||
@ -215,8 +219,7 @@
|
||||
|
||||
(defn iterator? [x]
|
||||
"Return true if x is an iterator"
|
||||
(try (= x (iter x))
|
||||
(catch [TypeError] false)))
|
||||
(isinstance x collections.Iterator))
|
||||
|
||||
(defn list* [hd &rest tl]
|
||||
"Return a dotted list construed from the elements of the argument"
|
||||
@ -257,13 +260,9 @@
|
||||
|
||||
(defn nth [coll index]
|
||||
"Return nth item in collection or sequence, counting from 0"
|
||||
(if (not (neg? index))
|
||||
(if (iterable? coll)
|
||||
(try (get (list (take 1 (drop index coll))) 0)
|
||||
(catch [IndexError] None))
|
||||
(try (get coll index)
|
||||
(catch [IndexError] None)))
|
||||
None))
|
||||
(try
|
||||
(next (drop index coll))
|
||||
(catch [e StopIteration] (raise (IndexError index)))))
|
||||
|
||||
(defn odd? [n]
|
||||
"Return true if n is an odd number"
|
||||
@ -284,14 +283,7 @@
|
||||
|
||||
(defn rest [coll]
|
||||
"Get all the elements of a coll, except the first."
|
||||
(slice coll 1))
|
||||
|
||||
(defn repeat [x &optional n]
|
||||
"Yield x forever or optionally n times"
|
||||
(if (none? n)
|
||||
(setv dispatch (fn [] (while true (yield x))))
|
||||
(setv dispatch (fn [] (for* [_ (range n)] (yield x)))))
|
||||
(dispatch))
|
||||
(drop 1 coll))
|
||||
|
||||
(defn repeatedly [func]
|
||||
"Yield result of running func repeatedly"
|
||||
@ -300,7 +292,7 @@
|
||||
|
||||
(defn second [coll]
|
||||
"Return second item from `coll`"
|
||||
(get coll 1))
|
||||
(nth coll 1))
|
||||
|
||||
(defn some [pred coll]
|
||||
"Return true if (pred x) is logical true for any x in coll, else false"
|
||||
@ -321,9 +313,7 @@
|
||||
(defn take [count coll]
|
||||
"Take `count` elements from `coll`, or the whole set if the total
|
||||
number of entries in `coll` is less than `count`."
|
||||
(let [[citer (iter coll)]]
|
||||
(for* [_ (range count)]
|
||||
(yield (next citer)))))
|
||||
(itertools.islice coll nil count))
|
||||
|
||||
(defn take-nth [n coll]
|
||||
"Return every nth member of coll
|
||||
@ -336,30 +326,15 @@
|
||||
(next citer))))
|
||||
(raise (ValueError "n must be positive"))))
|
||||
|
||||
(defn take-while [pred coll]
|
||||
"Take all elements while `pred` is true"
|
||||
(let [[citer (iter coll)]]
|
||||
(for* [val citer]
|
||||
(if (pred val)
|
||||
(yield val)
|
||||
(break)))))
|
||||
|
||||
(defn zero? [n]
|
||||
"Return true if n is 0"
|
||||
(_numeric_check n)
|
||||
(= n 0))
|
||||
|
||||
(defn zipwith [func &rest lists]
|
||||
"Zip the contents of several lists and map a function to the result"
|
||||
(do
|
||||
(import functools)
|
||||
(map (functools.partial (fn [f args] (apply f args)) func) (apply zip lists))))
|
||||
|
||||
(def *exports* '[butlast calling-module-name coll? cons cons? cycle dec
|
||||
distinct disassemble drop drop-while empty?
|
||||
even? every? first filter flatten float? gensym
|
||||
identity inc instance? integer integer? integer-char?
|
||||
iterable? iterate iterator? list* macroexpand
|
||||
macroexpand-1 neg? nil? none? nth numeric? odd? pos?
|
||||
remove repeat repeatedly rest second some string
|
||||
string? take take-nth take-while zero? zipwith])
|
||||
(def *exports* '[butlast calling-module-name coll? cons cons? cycle dec distinct
|
||||
disassemble drop drop-while empty? even? every? first filter
|
||||
flatten float? gensym identity inc instance? integer
|
||||
integer? integer-char? iterable? iterate iterator? keyword?
|
||||
list* macroexpand macroexpand-1 map neg? nil? none? nth
|
||||
numeric? odd? pos? range remove repeat repeatedly rest second
|
||||
some string string? take take-nth take-while zero? zip zipwith])
|
||||
|
@ -27,8 +27,8 @@
|
||||
|
||||
|
||||
(import [hy.models.list [HyList]]
|
||||
[hy.models.symbol [HySymbol]])
|
||||
|
||||
[hy.models.symbol [HySymbol]]
|
||||
[hy._compat [PY33 PY34]])
|
||||
|
||||
|
||||
(defmacro for [args &rest body]
|
||||
@ -145,6 +145,11 @@
|
||||
`(if (not ~test) ~not-branch ~yes-branch)))
|
||||
|
||||
|
||||
(defmacro-alias [lisp-if lif] [test &rest branches]
|
||||
"Like `if`, but anything that is not None/nil is considered true."
|
||||
`(if (is-not ~test nil) ~@branches))
|
||||
|
||||
|
||||
(defmacro when [test &rest body]
|
||||
"Execute `body` when `test` is true"
|
||||
`(if ~test (do ~@body)))
|
||||
@ -155,12 +160,6 @@
|
||||
`(if-not ~test (do ~@body)))
|
||||
|
||||
|
||||
(defmacro yield-from [iterable]
|
||||
"Yield all the items from iterable"
|
||||
(let [[x (gensym)]]
|
||||
`(for* [~x ~iterable]
|
||||
(yield ~x))))
|
||||
|
||||
(defmacro with-gensyms [args &rest body]
|
||||
`(let ~(HyList (map (fn [x] `[~x (gensym '~x)]) args))
|
||||
~@body))
|
||||
@ -172,22 +171,18 @@
|
||||
~@body))))
|
||||
|
||||
|
||||
(defmacro kwapply [call kwargs]
|
||||
"Use a dictionary as keyword arguments"
|
||||
(let [[-fun (car call)]
|
||||
[-args (cdr call)]
|
||||
[-okwargs `[(list (.items ~kwargs))]]]
|
||||
(while (= -fun "kwapply") ;; join any further kw
|
||||
(if (not (= (len -args) 2))
|
||||
(macro-error
|
||||
call
|
||||
(.format "Trying to call nested kwapply with {0} args instead of 2"
|
||||
(len -args))))
|
||||
(.insert -okwargs 0 `(list (.items ~(car (cdr -args)))))
|
||||
(setv -fun (car (car -args)))
|
||||
(setv -args (cdr (car -args))))
|
||||
(defmacro defmain [args &rest body]
|
||||
"Write a function named \"main\" and do the if __main__ dance"
|
||||
(let [[retval (gensym)]]
|
||||
`(do
|
||||
(defn main [~@args]
|
||||
~@body)
|
||||
|
||||
`(apply ~-fun [~@-args] (dict (sum ~-okwargs [])))))
|
||||
(when (= --name-- "__main__")
|
||||
(import sys)
|
||||
(setv ~retval (apply main sys.argv))
|
||||
(if (integer? ~retval)
|
||||
(sys.exit ~retval))))))
|
||||
|
||||
|
||||
(defmacro-alias [defn-alias defun-alias] [names lambda-list &rest body]
|
||||
|
@ -21,12 +21,14 @@
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
# DEALINGS IN THE SOFTWARE.
|
||||
|
||||
from hy._compat import PY3
|
||||
|
||||
import traceback
|
||||
|
||||
|
||||
class HyError(Exception):
|
||||
"""
|
||||
Generic Hy error. All interal Exceptions will be subclassed from this
|
||||
Generic Hy error. All internal Exceptions will be subclassed from this
|
||||
Exception.
|
||||
"""
|
||||
pass
|
||||
@ -137,7 +139,10 @@ class HyTypeError(TypeError):
|
||||
(self.__class__.__name__,
|
||||
self.message))
|
||||
|
||||
return result.encode('utf-8')
|
||||
if not PY3:
|
||||
return result.encode('utf-8')
|
||||
else:
|
||||
return result
|
||||
|
||||
|
||||
class HyMacroExpansionError(HyTypeError):
|
||||
|
@ -213,7 +213,7 @@ def reader_macroexpand(char, tree, module_name):
|
||||
"""Expand the reader macro "char" with argument `tree`."""
|
||||
load_macros(module_name)
|
||||
|
||||
if not char in _hy_reader[module_name]:
|
||||
if char not in _hy_reader[module_name]:
|
||||
raise HyTypeError(
|
||||
char,
|
||||
"`{0}' is not a reader macro in module '{1}'".format(
|
||||
|
@ -20,4 +20,4 @@
|
||||
|
||||
|
||||
__appname__ = "hy"
|
||||
__version__ = "0.9.12"
|
||||
__version__ = "0.10.0"
|
||||
|
8
make.bat
8
make.bat
@ -27,7 +27,9 @@ if "%1" == "help" (
|
||||
|
||||
if "%1" == "docs" (
|
||||
:docs
|
||||
echo.docs not yet supported under Windows
|
||||
cd docs
|
||||
make.bat html
|
||||
cd ..
|
||||
goto :EOF
|
||||
)
|
||||
|
||||
@ -70,8 +72,8 @@ goto :EOF
|
||||
|
||||
if "%1" == "flake" (
|
||||
:flake
|
||||
echo.flake8 hy
|
||||
flake8 hy
|
||||
echo.flake8 hy tests
|
||||
flake8 hy tests
|
||||
goto :EOF
|
||||
)
|
||||
|
||||
|
@ -1,5 +1,12 @@
|
||||
-r requirements.txt
|
||||
tox
|
||||
# test tools
|
||||
nose
|
||||
Sphinx
|
||||
tox
|
||||
|
||||
# code quality
|
||||
flake8
|
||||
coverage
|
||||
|
||||
# documentation
|
||||
Pygments>=1.6
|
||||
Sphinx
|
||||
sphinx_rtd_theme
|
||||
|
@ -1,3 +0,0 @@
|
||||
# Check site / dev for more deps!
|
||||
flake8
|
||||
rply>=0.7.0
|
@ -3,3 +3,6 @@ detailed-errors=1
|
||||
with-coverage=1
|
||||
cover-package=hy
|
||||
nocapture=1
|
||||
|
||||
[wheel]
|
||||
universal = 1
|
||||
|
4
setup.py
4
setup.py
@ -59,7 +59,8 @@ setup(
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'hy = hy.cmdline:hy_main',
|
||||
'hyc = hy.cmdline:hyc_main'
|
||||
'hyc = hy.cmdline:hyc_main',
|
||||
'hy2py = hy.cmdline:hy2py_main',
|
||||
]
|
||||
},
|
||||
packages=find_packages(exclude=['tests*']),
|
||||
@ -88,6 +89,7 @@ setup(
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.2",
|
||||
"Programming Language :: Python :: 3.3",
|
||||
"Programming Language :: Python :: 3.4",
|
||||
"Topic :: Software Development :: Code Generators",
|
||||
"Topic :: Software Development :: Compilers",
|
||||
"Topic :: Software Development :: Libraries",
|
||||
|
@ -19,3 +19,4 @@ from .native_tests.contrib.loop import * # noqa
|
||||
from .native_tests.contrib.meth import * # noqa
|
||||
from .native_tests.contrib.walk import * # noqa
|
||||
from .native_tests.contrib.multi import * # noqa
|
||||
from .native_tests.contrib.curry import * # noqa
|
||||
|
@ -353,17 +353,6 @@ def test_ast_non_decoratable():
|
||||
cant_compile("(with-decorator (foo) (* x x))")
|
||||
|
||||
|
||||
def test_ast_non_kwapplyable():
|
||||
""" Ensure kwapply breaks """
|
||||
code = tokenize("(kwapply foo bar)")
|
||||
code[0][2] = None
|
||||
try:
|
||||
hy_compile(code, "__main__")
|
||||
assert True is False
|
||||
except HyCompileError:
|
||||
pass
|
||||
|
||||
|
||||
def test_ast_lambda_lists():
|
||||
"""Ensure the compiler chokes on invalid lambda-lists"""
|
||||
cant_compile('(fn [&key {"a" b} &key {"foo" bar}] [a foo])')
|
||||
|
@ -1,27 +0,0 @@
|
||||
# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a
|
||||
# copy of this software and associated documentation files (the "Software"),
|
||||
# to deal in the Software without restriction, including without limitation
|
||||
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
# and/or sell copies of the Software, and to permit persons to whom the
|
||||
# Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
# DEALINGS IN THE SOFTWARE.
|
||||
|
||||
from .test_ast import can_compile, cant_compile
|
||||
|
||||
|
||||
def test_macro_nested_kwapply():
|
||||
"Make sure nested kwapply compile correctly"
|
||||
can_compile("(kwapply (kwapply (foo) bar) baz)")
|
||||
cant_compile("(kwapply (kwapply (foo)) bar)")
|
13
tests/native_tests/contrib/curry.hy
Normal file
13
tests/native_tests/contrib/curry.hy
Normal file
@ -0,0 +1,13 @@
|
||||
(require hy.contrib.curry)
|
||||
|
||||
|
||||
(defnc s [x y z] ((x z) (y z))) ; λxyz.xz(yz)
|
||||
(defnc k [x] (fn [y] x)) ; λx.λy.x
|
||||
(defnc i [x] x) ;; λx.x
|
||||
|
||||
(defnc succ [n] (+ n 1))
|
||||
|
||||
|
||||
(defn test-curry []
|
||||
(assert (= 16 (((((s ((((k s) k) i) i)) (i i)) ((i (i i))
|
||||
((((k s) i) ((s (k s)) k)) i))) succ) 0))))
|
@ -82,8 +82,8 @@
|
||||
(assert-equal res [None 4 5])
|
||||
(setv res (list (drop 0 [1 2 3 4 5])))
|
||||
(assert-equal res [1 2 3 4 5])
|
||||
(setv res (list (drop -1 [1 2 3 4 5])))
|
||||
(assert-equal res [1 2 3 4 5])
|
||||
(try (do (list (drop -1 [1 2 3 4 5])) (assert False))
|
||||
(catch [e [ValueError]] nil))
|
||||
(setv res (list (drop 6 (iter [1 2 3 4 5]))))
|
||||
(assert-equal res [])
|
||||
(setv res (list (take 5 (drop 2 (iterate inc 0)))))
|
||||
@ -335,12 +335,15 @@
|
||||
"NATIVE: testing the nth function"
|
||||
(assert-equal 2 (nth [1 2 4 7] 1))
|
||||
(assert-equal 7 (nth [1 2 4 7] 3))
|
||||
(assert-true (none? (nth [1 2 4 7] 5)))
|
||||
(assert-true (none? (nth [1 2 4 7] -1)))
|
||||
(try (do (nth [1 2 4 7] 5) (assert False))
|
||||
(catch [e [IndexError]] nil))
|
||||
(try (do (nth [1 2 4 7] -1) (assert False))
|
||||
(catch [e [ValueError]] nil))
|
||||
;; now for iterators
|
||||
(assert-equal 2 (nth (iter [1 2 4 7]) 1))
|
||||
(assert-equal 7 (nth (iter [1 2 4 7]) 3))
|
||||
(assert-true (none? (nth (iter [1 2 4 7]) -1)))
|
||||
(try (do (nth (iter [1 2 4 7]) -1) (assert False))
|
||||
(catch [e [ValueError]] nil))
|
||||
(assert-equal 5 (nth (take 3 (drop 2 [1 2 3 4 5 6])) 2)))
|
||||
|
||||
(defn test-numeric? []
|
||||
@ -429,8 +432,8 @@
|
||||
(assert-equal res ["s" "s" "s" "s"])
|
||||
(setv res (list (take 0 (repeat "s"))))
|
||||
(assert-equal res [])
|
||||
(setv res (list (take -1 (repeat "s"))))
|
||||
(assert-equal res [])
|
||||
(try (do (list (take -1 (repeat "s"))) (assert False))
|
||||
(catch [e [ValueError]] nil))
|
||||
(setv res (list (take 6 [1 2 None 4])))
|
||||
(assert-equal res [1 2 None 4]))
|
||||
|
||||
@ -478,3 +481,14 @@
|
||||
(assert-equal (list res) [4 4 4])
|
||||
(setv res (zipwith operator.sub [3 7 9] [1 2 4]))
|
||||
(assert-equal (list res) [2 5 5]))
|
||||
|
||||
(defn test-is-keyword []
|
||||
"NATIVE: testing the keyword? function"
|
||||
(assert (keyword? ':bar))
|
||||
(assert (keyword? ':baz))
|
||||
(assert (keyword? :bar))
|
||||
(assert (keyword? :baz))
|
||||
(assert (not (keyword? "foo")))
|
||||
(assert (not (keyword? ":foo")))
|
||||
(assert (not (keyword? 1)))
|
||||
(assert (not (keyword? nil))))
|
||||
|
@ -199,20 +199,10 @@
|
||||
|
||||
(defn test-kwargs []
|
||||
"NATIVE: test kwargs things."
|
||||
(assert (= (kwapply (kwtest) {"one" "two"}) {"one" "two"}))
|
||||
(assert (= (apply kwtest [] {"one" "two"}) {"one" "two"}))
|
||||
(setv mydict {"one" "three"})
|
||||
(assert (= (kwapply (kwtest) mydict) mydict))
|
||||
(assert (= (kwapply (kwtest) ((fn [] {"one" "two"}))) {"one" "two"}))
|
||||
(assert (= (kwapply
|
||||
(kwapply
|
||||
(kwapply
|
||||
(kwapply
|
||||
(kwapply (kwtest) {"x" 4})
|
||||
mydict)
|
||||
{"x" 8})
|
||||
{"x" (- 3 2) "y" 2})
|
||||
{"y" 5 "z" 3})
|
||||
{"x" 1 "y" 5 "z" 3 "one" "three"})))
|
||||
(assert (= (apply kwtest [] mydict) mydict))
|
||||
(assert (= (apply kwtest [] ((fn [] {"one" "two"}))) {"one" "two"})))
|
||||
|
||||
|
||||
(defn test-apply []
|
||||
@ -246,6 +236,11 @@
|
||||
"NATIVE: test do"
|
||||
(do))
|
||||
|
||||
(defn test-bare-try [] (try
|
||||
(try (raise ValueError))
|
||||
(except [ValueError])
|
||||
(else (assert false))))
|
||||
|
||||
|
||||
(defn test-exceptions []
|
||||
"NATIVE: test Exceptions"
|
||||
@ -479,7 +474,7 @@
|
||||
|
||||
(defn test-rest []
|
||||
"NATIVE: test rest"
|
||||
(assert (= (rest [1 2 3 4 5]) [2 3 4 5])))
|
||||
(assert (= (list (rest [1 2 3 4 5])) [2 3 4 5])))
|
||||
|
||||
|
||||
(defn test-importas []
|
||||
@ -785,8 +780,8 @@
|
||||
"NATIVE: test &key function arguments"
|
||||
(defn foo [&key {"a" None "b" 1}] [a b])
|
||||
(assert (= (foo) [None 1]))
|
||||
(assert (= (kwapply (foo) {"a" 2}) [2 1]))
|
||||
(assert (= (kwapply (foo) {"b" 42}) [None 42])))
|
||||
(assert (= (apply foo [] {"a" 2}) [2 1]))
|
||||
(assert (= (apply foo [] {"b" 42}) [None 42])))
|
||||
|
||||
|
||||
(defn test-optional-arguments []
|
||||
@ -947,22 +942,10 @@
|
||||
|
||||
(defn test-disassemble []
|
||||
"NATIVE: Test the disassemble function"
|
||||
(import sys)
|
||||
(if-python2
|
||||
(import [io [BytesIO :as StringIO]])
|
||||
(import [io [StringIO]]))
|
||||
(setv prev-stdout sys.stdout)
|
||||
(setv sys.stdout (StringIO))
|
||||
(disassemble '(do (leaky) (leaky) (macros)))
|
||||
(setv stdout (.getvalue sys.stdout))
|
||||
(setv sys.stdout prev-stdout)
|
||||
(assert (in "leaky" stdout))
|
||||
(assert (in "macros" stdout))
|
||||
(setv sys.stdout (StringIO))
|
||||
(disassemble '(do (leaky) (leaky) (macros)) true)
|
||||
(setv stdout (.getvalue sys.stdout))
|
||||
(setv sys.stdout prev-stdout)
|
||||
(assert (= stdout "leaky()\nleaky()\nmacros()\n")))
|
||||
(assert (= (disassemble '(do (leaky) (leaky) (macros)))
|
||||
"Module(\n body=[\n Expr(value=Call(func=Name(id='leaky'), args=[], keywords=[], starargs=None, kwargs=None)),\n Expr(value=Call(func=Name(id='leaky'), args=[], keywords=[], starargs=None, kwargs=None)),\n Expr(value=Call(func=Name(id='macros'), args=[], keywords=[], starargs=None, kwargs=None))])"))
|
||||
(assert (= (disassemble '(do (leaky) (leaky) (macros)) true)
|
||||
"leaky()\nleaky()\nmacros()")))
|
||||
|
||||
|
||||
(defn test-attribute-access []
|
||||
|
@ -1,3 +1,6 @@
|
||||
(import [hy._compat [PY33]])
|
||||
(import [hy.errors [HyCompileError]])
|
||||
|
||||
(defmacro rev [&rest body]
|
||||
"Execute the `body` statements in reverse"
|
||||
(quasiquote (do (unquote-splice (list (reversed body))))))
|
||||
@ -99,11 +102,18 @@
|
||||
|
||||
(defn test-yield-from []
|
||||
"NATIVE: testing yield from"
|
||||
(defn yield-from-test []
|
||||
(for* [i (range 3)]
|
||||
(yield i))
|
||||
(yield-from [1 2 3]))
|
||||
(assert (= (list (yield-from-test)) [0 1 2 1 2 3])))
|
||||
|
||||
(try
|
||||
(eval
|
||||
'(do (defn yield-from-test []
|
||||
(for* [i (range 3)]
|
||||
(yield i))
|
||||
(yield-from [1 2 3]))
|
||||
(assert (= (list (yield-from-test)) [0 1 2 1 2 3]))))
|
||||
(catch [e HyCompileError]
|
||||
;; Yup, this should happen on non-Python3.3 thingies
|
||||
(assert (not PY33)))
|
||||
(else (assert PY33))))
|
||||
|
||||
(defn test-if-python2 []
|
||||
(import sys)
|
||||
@ -191,6 +201,25 @@
|
||||
:yes)))
|
||||
|
||||
|
||||
(defn test-lisp-if []
|
||||
"test that lisp-if works as expected"
|
||||
; nil is false
|
||||
(assert (= (lisp-if None "true" "false") "false"))
|
||||
(assert (= (lisp-if nil "true" "false") "false"))
|
||||
|
||||
; But everything else is True! Even falsey things.
|
||||
(assert (= (lisp-if True "true" "false") "true"))
|
||||
(assert (= (lisp-if False "true" "false") "true"))
|
||||
(assert (= (lisp-if 0 "true" "false") "true"))
|
||||
(assert (= (lisp-if "some-string" "true" "false") "true"))
|
||||
(assert (= (lisp-if "" "true" "false") "true"))
|
||||
(assert (= (lisp-if (+ 1 2 3) "true" "false") "true"))
|
||||
|
||||
; Just to be sure, test the alias lif
|
||||
(assert (= (lif nil "true" "false") "false"))
|
||||
(assert (= (lif 0 "true" "false") "true")))
|
||||
|
||||
|
||||
(defn test-defn-alias []
|
||||
(defn-alias [tda-main tda-a1 tda-a2] [] :bazinga)
|
||||
(defun-alias [tda-main tda-a1 tda-a2] [] :bazinga)
|
||||
|
5
tests/resources/bin/main.hy
Normal file
5
tests/resources/bin/main.hy
Normal file
@ -0,0 +1,5 @@
|
||||
(defmain [&rest args]
|
||||
(print args)
|
||||
(print "Hello World")
|
||||
(if (in "exit1" args)
|
||||
1))
|
4
tests/resources/bin/nomain.hy
Normal file
4
tests/resources/bin/nomain.hy
Normal file
@ -0,0 +1,4 @@
|
||||
(print "This Should Still Works")
|
||||
|
||||
(defn main []
|
||||
(print "This Should Not Work"))
|
@ -2,6 +2,7 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
|
||||
# Copyright (c) 2013 Will Kahn-Greene <willg@bluesock.org>
|
||||
# Copyright (c) 2014 Bob Tolbert <bob@tolbert.org>
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a
|
||||
# copy of this software and associated documentation files (the "Software"),
|
||||
@ -23,8 +24,6 @@
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from nose.plugins.skip import SkipTest
|
||||
|
||||
|
||||
def run_cmd(cmd, stdin_data=None):
|
||||
p = subprocess.Popen(cmd,
|
||||
@ -125,16 +124,13 @@ def test_bin_hyc_missing_file():
|
||||
|
||||
|
||||
def test_hy2py():
|
||||
# and running this script this way doesn't work on Windows
|
||||
if os.name == "nt":
|
||||
raise SkipTest("doesn't work on Windows")
|
||||
|
||||
i = 0
|
||||
for dirpath, dirnames, filenames in os.walk("tests/native_tests"):
|
||||
for f in filenames:
|
||||
if f.endswith(".hy"):
|
||||
i += 1
|
||||
ret = run_cmd("bin/hy2py -s -a " + os.path.join(dirpath, f))
|
||||
ret = run_cmd("hy2py -s -a "
|
||||
+ os.path.join(dirpath, f))
|
||||
assert ret[0] == 0, f
|
||||
assert len(ret[1]) > 1, f
|
||||
assert len(ret[2]) == 0, f
|
||||
@ -146,3 +142,27 @@ def test_bin_hy_builtins():
|
||||
|
||||
assert str(exit) == "Use (exit) or Ctrl-D (i.e. EOF) to exit"
|
||||
assert str(quit) == "Use (quit) or Ctrl-D (i.e. EOF) to exit"
|
||||
|
||||
|
||||
def test_bin_hy_main():
|
||||
ret = run_cmd("hy tests/resources/bin/main.hy")
|
||||
assert ret[0] == 0
|
||||
assert "Hello World" in ret[1]
|
||||
|
||||
|
||||
def test_bin_hy_main_args():
|
||||
ret = run_cmd("hy tests/resources/bin/main.hy test 123")
|
||||
assert ret[0] == 0
|
||||
assert "test" in ret[1]
|
||||
assert "123" in ret[1]
|
||||
|
||||
|
||||
def test_bin_hy_main_exitvalue():
|
||||
ret = run_cmd("hy tests/resources/bin/main.hy exit1")
|
||||
assert ret[0] == 1
|
||||
|
||||
|
||||
def test_bin_hy_no_main():
|
||||
ret = run_cmd("hy tests/resources/bin/nomain.hy")
|
||||
assert ret[0] == 0
|
||||
assert "This Should Still Work" in ret[1]
|
||||
|
37
tox.ini
37
tox.ini
@ -1,39 +1,18 @@
|
||||
[tox]
|
||||
envlist = py27,pypy,py32,py33,py26,flake8
|
||||
envlist = py26,py27,pypy,py32,py33,flake8
|
||||
skipsdist = True
|
||||
|
||||
[testenv]
|
||||
commands = nosetests
|
||||
commands =
|
||||
pip install --allow-all-external -e .
|
||||
nosetests
|
||||
deps =
|
||||
nose
|
||||
setuptools
|
||||
rply
|
||||
|
||||
[testenv:pypy]
|
||||
commands = nosetests
|
||||
deps =
|
||||
astor
|
||||
nose
|
||||
setuptools
|
||||
rply
|
||||
|
||||
[testenv:py27]
|
||||
commands = nosetests
|
||||
deps =
|
||||
astor
|
||||
nose
|
||||
setuptools
|
||||
rply
|
||||
-rrequirements-dev.txt
|
||||
|
||||
[testenv:py26]
|
||||
deps =
|
||||
astor
|
||||
nose
|
||||
setuptools
|
||||
{[testenv]deps}
|
||||
unittest2
|
||||
importlib
|
||||
rply
|
||||
|
||||
[testenv:flake8]
|
||||
deps =
|
||||
flake8
|
||||
rply
|
||||
commands = flake8 hy bin tests
|
||||
|
Loading…
x
Reference in New Issue
Block a user