We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Remove internal `importlib` frames from traceback
Python 3.x uses `_call_with_frames_removed` to remove internal frames from tracebacks.  I tried it in #1687, but couldn't get it to work; might be due to this [Python issue](https://bugs.python.org/issue23773).  
Regardless, it would be good to remove those frames somehow.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `hy/errors.py`
Content:
```
1 import os
2 import re
3 import sys
4 import traceback
5 import pkgutil
6 
7 from functools import reduce
8 from colorama import Fore
9 from contextlib import contextmanager
10 from hy import _initialize_env_var
11 
12 _hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',
13                                                  True)
14 COLORED = _initialize_env_var('HY_COLORED_ERRORS', False)
15 
16 
17 class HyError(Exception):
18     pass
19 
20 
21 class HyInternalError(HyError):
22     """Unexpected errors occurring during compilation or parsing of Hy code.
23 
24     Errors sub-classing this are not intended to be user-facing, and will,
25     hopefully, never be seen by users!
26     """
27 
28 
29 class HyLanguageError(HyError):
30     """Errors caused by invalid use of the Hy language.
31 
32     This, and any errors inheriting from this, are user-facing.
33     """
34 
35     def __init__(self, message, expression=None, filename=None, source=None,
36                  lineno=1, colno=1):
37         """
38         Parameters
39         ----------
40         message: str
41             The message to display for this error.
42         expression: HyObject, optional
43             The Hy expression generating this error.
44         filename: str, optional
45             The filename for the source code generating this error.
46             Expression-provided information will take precedence of this value.
47         source: str, optional
48             The actual source code generating this error.  Expression-provided
49             information will take precedence of this value.
50         lineno: int, optional
51             The line number of the error.  Expression-provided information will
52             take precedence of this value.
53         colno: int, optional
54             The column number of the error.  Expression-provided information
55             will take precedence of this value.
56         """
57         self.msg = message
58         self.compute_lineinfo(expression, filename, source, lineno, colno)
59 
60         if isinstance(self, SyntaxError):
61             syntax_error_args = (self.filename, self.lineno, self.offset,
62                                  self.text)
63             super(HyLanguageError, self).__init__(message, syntax_error_args)
64         else:
65             super(HyLanguageError, self).__init__(message)
66 
67     def compute_lineinfo(self, expression, filename, source, lineno, colno):
68 
69         # NOTE: We use `SyntaxError`'s field names (i.e. `text`, `offset`,
70         # `msg`) for compatibility and print-outs.
71         self.text = getattr(expression, 'source', source)
72         self.filename = getattr(expression, 'filename', filename)
73 
74         if self.text:
75             lines = self.text.splitlines()
76 
77             self.lineno = getattr(expression, 'start_line', lineno)
78             self.offset = getattr(expression, 'start_column', colno)
79             end_column = getattr(expression, 'end_column',
80                                  len(lines[self.lineno-1]))
81             end_line = getattr(expression, 'end_line', self.lineno)
82 
83             # Trim the source down to the essentials.
84             self.text = '\n'.join(lines[self.lineno-1:end_line])
85 
86             if end_column:
87                 if self.lineno == end_line:
88                     self.arrow_offset = end_column
89                 else:
90                     self.arrow_offset = len(self.text[0])
91 
92                 self.arrow_offset -= self.offset
93             else:
94                 self.arrow_offset = None
95         else:
96             # We could attempt to extract the source given a filename, but we
97             # don't.
98             self.lineno = lineno
99             self.offset = colno
100             self.arrow_offset = None
101 
102     def __str__(self):
103         """Provide an exception message that includes SyntaxError-like source
104         line information when available.
105         """
106         # Syntax errors are special and annotate the traceback (instead of what
107         # we would do in the message that follows the traceback).
108         if isinstance(self, SyntaxError):
109             return super(HyLanguageError, self).__str__()
110         # When there isn't extra source information, use the normal message.
111         elif not self.text:
112             return super(HyLanguageError, self).__str__()
113 
114         # Re-purpose Python's builtin syntax error formatting.
115         output = traceback.format_exception_only(
116             SyntaxError,
117             SyntaxError(self.msg, (self.filename, self.lineno, self.offset,
118                                    self.text)))
119 
120         arrow_idx, _ = next(((i, x) for i, x in enumerate(output)
121                              if x.strip() == '^'),
122                             (None, None))
123         if arrow_idx:
124             msg_idx = arrow_idx + 1
125         else:
126             msg_idx, _ = next((i, x) for i, x in enumerate(output)
127                               if x.startswith('SyntaxError: '))
128 
129         # Get rid of erroneous error-type label.
130         output[msg_idx] = re.sub('^SyntaxError: ', '', output[msg_idx])
131 
132         # Extend the text arrow, when given enough source info.
133         if arrow_idx and self.arrow_offset:
134             output[arrow_idx] = '{}{}^\n'.format(output[arrow_idx].rstrip('\n'),
135                                                  '-' * (self.arrow_offset - 1))
136 
137         if COLORED:
138             output[msg_idx:] = [Fore.YELLOW + o + Fore.RESET for o in output[msg_idx:]]
139             if arrow_idx:
140                 output[arrow_idx] = Fore.GREEN + output[arrow_idx] + Fore.RESET
141             for idx, line in enumerate(output[::msg_idx]):
142                 if line.strip().startswith(
143                         'File "{}", line'.format(self.filename)):
144                     output[idx] = Fore.RED + line + Fore.RESET
145 
146         # This resulting string will come after a "<class-name>:" prompt, so
147         # put it down a line.
148         output.insert(0, '\n')
149 
150         # Avoid "...expected str instance, ColoredString found"
151         return reduce(lambda x, y: x + y, output)
152 
153 
154 class HyCompileError(HyInternalError):
155     """Unexpected errors occurring within the compiler."""
156 
157 
158 class HyTypeError(HyLanguageError, TypeError):
159     """TypeError occurring during the normal use of Hy."""
160 
161 
162 class HyNameError(HyLanguageError, NameError):
163     """NameError occurring during the normal use of Hy."""
164 
165 
166 class HyRequireError(HyLanguageError):
167     """Errors arising during the use of `require`
168 
169     This, and any errors inheriting from this, are user-facing.
170     """
171 
172 
173 class HyMacroExpansionError(HyLanguageError):
174     """Errors caused by invalid use of Hy macros.
175 
176     This, and any errors inheriting from this, are user-facing.
177     """
178 
179 
180 class HyEvalError(HyLanguageError):
181     """Errors occurring during code evaluation at compile-time.
182 
183     These errors distinguish unexpected errors within the compilation process
184     (i.e. `HyInternalError`s) from unrelated errors in user code evaluated by
185     the compiler (e.g. in `eval-and-compile`).
186 
187     This, and any errors inheriting from this, are user-facing.
188     """
189 
190 
191 class HyIOError(HyInternalError, IOError):
192     """ Subclass used to distinguish between IOErrors raised by Hy itself as
193     opposed to Hy programs.
194     """
195 
196 
197 class HySyntaxError(HyLanguageError, SyntaxError):
198     """Error during the Lexing of a Hython expression."""
199 
200 
201 class HyWrapperError(HyError, TypeError):
202     """Errors caused by language model object wrapping.
203 
204     These can be caused by improper user-level use of a macro, so they're
205     not really "internal".  If they arise due to anything else, they're an
206     internal/compiler problem, though.
207     """
208 
209 
210 def _module_filter_name(module_name):
211     try:
212         compiler_loader = pkgutil.get_loader(module_name)
213         if not compiler_loader:
214             return None
215 
216         filename = compiler_loader.get_filename(module_name)
217         if not filename:
218             return None
219 
220         if compiler_loader.is_package(module_name):
221             # Use the package directory (e.g. instead of `.../__init__.py`) so
222             # that we can filter all modules in a package.
223             return os.path.dirname(filename)
224         else:
225             # Normalize filename endings, because tracebacks will use `pyc` when
226             # the loader says `py`.
227             return filename.replace('.pyc', '.py')
228     except Exception:
229         return None
230 
231 
232 _tb_hidden_modules = {m for m in map(_module_filter_name,
233                                      ['hy.compiler', 'hy.lex',
234                                       'hy.cmdline', 'hy.lex.parser',
235                                       'hy.importer', 'hy._compat',
236                                       'hy.macros', 'hy.models',
237                                       'hy.core.result_macros',
238                                       'rply'])
239                       if m is not None}
240 
241 
242 def hy_exc_filter(exc_type, exc_value, exc_traceback):
243     """Produce exceptions print-outs with all frames originating from the
244     modules in `_tb_hidden_modules` filtered out.
245 
246     The frames are actually filtered by each module's filename and only when a
247     subclass of `HyLanguageError` is emitted.
248 
249     This does not remove the frames from the actual tracebacks, so debugging
250     will show everything.
251     """
252     # frame = (filename, line number, function name*, text)
253     new_tb = []
254     for frame in traceback.extract_tb(exc_traceback):
255         if not (frame[0].replace('.pyc', '.py') in _tb_hidden_modules or
256                 os.path.dirname(frame[0]) in _tb_hidden_modules):
257             new_tb += [frame]
258 
259     lines = traceback.format_list(new_tb)
260 
261     lines.insert(0, "Traceback (most recent call last):\n")
262 
263     lines.extend(traceback.format_exception_only(exc_type, exc_value))
264     output = ''.join(lines)
265 
266     return output
267 
268 
269 def hy_exc_handler(exc_type, exc_value, exc_traceback):
270     """A `sys.excepthook` handler that uses `hy_exc_filter` to
271     remove internal Hy frames from a traceback print-out.
272     """
273     if os.environ.get('HY_DEBUG', False):
274         return sys.__excepthook__(exc_type, exc_value, exc_traceback)
275 
276     try:
277         output = hy_exc_filter(exc_type, exc_value, exc_traceback)
278         sys.stderr.write(output)
279         sys.stderr.flush()
280     except Exception:
281         sys.__excepthook__(exc_type, exc_value, exc_traceback)
282 
283 
284 @contextmanager
285 def filtered_hy_exceptions():
286     """Temporarily apply a `sys.excepthook` that filters Hy internal frames
287     from tracebacks.
288 
289     Filtering can be controlled by the variable
290     `hy.errors._hy_filter_internal_errors` and environment variable
291     `HY_FILTER_INTERNAL_ERRORS`.
292     """
293     global _hy_filter_internal_errors
294     if _hy_filter_internal_errors:
295         current_hook = sys.excepthook
296         sys.excepthook = hy_exc_handler
297         yield
298         sys.excepthook = current_hook
299     else:
300         yield
301
```

Path: `hy/_compat.py`
Content:
```
1 import sys
2 
3 PY3_7 = sys.version_info >= (3, 7)
4 PY3_8 = sys.version_info >= (3, 8)
5 PY3_9 = sys.version_info >= (3, 9)
6 PY3_10 = sys.version_info >= (3, 10)
7 
8 
9 if not PY3_9:
10     # Shim `ast.unparse`.
11     import ast, astor.code_gen
12     ast.unparse = astor.code_gen.to_source
13 
14 
15 if not PY3_7:
16     # Shim `asyncio.run`.
17     import asyncio
18     def f(coro):
19         return asyncio.get_event_loop().run_until_complete(coro)
20     asyncio.run = f
21
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/hy/_compat.py b/hy/_compat.py
--- a/hy/_compat.py
+++ b/hy/_compat.py
@@ -1,9 +1,11 @@
 import sys
+import platform
 
 PY3_7 = sys.version_info >= (3, 7)
 PY3_8 = sys.version_info >= (3, 8)
 PY3_9 = sys.version_info >= (3, 9)
 PY3_10 = sys.version_info >= (3, 10)
+PYPY = platform.python_implementation() == "PyPy"
 
 
 if not PY3_9:
diff --git a/hy/errors.py b/hy/errors.py
--- a/hy/errors.py
+++ b/hy/errors.py
@@ -8,6 +8,7 @@
 from colorama import Fore
 from contextlib import contextmanager
 from hy import _initialize_env_var
+from hy._compat import PYPY
 
 _hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',
                                                  True)
@@ -238,6 +239,13 @@
                                       'rply'])
                       if m is not None}
 
+# We can't derive these easily from just their module names due
+# to missing magic attributes in internal importlib modules
+_tb_hidden_modules.update(
+    f"<builtin>/frozen {x}" if PYPY else f"<frozen {x}>"
+    for x in ("importlib._bootstrap", "importlib._bootstrap_external")
+)
+
 
 def hy_exc_filter(exc_type, exc_value, exc_traceback):
     """Produce exceptions print-outs with all frames originating from the

{"golden_diff": "diff --git a/hy/_compat.py b/hy/_compat.py\n--- a/hy/_compat.py\n+++ b/hy/_compat.py\n@@ -1,9 +1,11 @@\n import sys\n+import platform\n \n PY3_7 = sys.version_info >= (3, 7)\n PY3_8 = sys.version_info >= (3, 8)\n PY3_9 = sys.version_info >= (3, 9)\n PY3_10 = sys.version_info >= (3, 10)\n+PYPY = platform.python_implementation() == \"PyPy\"\n \n \n if not PY3_9:\ndiff --git a/hy/errors.py b/hy/errors.py\n--- a/hy/errors.py\n+++ b/hy/errors.py\n@@ -8,6 +8,7 @@\n from colorama import Fore\n from contextlib import contextmanager\n from hy import _initialize_env_var\n+from hy._compat import PYPY\n \n _hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',\n                                                  True)\n@@ -238,6 +239,13 @@\n                                       'rply'])\n                       if m is not None}\n \n+# We can't derive these easily from just their module names due\n+# to missing magic attributes in internal importlib modules\n+_tb_hidden_modules.update(\n+    f\"<builtin>/frozen {x}\" if PYPY else f\"<frozen {x}>\"\n+    for x in (\"importlib._bootstrap\", \"importlib._bootstrap_external\")\n+)\n+\n \n def hy_exc_filter(exc_type, exc_value, exc_traceback):\n     \"\"\"Produce exceptions print-outs with all frames originating from the\n", "issue": "Remove internal `importlib` frames from traceback\nPython 3.x uses `_call_with_frames_removed` to remove internal frames from tracebacks.  I tried it in #1687, but couldn't get it to work; might be due to this [Python issue](https://bugs.python.org/issue23773).  \r\nRegardless, it would be good to remove those frames somehow.\n", "before_files": [{"content": "import os\nimport re\nimport sys\nimport traceback\nimport pkgutil\n\nfrom functools import reduce\nfrom colorama import Fore\nfrom contextlib import contextmanager\nfrom hy import _initialize_env_var\n\n_hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',\n                                                 True)\nCOLORED = _initialize_env_var('HY_COLORED_ERRORS', False)\n\n\nclass HyError(Exception):\n    pass\n\n\nclass HyInternalError(HyError):\n    \"\"\"Unexpected errors occurring during compilation or parsing of Hy code.\n\n    Errors sub-classing this are not intended to be user-facing, and will,\n    hopefully, never be seen by users!\n    \"\"\"\n\n\nclass HyLanguageError(HyError):\n    \"\"\"Errors caused by invalid use of the Hy language.\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n    def __init__(self, message, expression=None, filename=None, source=None,\n                 lineno=1, colno=1):\n        \"\"\"\n        Parameters\n        ----------\n        message: str\n            The message to display for this error.\n        expression: HyObject, optional\n            The Hy expression generating this error.\n        filename: str, optional\n            The filename for the source code generating this error.\n            Expression-provided information will take precedence of this value.\n        source: str, optional\n            The actual source code generating this error.  Expression-provided\n            information will take precedence of this value.\n        lineno: int, optional\n            The line number of the error.  Expression-provided information will\n            take precedence of this value.\n        colno: int, optional\n            The column number of the error.  Expression-provided information\n            will take precedence of this value.\n        \"\"\"\n        self.msg = message\n        self.compute_lineinfo(expression, filename, source, lineno, colno)\n\n        if isinstance(self, SyntaxError):\n            syntax_error_args = (self.filename, self.lineno, self.offset,\n                                 self.text)\n            super(HyLanguageError, self).__init__(message, syntax_error_args)\n        else:\n            super(HyLanguageError, self).__init__(message)\n\n    def compute_lineinfo(self, expression, filename, source, lineno, colno):\n\n        # NOTE: We use `SyntaxError`'s field names (i.e. `text`, `offset`,\n        # `msg`) for compatibility and print-outs.\n        self.text = getattr(expression, 'source', source)\n        self.filename = getattr(expression, 'filename', filename)\n\n        if self.text:\n            lines = self.text.splitlines()\n\n            self.lineno = getattr(expression, 'start_line', lineno)\n            self.offset = getattr(expression, 'start_column', colno)\n            end_column = getattr(expression, 'end_column',\n                                 len(lines[self.lineno-1]))\n            end_line = getattr(expression, 'end_line', self.lineno)\n\n            # Trim the source down to the essentials.\n            self.text = '\\n'.join(lines[self.lineno-1:end_line])\n\n            if end_column:\n                if self.lineno == end_line:\n                    self.arrow_offset = end_column\n                else:\n                    self.arrow_offset = len(self.text[0])\n\n                self.arrow_offset -= self.offset\n            else:\n                self.arrow_offset = None\n        else:\n            # We could attempt to extract the source given a filename, but we\n            # don't.\n            self.lineno = lineno\n            self.offset = colno\n            self.arrow_offset = None\n\n    def __str__(self):\n        \"\"\"Provide an exception message that includes SyntaxError-like source\n        line information when available.\n        \"\"\"\n        # Syntax errors are special and annotate the traceback (instead of what\n        # we would do in the message that follows the traceback).\n        if isinstance(self, SyntaxError):\n            return super(HyLanguageError, self).__str__()\n        # When there isn't extra source information, use the normal message.\n        elif not self.text:\n            return super(HyLanguageError, self).__str__()\n\n        # Re-purpose Python's builtin syntax error formatting.\n        output = traceback.format_exception_only(\n            SyntaxError,\n            SyntaxError(self.msg, (self.filename, self.lineno, self.offset,\n                                   self.text)))\n\n        arrow_idx, _ = next(((i, x) for i, x in enumerate(output)\n                             if x.strip() == '^'),\n                            (None, None))\n        if arrow_idx:\n            msg_idx = arrow_idx + 1\n        else:\n            msg_idx, _ = next((i, x) for i, x in enumerate(output)\n                              if x.startswith('SyntaxError: '))\n\n        # Get rid of erroneous error-type label.\n        output[msg_idx] = re.sub('^SyntaxError: ', '', output[msg_idx])\n\n        # Extend the text arrow, when given enough source info.\n        if arrow_idx and self.arrow_offset:\n            output[arrow_idx] = '{}{}^\\n'.format(output[arrow_idx].rstrip('\\n'),\n                                                 '-' * (self.arrow_offset - 1))\n\n        if COLORED:\n            output[msg_idx:] = [Fore.YELLOW + o + Fore.RESET for o in output[msg_idx:]]\n            if arrow_idx:\n                output[arrow_idx] = Fore.GREEN + output[arrow_idx] + Fore.RESET\n            for idx, line in enumerate(output[::msg_idx]):\n                if line.strip().startswith(\n                        'File \"{}\", line'.format(self.filename)):\n                    output[idx] = Fore.RED + line + Fore.RESET\n\n        # This resulting string will come after a \"<class-name>:\" prompt, so\n        # put it down a line.\n        output.insert(0, '\\n')\n\n        # Avoid \"...expected str instance, ColoredString found\"\n        return reduce(lambda x, y: x + y, output)\n\n\nclass HyCompileError(HyInternalError):\n    \"\"\"Unexpected errors occurring within the compiler.\"\"\"\n\n\nclass HyTypeError(HyLanguageError, TypeError):\n    \"\"\"TypeError occurring during the normal use of Hy.\"\"\"\n\n\nclass HyNameError(HyLanguageError, NameError):\n    \"\"\"NameError occurring during the normal use of Hy.\"\"\"\n\n\nclass HyRequireError(HyLanguageError):\n    \"\"\"Errors arising during the use of `require`\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyMacroExpansionError(HyLanguageError):\n    \"\"\"Errors caused by invalid use of Hy macros.\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyEvalError(HyLanguageError):\n    \"\"\"Errors occurring during code evaluation at compile-time.\n\n    These errors distinguish unexpected errors within the compilation process\n    (i.e. `HyInternalError`s) from unrelated errors in user code evaluated by\n    the compiler (e.g. in `eval-and-compile`).\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyIOError(HyInternalError, IOError):\n    \"\"\" Subclass used to distinguish between IOErrors raised by Hy itself as\n    opposed to Hy programs.\n    \"\"\"\n\n\nclass HySyntaxError(HyLanguageError, SyntaxError):\n    \"\"\"Error during the Lexing of a Hython expression.\"\"\"\n\n\nclass HyWrapperError(HyError, TypeError):\n    \"\"\"Errors caused by language model object wrapping.\n\n    These can be caused by improper user-level use of a macro, so they're\n    not really \"internal\".  If they arise due to anything else, they're an\n    internal/compiler problem, though.\n    \"\"\"\n\n\ndef _module_filter_name(module_name):\n    try:\n        compiler_loader = pkgutil.get_loader(module_name)\n        if not compiler_loader:\n            return None\n\n        filename = compiler_loader.get_filename(module_name)\n        if not filename:\n            return None\n\n        if compiler_loader.is_package(module_name):\n            # Use the package directory (e.g. instead of `.../__init__.py`) so\n            # that we can filter all modules in a package.\n            return os.path.dirname(filename)\n        else:\n            # Normalize filename endings, because tracebacks will use `pyc` when\n            # the loader says `py`.\n            return filename.replace('.pyc', '.py')\n    except Exception:\n        return None\n\n\n_tb_hidden_modules = {m for m in map(_module_filter_name,\n                                     ['hy.compiler', 'hy.lex',\n                                      'hy.cmdline', 'hy.lex.parser',\n                                      'hy.importer', 'hy._compat',\n                                      'hy.macros', 'hy.models',\n                                      'hy.core.result_macros',\n                                      'rply'])\n                      if m is not None}\n\n\ndef hy_exc_filter(exc_type, exc_value, exc_traceback):\n    \"\"\"Produce exceptions print-outs with all frames originating from the\n    modules in `_tb_hidden_modules` filtered out.\n\n    The frames are actually filtered by each module's filename and only when a\n    subclass of `HyLanguageError` is emitted.\n\n    This does not remove the frames from the actual tracebacks, so debugging\n    will show everything.\n    \"\"\"\n    # frame = (filename, line number, function name*, text)\n    new_tb = []\n    for frame in traceback.extract_tb(exc_traceback):\n        if not (frame[0].replace('.pyc', '.py') in _tb_hidden_modules or\n                os.path.dirname(frame[0]) in _tb_hidden_modules):\n            new_tb += [frame]\n\n    lines = traceback.format_list(new_tb)\n\n    lines.insert(0, \"Traceback (most recent call last):\\n\")\n\n    lines.extend(traceback.format_exception_only(exc_type, exc_value))\n    output = ''.join(lines)\n\n    return output\n\n\ndef hy_exc_handler(exc_type, exc_value, exc_traceback):\n    \"\"\"A `sys.excepthook` handler that uses `hy_exc_filter` to\n    remove internal Hy frames from a traceback print-out.\n    \"\"\"\n    if os.environ.get('HY_DEBUG', False):\n        return sys.__excepthook__(exc_type, exc_value, exc_traceback)\n\n    try:\n        output = hy_exc_filter(exc_type, exc_value, exc_traceback)\n        sys.stderr.write(output)\n        sys.stderr.flush()\n    except Exception:\n        sys.__excepthook__(exc_type, exc_value, exc_traceback)\n\n\n@contextmanager\ndef filtered_hy_exceptions():\n    \"\"\"Temporarily apply a `sys.excepthook` that filters Hy internal frames\n    from tracebacks.\n\n    Filtering can be controlled by the variable\n    `hy.errors._hy_filter_internal_errors` and environment variable\n    `HY_FILTER_INTERNAL_ERRORS`.\n    \"\"\"\n    global _hy_filter_internal_errors\n    if _hy_filter_internal_errors:\n        current_hook = sys.excepthook\n        sys.excepthook = hy_exc_handler\n        yield\n        sys.excepthook = current_hook\n    else:\n        yield\n", "path": "hy/errors.py"}, {"content": "import sys\n\nPY3_7 = sys.version_info >= (3, 7)\nPY3_8 = sys.version_info >= (3, 8)\nPY3_9 = sys.version_info >= (3, 9)\nPY3_10 = sys.version_info >= (3, 10)\n\n\nif not PY3_9:\n    # Shim `ast.unparse`.\n    import ast, astor.code_gen\n    ast.unparse = astor.code_gen.to_source\n\n\nif not PY3_7:\n    # Shim `asyncio.run`.\n    import asyncio\n    def f(coro):\n        return asyncio.get_event_loop().run_until_complete(coro)\n    asyncio.run = f\n", "path": "hy/_compat.py"}], "after_files": [{"content": "import os\nimport re\nimport sys\nimport traceback\nimport pkgutil\n\nfrom functools import reduce\nfrom colorama import Fore\nfrom contextlib import contextmanager\nfrom hy import _initialize_env_var\nfrom hy._compat import PYPY\n\n_hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',\n                                                 True)\nCOLORED = _initialize_env_var('HY_COLORED_ERRORS', False)\n\n\nclass HyError(Exception):\n    pass\n\n\nclass HyInternalError(HyError):\n    \"\"\"Unexpected errors occurring during compilation or parsing of Hy code.\n\n    Errors sub-classing this are not intended to be user-facing, and will,\n    hopefully, never be seen by users!\n    \"\"\"\n\n\nclass HyLanguageError(HyError):\n    \"\"\"Errors caused by invalid use of the Hy language.\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n    def __init__(self, message, expression=None, filename=None, source=None,\n                 lineno=1, colno=1):\n        \"\"\"\n        Parameters\n        ----------\n        message: str\n            The message to display for this error.\n        expression: HyObject, optional\n            The Hy expression generating this error.\n        filename: str, optional\n            The filename for the source code generating this error.\n            Expression-provided information will take precedence of this value.\n        source: str, optional\n            The actual source code generating this error.  Expression-provided\n            information will take precedence of this value.\n        lineno: int, optional\n            The line number of the error.  Expression-provided information will\n            take precedence of this value.\n        colno: int, optional\n            The column number of the error.  Expression-provided information\n            will take precedence of this value.\n        \"\"\"\n        self.msg = message\n        self.compute_lineinfo(expression, filename, source, lineno, colno)\n\n        if isinstance(self, SyntaxError):\n            syntax_error_args = (self.filename, self.lineno, self.offset,\n                                 self.text)\n            super(HyLanguageError, self).__init__(message, syntax_error_args)\n        else:\n            super(HyLanguageError, self).__init__(message)\n\n    def compute_lineinfo(self, expression, filename, source, lineno, colno):\n\n        # NOTE: We use `SyntaxError`'s field names (i.e. `text`, `offset`,\n        # `msg`) for compatibility and print-outs.\n        self.text = getattr(expression, 'source', source)\n        self.filename = getattr(expression, 'filename', filename)\n\n        if self.text:\n            lines = self.text.splitlines()\n\n            self.lineno = getattr(expression, 'start_line', lineno)\n            self.offset = getattr(expression, 'start_column', colno)\n            end_column = getattr(expression, 'end_column',\n                                 len(lines[self.lineno-1]))\n            end_line = getattr(expression, 'end_line', self.lineno)\n\n            # Trim the source down to the essentials.\n            self.text = '\\n'.join(lines[self.lineno-1:end_line])\n\n            if end_column:\n                if self.lineno == end_line:\n                    self.arrow_offset = end_column\n                else:\n                    self.arrow_offset = len(self.text[0])\n\n                self.arrow_offset -= self.offset\n            else:\n                self.arrow_offset = None\n        else:\n            # We could attempt to extract the source given a filename, but we\n            # don't.\n            self.lineno = lineno\n            self.offset = colno\n            self.arrow_offset = None\n\n    def __str__(self):\n        \"\"\"Provide an exception message that includes SyntaxError-like source\n        line information when available.\n        \"\"\"\n        # Syntax errors are special and annotate the traceback (instead of what\n        # we would do in the message that follows the traceback).\n        if isinstance(self, SyntaxError):\n            return super(HyLanguageError, self).__str__()\n        # When there isn't extra source information, use the normal message.\n        elif not self.text:\n            return super(HyLanguageError, self).__str__()\n\n        # Re-purpose Python's builtin syntax error formatting.\n        output = traceback.format_exception_only(\n            SyntaxError,\n            SyntaxError(self.msg, (self.filename, self.lineno, self.offset,\n                                   self.text)))\n\n        arrow_idx, _ = next(((i, x) for i, x in enumerate(output)\n                             if x.strip() == '^'),\n                            (None, None))\n        if arrow_idx:\n            msg_idx = arrow_idx + 1\n        else:\n            msg_idx, _ = next((i, x) for i, x in enumerate(output)\n                              if x.startswith('SyntaxError: '))\n\n        # Get rid of erroneous error-type label.\n        output[msg_idx] = re.sub('^SyntaxError: ', '', output[msg_idx])\n\n        # Extend the text arrow, when given enough source info.\n        if arrow_idx and self.arrow_offset:\n            output[arrow_idx] = '{}{}^\\n'.format(output[arrow_idx].rstrip('\\n'),\n                                                 '-' * (self.arrow_offset - 1))\n\n        if COLORED:\n            output[msg_idx:] = [Fore.YELLOW + o + Fore.RESET for o in output[msg_idx:]]\n            if arrow_idx:\n                output[arrow_idx] = Fore.GREEN + output[arrow_idx] + Fore.RESET\n            for idx, line in enumerate(output[::msg_idx]):\n                if line.strip().startswith(\n                        'File \"{}\", line'.format(self.filename)):\n                    output[idx] = Fore.RED + line + Fore.RESET\n\n        # This resulting string will come after a \"<class-name>:\" prompt, so\n        # put it down a line.\n        output.insert(0, '\\n')\n\n        # Avoid \"...expected str instance, ColoredString found\"\n        return reduce(lambda x, y: x + y, output)\n\n\nclass HyCompileError(HyInternalError):\n    \"\"\"Unexpected errors occurring within the compiler.\"\"\"\n\n\nclass HyTypeError(HyLanguageError, TypeError):\n    \"\"\"TypeError occurring during the normal use of Hy.\"\"\"\n\n\nclass HyNameError(HyLanguageError, NameError):\n    \"\"\"NameError occurring during the normal use of Hy.\"\"\"\n\n\nclass HyRequireError(HyLanguageError):\n    \"\"\"Errors arising during the use of `require`\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyMacroExpansionError(HyLanguageError):\n    \"\"\"Errors caused by invalid use of Hy macros.\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyEvalError(HyLanguageError):\n    \"\"\"Errors occurring during code evaluation at compile-time.\n\n    These errors distinguish unexpected errors within the compilation process\n    (i.e. `HyInternalError`s) from unrelated errors in user code evaluated by\n    the compiler (e.g. in `eval-and-compile`).\n\n    This, and any errors inheriting from this, are user-facing.\n    \"\"\"\n\n\nclass HyIOError(HyInternalError, IOError):\n    \"\"\" Subclass used to distinguish between IOErrors raised by Hy itself as\n    opposed to Hy programs.\n    \"\"\"\n\n\nclass HySyntaxError(HyLanguageError, SyntaxError):\n    \"\"\"Error during the Lexing of a Hython expression.\"\"\"\n\n\nclass HyWrapperError(HyError, TypeError):\n    \"\"\"Errors caused by language model object wrapping.\n\n    These can be caused by improper user-level use of a macro, so they're\n    not really \"internal\".  If they arise due to anything else, they're an\n    internal/compiler problem, though.\n    \"\"\"\n\n\ndef _module_filter_name(module_name):\n    try:\n        compiler_loader = pkgutil.get_loader(module_name)\n        if not compiler_loader:\n            return None\n\n        filename = compiler_loader.get_filename(module_name)\n        if not filename:\n            return None\n\n        if compiler_loader.is_package(module_name):\n            # Use the package directory (e.g. instead of `.../__init__.py`) so\n            # that we can filter all modules in a package.\n            return os.path.dirname(filename)\n        else:\n            # Normalize filename endings, because tracebacks will use `pyc` when\n            # the loader says `py`.\n            return filename.replace('.pyc', '.py')\n    except Exception:\n        return None\n\n\n_tb_hidden_modules = {m for m in map(_module_filter_name,\n                                     ['hy.compiler', 'hy.lex',\n                                      'hy.cmdline', 'hy.lex.parser',\n                                      'hy.importer', 'hy._compat',\n                                      'hy.macros', 'hy.models',\n                                      'hy.core.result_macros',\n                                      'rply'])\n                      if m is not None}\n\n# We can't derive these easily from just their module names due\n# to missing magic attributes in internal importlib modules\n_tb_hidden_modules.update(\n    f\"<builtin>/frozen {x}\" if PYPY else f\"<frozen {x}>\"\n    for x in (\"importlib._bootstrap\", \"importlib._bootstrap_external\")\n)\n\n\ndef hy_exc_filter(exc_type, exc_value, exc_traceback):\n    \"\"\"Produce exceptions print-outs with all frames originating from the\n    modules in `_tb_hidden_modules` filtered out.\n\n    The frames are actually filtered by each module's filename and only when a\n    subclass of `HyLanguageError` is emitted.\n\n    This does not remove the frames from the actual tracebacks, so debugging\n    will show everything.\n    \"\"\"\n    # frame = (filename, line number, function name*, text)\n    new_tb = []\n    for frame in traceback.extract_tb(exc_traceback):\n        if not (frame[0].replace('.pyc', '.py') in _tb_hidden_modules or\n                os.path.dirname(frame[0]) in _tb_hidden_modules):\n            new_tb += [frame]\n\n    lines = traceback.format_list(new_tb)\n\n    lines.insert(0, \"Traceback (most recent call last):\\n\")\n\n    lines.extend(traceback.format_exception_only(exc_type, exc_value))\n    output = ''.join(lines)\n\n    return output\n\n\ndef hy_exc_handler(exc_type, exc_value, exc_traceback):\n    \"\"\"A `sys.excepthook` handler that uses `hy_exc_filter` to\n    remove internal Hy frames from a traceback print-out.\n    \"\"\"\n    if os.environ.get('HY_DEBUG', False):\n        return sys.__excepthook__(exc_type, exc_value, exc_traceback)\n\n    try:\n        output = hy_exc_filter(exc_type, exc_value, exc_traceback)\n        sys.stderr.write(output)\n        sys.stderr.flush()\n    except Exception:\n        sys.__excepthook__(exc_type, exc_value, exc_traceback)\n\n\n@contextmanager\ndef filtered_hy_exceptions():\n    \"\"\"Temporarily apply a `sys.excepthook` that filters Hy internal frames\n    from tracebacks.\n\n    Filtering can be controlled by the variable\n    `hy.errors._hy_filter_internal_errors` and environment variable\n    `HY_FILTER_INTERNAL_ERRORS`.\n    \"\"\"\n    global _hy_filter_internal_errors\n    if _hy_filter_internal_errors:\n        current_hook = sys.excepthook\n        sys.excepthook = hy_exc_handler\n        yield\n        sys.excepthook = current_hook\n    else:\n        yield\n", "path": "hy/errors.py"}, {"content": "import sys\nimport platform\n\nPY3_7 = sys.version_info >= (3, 7)\nPY3_8 = sys.version_info >= (3, 8)\nPY3_9 = sys.version_info >= (3, 9)\nPY3_10 = sys.version_info >= (3, 10)\nPYPY = platform.python_implementation() == \"PyPy\"\n\n\nif not PY3_9:\n    # Shim `ast.unparse`.\n    import ast, astor.code_gen\n    ast.unparse = astor.code_gen.to_source\n\n\nif not PY3_7:\n    # Shim `asyncio.run`.\n    import asyncio\n    def f(coro):\n        return asyncio.get_event_loop().run_until_complete(coro)\n    asyncio.run = f\n", "path": "hy/_compat.py"}]}