MCPcopy Index your code
hub / github.com/RustPython/RustPython / _extract_caret_anchors_from_line_segment

Function _extract_caret_anchors_from_line_segment

Lib/traceback.py:812–956  ·  view source on GitHub ↗

Given source code `segment` corresponding to a FrameSummary, determine: - for binary ops, the location of the binary op - for indexing and function calls, the location of the brackets. `segment` is expected to be a valid Python expression.

(segment)

Source from the content-addressed store, hash-verified

810)
811
812def _extract_caret_anchors_from_line_segment(segment):
813 """
814 Given source code `segment` corresponding to a FrameSummary, determine:
815 - for binary ops, the location of the binary op
816 - for indexing and function calls, the location of the brackets.
817 `segment` is expected to be a valid Python expression.
818 """
819 import ast
820
821 try:
822 # Without parentheses, `segment` is parsed as a statement.
823 # Binary ops, subscripts, and calls are expressions, so
824 # we can wrap them with parentheses to parse them as
825 # (possibly multi-line) expressions.
826 # e.g. if we try to highlight the addition in
827 # x = (
828 # a +
829 # b
830 # )
831 # then we would ast.parse
832 # a +
833 # b
834 # which is not a valid statement because of the newline.
835 # Adding brackets makes it a valid expression.
836 # (
837 # a +
838 # b
839 # )
840 # Line locations will be different than the original,
841 # which is taken into account later on.
842 tree = ast.parse(f"(\n{segment}\n)")
843 except SyntaxError:
844 return None
845
846 if len(tree.body) != 1:
847 return None
848
849 lines = segment.splitlines()
850
851 def normalize(lineno, offset):
852 """Get character index given byte offset"""
853 return _byte_offset_to_character_offset(lines[lineno], offset)
854
855 def next_valid_char(lineno, col):
856 """Gets the next valid character index in `lines`, if
857 the current location is not valid. Handles empty lines.
858 """
859 while lineno < len(lines) and col >= len(lines[lineno]):
860 col = 0
861 lineno += 1
862 assert lineno < len(lines) and col < len(lines[lineno])
863 return lineno, col
864
865 def increment(lineno, col):
866 """Get the next valid character index in `lines`."""
867 col += 1
868 lineno, col = next_valid_char(lineno, col)
869 return lineno, col

Callers 1

format_frame_summaryMethod · 0.85

Calls 7

lenFunction · 0.85
setup_positionsFunction · 0.85
increment_untilFunction · 0.85
normalizeFunction · 0.70
parseMethod · 0.45
splitlinesMethod · 0.45
isspaceMethod · 0.45

Tested by

no test coverage detected