Repository: berkerpeksag/astor

Issue:
Can't generate code containing ast.Num(NaN)
Somewhat related to #82, the `codegen` of astor 0.5 would produce `nan` if given a `Num` node that contained NaN. In astor 0.6, the following raises an `AssertionError` in code_gen.py:

```py
import ast, astor

nan = 1e1000 - 1e1000

print(astor.code_gen.to_source(
         ast.Module([ast.Expr(ast.BinOp(
             ast.Num(1.0),
             ast.Add(),
             ast.Num(nan)))])))
```

While Python has no NaN literal, you could represent `ast.Num(nan)` as an expression (such as `1e1000 - 1e1000`) if you want to generate real Python. See hylang/hy#1447.


Discussion:
berkerpeksag: Thanks for the PR, @Kodiologist! I will review this later today. Could you also add release notes for #85 and #100 to `docs/changelog.rst`?
Kodiologist: You're welcome. Done.

Patch:
diff --git a/.travis.yml b/.travis.yml
index e6362f4..c0e59fa 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,18 +1,13 @@
 sudo: false  # run travis jobs in containers
 language: python
 python:
-  - 2.6
   - 2.7
-  - 3.3
   - 3.4
   - 3.5
   - 3.6
   - pypy
   - pypy3.5
   - 3.7-dev
-matrix:
-  allow_failures:
-  - python: 2.6
 cache: pip
 install:
   - pip install tox-travis
diff --git a/AUTHORS b/AUTHORS
index 9949ccc..f00747a 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -13,3 +13,4 @@ And with some modifications based on Armin's code:
 * Ryan Gonzalez <rymg19@gmail.com>
 * Lenny Truong <leonardtruong@protonmail.com>
 * Radomír Bosák <radomir.bosak@gmail.com>
+* Kodi Arfer <git@arfer.net>
diff --git a/astor/code_gen.py b/astor/code_gen.py
index 8e1e6fa..e37b320 100644
--- a/astor/code_gen.py
+++ b/astor/code_gen.py
@@ -18,6 +18,7 @@ this code came from here (in 2012):
 """
 
 import ast
+import math
 import sys
 
 from .op_util import get_op_symbol, get_op_precedence, Precedence
@@ -638,22 +639,38 @@ class SourceGenerator(ExplicitNodeVisitor):
                   # constants
                   new=sys.version_info >= (3, 0)):
         with self.delimit(node) as delimiters:
-            s = repr(node.n)
-
-            # Deal with infinities -- if detected, we can
-            # generate them with 1e1000.
-            signed = s.startswith('-')
-            if s[signed].isalpha():
-                im = s[-1] == 'j' and 'j' or ''
-                assert s[signed:signed + 3] == 'inf', s
-                s = '%s1e1000%s' % ('-' if signed else '', im)
+            x = node.n
+
+            def part(p, imaginary):
+                # Represent infinity as 1e1000 and NaN as 1e1000-1e1000.
+                s = 'j' if imaginary else ''
+                if math.isinf(p):
+                    if p < 0:
+                        return '-1e1000' + s
+                    return '1e1000' + s
+                if math.isnan(p):
+                    return '(1e1000%s-1e1000%s)' % (s, s)
+                return repr(p) + s
+
+            real = part(x.real if isinstance(x, complex) else x, imaginary=False)
+            if isinstance(x, complex):
+                imag = part(x.imag, imaginary=True)
+                if x.real == 0:
+                    s = imag
+                elif x.imag == 0:
+                    s = '(%s+0j)' % real
+                else:
+                    # x has nonzero real and imaginary parts.
+                    s = '(%s%s%s)' % (real, ['+', ''][imag.startswith('-')], imag)
+            else:
+                s = real
             self.write(s)
 
             # The Python 2.x compiler merges a unary minus
             # with a number.  This is a premature optimization
             # that we deal with here...
             if not new and delimiters.discard:
-                if signed:
+                if not isinstance(node.n, complex) and node.n < 0:
                     pow_lhs = Precedence.Pow + 1
                     delimiters.discard = delimiters.pp != pow_lhs
                 else:
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 706d322..9135d8b 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -22,6 +22,9 @@ New features
 
 .. _`Issue 86`: https://github.com/berkerpeksag/astor/issues/86
 
+* Dropped support for Python 2.6 and Python 3.3. Even the latest version of pip
+  dropped its support for both of these versions.
+
 Bug fixes
 ~~~~~~~~~
 
@@ -37,6 +40,12 @@ Bug fixes
 .. _`Issue 89`: https://github.com/berkerpeksag/astor/issues/89
 .. _`Issue 101`: https://github.com/berkerpeksag/astor/issues/101
 
+* Improved code generation to support ``ast.Num`` nodes containing infinities
+  or NaNs.
+  (Reported and fixed by Kodi Arfer in `Issue 85`_ and `Issue 100`_.)
+
+.. _`Issue 85`: https://github.com/berkerpeksag/astor/issues/85
+.. _`Issue 100`: https://github.com/berkerpeksag/astor/issues/100
 
 0.6.2 - 2017-11-11
 ------------------
diff --git a/setup.cfg b/setup.cfg
index 8faaf1f..cf0bb95 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -33,6 +33,7 @@ classifiers =
 zip_safe = True
 include_package_data = True
 packages = find:
+python_requires = >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
 
 [options.packages.find]
 exclude = tests
diff --git a/tox.ini b/tox.ini
index e364485..5f6ddf0 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
 [tox]
-envlist = py26, py27, py33, py34, py35, py36, pypy, pypy3.5
+envlist = py27, py34, py35, py36, pypy, pypy3.5
 skipsdist = True
 
 [testenv]
@@ -7,4 +7,4 @@ usedevelop = True
 commands = nosetests -v --nocapture {posargs}
 deps =
  -rrequirements-tox.txt
- py2{6,7},pypy: unittest2
+ py27,pypy: unittest2


Test patch:
diff --git a/tests/test_code_gen.py b/tests/test_code_gen.py
index a71a939..b8c1c6a 100644
--- a/tests/test_code_gen.py
+++ b/tests/test_code_gen.py
@@ -8,6 +8,7 @@ Copyright (c) 2015 Patrick Maupin
 """
 
 import ast
+import math
 import sys
 import textwrap
 
@@ -22,6 +23,8 @@ import astor
 def canonical(srctxt):
     return textwrap.dedent(srctxt).strip()
 
+def astornum(x):
+    return eval(astor.to_source(ast.Expression(body=ast.Num(n=x))))
 
 class Comparisons(object):
 
@@ -245,6 +248,14 @@ class CodegenTestCase(unittest.TestCase, Comparisons):
         """
         self.assertAstRoundtripsGtVer(source, (2, 7))
 
+    def test_complex(self):
+        source = """
+            (3) + (4j) + (1+2j) + (1+0j)
+        """
+        self.assertAstRoundtrips(source)
+
+        self.assertIsInstance(astornum(1+0j), complex)
+
     def test_inf(self):
         source = """
             (1e1000) + (-1e1000) + (1e1000j) + (-1e1000j)
@@ -259,6 +270,19 @@ class CodegenTestCase(unittest.TestCase, Comparisons):
         # Returns 'a = 1e1000'.
         self.assertSrcDoesNotRoundtrip(source)
 
+        self.assertIsInstance(astornum((1e1000+1e1000)+0j), complex)
+
+    def test_nan(self):
+        self.assertTrue(math.isnan(astornum(float('nan'))))
+
+        v = astornum(complex(-1e1000, float('nan')))
+        self.assertEqual(v.real, -1e1000)
+        self.assertTrue(math.isnan(v.imag))
+
+        v = astornum(complex(float('nan'), -1e1000))
+        self.assertTrue(math.isnan(v.real))
+        self.assertEqual(v.imag, -1e1000)
+
     def test_unary(self):
         source = """
             -(1) + ~(2) + +(3)