Repository: hylang/hy

Issue:
repl shouldn't crash
```Hy
=> (defmacro bad [] `(macro-error 'x ""))
<function <lambda> at 0x000001D01D0ED7B8>
=> (bad)
Traceback (most recent call last):
  File "c:\users\me\documents\github\hy\hy\cmdline.py", line 99, in runsource
    ast_callback)
  File "c:\users\me\documents\github\hy\hy\importer.py", line 198, in hy_eval
    eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)
  File "<eval_body>", line 1, in <module>
hy.errors.HyMacroExpansionError: <exception str() failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ME\workspace\hy36-gilch\Scripts\hy-script.py", line 11, in <module>
    load_entry_point('hy', 'console_scripts', 'hy')()
  File "c:\users\me\documents\github\hy\hy\cmdline.py", line 346, in hy_main
    sys.exit(cmdline_handler("hy", sys.argv))
  File "c:\users\me\documents\github\hy\hy\cmdline.py", line 341, in cmdline_handler
    return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
  File "c:\users\me\documents\github\hy\hy\cmdline.py", line 236, in run_repl
    os=platform.system()
  File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 233, in interact
    more = self.push(line)
  File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 259, in push
    more = self.runsource(source, self.filename)
  File "c:\users\me\documents\github\hy\hy\cmdline.py", line 105, in runsource
    print(e, file=sys.stderr)
  File "c:\users\me\documents\github\hy\hy\errors.py", line 46, in __str__
    line = self.expression.start_line
AttributeError: 'HySymbol' object has no attribute 'start_line'
```
The repl should report errors, but not exit.


Discussion:
> `AttributeError: 'HySymbol' object has no attribute 'start_line'`

It looks like `x` isn't getting position information set.

Have you seen a way to replicate this without using `macro-error` in user code?
In particular, I don't believe `macro-error` is designed to take a quoted form, just an argument to the macro (or `None`).
`macro-error` is not documented, #1358, so I had to experiment. My complaint isn't that `macro-error` crashed, but that the repl crashed.
Fair enough; that's why I think this and #1413 are properly the same bug.
I think the REPL is crashable in multiple places, but whatever.

Your minimal example from #1413 is fixable by catching `BaseException` (or just using an empty `except:`.) in those two places. But that doesn't fix the macroexpand or macro-error issues.
Hmm. Perhaps what's needed is a `try` for `self.showtraceback()`, then.
It actually appears to be from [line 105](https://github.com/hylang/hy/blob/51fb807cc9eb5b005b79b4dbe819d8e11889de78/hy/cmdline.py#L105)

I'm thinking we should just wrap the whole contents of this function with a try/except to show traceback.
We should also fix the cause. `HyTypeError` is assuming its expression has start/end values for line/column. This assumption is wrong, since macros can return expressions that weren't created directly from text. Models created this way will lack those attributes.

Here's the real minimal example.
```Hy
=> (import [hy.errors [HyTypeError]])
=> (raise (HyTypeError '[] "bad"))
```
This crashes the repl.

The easiest solution is to assign a default `-1` for these four attrs in the `HyObject` class.

The nicest solution would probably be to find the right line and column values in some kind of source generated from the expression, probably the pretty-printed Hy models #1360 or maybe the astor-generated Python, if possible.

Resolving patch:
diff --git a/hy/errors.py b/hy/errors.py
--- a/hy/errors.py
+++ b/hy/errors.py
@@ -43,41 +43,47 @@ def __init__(self, expression, message):
 
     def __str__(self):
 
-        line = self.expression.start_line
-        start = self.expression.start_column
-        end = self.expression.end_column
-
-        source = []
-        if self.source is not None:
-            source = self.source.split("\n")[line-1:self.expression.end_line]
-
-            if line == self.expression.end_line:
-                length = end - start
-            else:
-                length = len(source[0]) - start
-
         result = ""
 
-        result += '  File "%s", line %d, column %d\n\n' % (self.filename,
-                                                           line,
-                                                           start)
-
-        if len(source) == 1:
-            result += '  %s\n' % colored.red(source[0])
-            result += '  %s%s\n' % (' '*(start-1),
-                                    colored.green('^' + '-'*(length-1) + '^'))
-        if len(source) > 1:
-            result += '  %s\n' % colored.red(source[0])
-            result += '  %s%s\n' % (' '*(start-1),
-                                    colored.green('^' + '-'*length))
-            if len(source) > 2:  # write the middle lines
-                for line in source[1:-1]:
-                    result += '  %s\n' % colored.red("".join(line))
-                    result += '  %s\n' % colored.green("-"*len(line))
-
-            # write the last line
-            result += '  %s\n' % colored.red("".join(source[-1]))
-            result += '  %s\n' % colored.green('-'*(end-1) + '^')
+        if all(getattr(self.expression, x, None) is not None
+               for x in ("start_line", "start_column", "end_column")):
+
+            line = self.expression.start_line
+            start = self.expression.start_column
+            end = self.expression.end_column
+
+            source = []
+            if self.source is not None:
+                source = self.source.split("\n")[line-1:self.expression.end_line]
+
+                if line == self.expression.end_line:
+                    length = end - start
+                else:
+                    length = len(source[0]) - start
+
+            result += '  File "%s", line %d, column %d\n\n' % (self.filename,
+                                                               line,
+                                                               start)
+
+            if len(source) == 1:
+                result += '  %s\n' % colored.red(source[0])
+                result += '  %s%s\n' % (' '*(start-1),
+                                        colored.green('^' + '-'*(length-1) + '^'))
+            if len(source) > 1:
+                result += '  %s\n' % colored.red(source[0])
+                result += '  %s%s\n' % (' '*(start-1),
+                                        colored.green('^' + '-'*length))
+                if len(source) > 2:  # write the middle lines
+                    for line in source[1:-1]:
+                        result += '  %s\n' % colored.red("".join(line))
+                        result += '  %s\n' % colored.green("-"*len(line))
+
+                # write the last line
+                result += '  %s\n' % colored.red("".join(source[-1]))
+                result += '  %s\n' % colored.green('-'*(end-1) + '^')
+
+        else:
+            result += '  File "%s", unknown location\n' % self.filename
 
         result += colored.yellow("%s: %s\n\n" %
                                  (self.__class__.__name__,


Test patch:
diff --git a/tests/test_bin.py b/tests/test_bin.py
--- a/tests/test_bin.py
+++ b/tests/test_bin.py
@@ -138,6 +138,16 @@ def test_bin_hy_stdin_except_do():
     assert "zzz" in output
 
 
+def test_bin_hy_stdin_unlocatable_hytypeerror():
+    # https://github.com/hylang/hy/issues/1412
+    # The chief test of interest here is the returncode assertion
+    # inside run_cmd.
+    _, err = run_cmd("hy", """
+        (import hy.errors)
+        (raise (hy.errors.HyTypeError '[] (+ "A" "Z")))""")
+    assert "AZ" in err
+
+
 def test_bin_hy_stdin_bad_repr():
     # https://github.com/hylang/hy/issues/1389
     output, err = run_cmd("hy", """