diff mbox series

utils/better_compile: Fix error handler when exception lacks valid lineno

Message ID 20261201200657.107980-1-mark.asselstine@windriver.com
State New
Headers show
Series utils/better_compile: Fix error handler when exception lacks valid lineno | expand

Commit Message

Mark Asselstine Dec. 1, 2026, 8:06 p.m. UTC
The error handler in better_compile() accessed e.lineno before checking
that the exception has one. compile() normally raises SyntaxError or
IndentationError, which have lineno, but other exceptions such as
ValueError or TypeError do not, causing an AttributeError in the
handler itself. A SyntaxError can also have lineno set to None, which
will cause a TypeError in e.lineno - lineno.

For example, on Python 3.12 or later the following code should show
lineno set to None:

  python3 -c "
  try: compile('x=1\0','f','exec')
  except SyntaxError as e: print(e.lineno)"

Only use e.lineno when it is present and not None, and otherwise report
the error without a line number and print the whole function.

Signed-off-by: Mark Asselstine <mark.asselstine@windriver.com>
---
 lib/bb/utils.py | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
diff mbox series

Patch

diff --git a/lib/bb/utils.py b/lib/bb/utils.py
index 046bf4b8b..7ee0479aa 100644
--- a/lib/bb/utils.py
+++ b/lib/bb/utils.py
@@ -379,14 +379,15 @@  def better_compile(text, file, realfile, mode = "exec", lineno = 0):
         error = []
         # split the text into lines again
         body = text.split('\n')
-        error.append("Error in compiling python function in %s, line %s:\n" % (realfile, e.lineno))
-        if hasattr(e, "lineno"):
+        if getattr(e, "lineno", None) is not None:
+            error.append("Error in compiling python function in %s, line %s:\n" % (realfile, e.lineno))
             error.append("The code lines resulting in this error were:")
             # e.lineno: line's position in reaflile
             # lineno: function name's "position -1" in realfile
             # e.lineno - lineno: line's relative position in function
             error.extend(_print_trace(body, e.lineno - lineno))
         else:
+            error.append("Error in compiling python function in %s:\n" % realfile)
             error.append("The function causing this error was:")
             for line in body:
                 error.append(line)