debug.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import sys
  2. import typing as t
  3. from types import CodeType
  4. from types import TracebackType
  5. from .exceptions import TemplateSyntaxError
  6. from .utils import internal_code
  7. from .utils import missing
  8. if t.TYPE_CHECKING:
  9. from .runtime import Context
  10. def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:
  11. """Rewrite the current exception to replace any tracebacks from
  12. within compiled template code with tracebacks that look like they
  13. came from the template source.
  14. This must be called within an ``except`` block.
  15. :param source: For ``TemplateSyntaxError``, the original source if
  16. known.
  17. :return: The original exception with the rewritten traceback.
  18. """
  19. _, exc_value, tb = sys.exc_info()
  20. exc_value = t.cast(BaseException, exc_value)
  21. tb = t.cast(TracebackType, tb)
  22. if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:
  23. exc_value.translated = True
  24. exc_value.source = source
  25. # Remove the old traceback, otherwise the frames from the
  26. # compiler still show up.
  27. exc_value.with_traceback(None)
  28. # Outside of runtime, so the frame isn't executing template
  29. # code, but it still needs to point at the template.
  30. tb = fake_traceback(
  31. exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
  32. )
  33. else:
  34. # Skip the frame for the render function.
  35. tb = tb.tb_next
  36. stack = []
  37. # Build the stack of traceback object, replacing any in template
  38. # code with the source file and line information.
  39. while tb is not None:
  40. # Skip frames decorated with @internalcode. These are internal
  41. # calls that aren't useful in template debugging output.
  42. if tb.tb_frame.f_code in internal_code:
  43. tb = tb.tb_next
  44. continue
  45. template = tb.tb_frame.f_globals.get("__jinja_template__")
  46. if template is not None:
  47. lineno = template.get_corresponding_lineno(tb.tb_lineno)
  48. fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)
  49. stack.append(fake_tb)
  50. else:
  51. stack.append(tb)
  52. tb = tb.tb_next
  53. tb_next = None
  54. # Assign tb_next in reverse to avoid circular references.
  55. for tb in reversed(stack):
  56. tb.tb_next = tb_next
  57. tb_next = tb
  58. return exc_value.with_traceback(tb_next)
  59. def fake_traceback( # type: ignore
  60. exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int
  61. ) -> TracebackType:
  62. """Produce a new traceback object that looks like it came from the
  63. template source instead of the compiled code. The filename, line
  64. number, and location name will point to the template, and the local
  65. variables will be the current template context.
  66. :param exc_value: The original exception to be re-raised to create
  67. the new traceback.
  68. :param tb: The original traceback to get the local variables and
  69. code info from.
  70. :param filename: The template filename.
  71. :param lineno: The line number in the template source.
  72. """
  73. if tb is not None:
  74. # Replace the real locals with the context that would be
  75. # available at that point in the template.
  76. locals = get_template_locals(tb.tb_frame.f_locals)
  77. locals.pop("__jinja_exception__", None)
  78. else:
  79. locals = {}
  80. globals = {
  81. "__name__": filename,
  82. "__file__": filename,
  83. "__jinja_exception__": exc_value,
  84. }
  85. # Raise an exception at the correct line number.
  86. code: CodeType = compile(
  87. "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"
  88. )
  89. # Build a new code object that points to the template file and
  90. # replaces the location with a block name.
  91. location = "template"
  92. if tb is not None:
  93. function = tb.tb_frame.f_code.co_name
  94. if function == "root":
  95. location = "top-level template code"
  96. elif function.startswith("block_"):
  97. location = f"block {function[6:]!r}"
  98. if sys.version_info >= (3, 8):
  99. code = code.replace(co_name=location)
  100. else:
  101. code = CodeType(
  102. code.co_argcount,
  103. code.co_kwonlyargcount,
  104. code.co_nlocals,
  105. code.co_stacksize,
  106. code.co_flags,
  107. code.co_code,
  108. code.co_consts,
  109. code.co_names,
  110. code.co_varnames,
  111. code.co_filename,
  112. location,
  113. code.co_firstlineno,
  114. code.co_lnotab,
  115. code.co_freevars,
  116. code.co_cellvars,
  117. )
  118. # Execute the new code, which is guaranteed to raise, and return
  119. # the new traceback without this frame.
  120. try:
  121. exec(code, globals, locals)
  122. except BaseException:
  123. return sys.exc_info()[2].tb_next # type: ignore
  124. def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:
  125. """Based on the runtime locals, get the context that would be
  126. available at that point in the template.
  127. """
  128. # Start with the current template context.
  129. ctx: "t.Optional[Context]" = real_locals.get("context")
  130. if ctx is not None:
  131. data: t.Dict[str, t.Any] = ctx.get_all().copy()
  132. else:
  133. data = {}
  134. # Might be in a derived context that only sets local variables
  135. # rather than pushing a context. Local variables follow the scheme
  136. # l_depth_name. Find the highest-depth local that has a value for
  137. # each name.
  138. local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}
  139. for name, value in real_locals.items():
  140. if not name.startswith("l_") or value is missing:
  141. # Not a template variable, or no longer relevant.
  142. continue
  143. try:
  144. _, depth_str, name = name.split("_", 2)
  145. depth = int(depth_str)
  146. except ValueError:
  147. continue
  148. cur_depth = local_overrides.get(name, (-1,))[0]
  149. if cur_depth < depth:
  150. local_overrides[name] = (depth, value)
  151. # Modify the context with any derived context.
  152. for name, (_, value) in local_overrides.items():
  153. if value is missing:
  154. data.pop(name, None)
  155. else:
  156. data[name] = value
  157. return data