source_map.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Defines source maps: dictionaries that map lines in generated source to debug information."""
  2. class SourceMap(object):
  3. """A source map, which converts generated source lines to debug information."""
  4. def __init__(self):
  5. self.lines = {}
  6. def map_line(self, line_number, debug_info):
  7. """Assigns the given debug information to the given line."""
  8. self.lines[line_number] = debug_info
  9. def get_debug_info(self, line_number):
  10. """Gets the debug information for the given line number, or None if no debug info was
  11. found."""
  12. return self.lines[line_number]
  13. def __str__(self):
  14. return '\n'.join(
  15. ['%d: %s' % pair
  16. for pair in sorted(self.lines.items(), key=lambda (key, _): key)])
  17. class SourceMapBuilder(object):
  18. """A type of object that makes it easy to build source maps for hierarchical instructions."""
  19. def __init__(self, initial_line_number=0):
  20. self.source_map = SourceMap()
  21. self.debug_info_stack = []
  22. self.line_number = initial_line_number - 1
  23. def push_debug_info(self, debug_info):
  24. """Informs the source map that subsequent lines of code will have the given debug
  25. information associated with them."""
  26. self.debug_info_stack.append(debug_info)
  27. def pop_debug_info(self):
  28. """Informs the source map that the debug information that was pushed last should
  29. be discarded in favor of the debug information that was pushed onto the stack
  30. just prior to it."""
  31. return self.debug_info_stack.pop()
  32. def append_line(self):
  33. """Has the source map builder increment its line number counter, and assigns the debug
  34. information that is at the top of the debug information stack to that line."""
  35. self.line_number += 1
  36. if len(self.debug_info_stack) > 0:
  37. self.source_map.map_line(self.line_number, self.debug_info_stack[-1])
  38. def __str__(self):
  39. return str(self.source_map)