|
| 1 | +import re |
| 2 | +from functools import reduce |
| 3 | +from typing import List, Optional, Tuple |
| 4 | + |
| 5 | +from .ast import Location |
| 6 | +from .location import SourceLocation, get_location |
| 7 | +from .source import Source |
| 8 | + |
| 9 | + |
| 10 | +__all__ = ["print_location", "print_source_location"] |
| 11 | + |
| 12 | + |
| 13 | +def print_location(location: Location) -> str: |
| 14 | + """Render a helpful description of the location in the GraphQL Source document.""" |
| 15 | + return print_source_location( |
| 16 | + location.source, get_location(location.source, location.start) |
| 17 | + ) |
| 18 | + |
| 19 | + |
| 20 | +_re_newline = re.compile(r"\r\n|[\n\r]") |
| 21 | + |
| 22 | + |
| 23 | +def print_source_location(source: Source, source_location: SourceLocation) -> str: |
| 24 | + """Render a helpful description of the location in the GraphQL Source document.""" |
| 25 | + first_line_column_offset = source.location_offset.column - 1 |
| 26 | + body = " " * first_line_column_offset + source.body |
| 27 | + |
| 28 | + line_index = source_location.line - 1 |
| 29 | + line_offset = source.location_offset.line - 1 |
| 30 | + line_num = source_location.line + line_offset |
| 31 | + |
| 32 | + column_offset = first_line_column_offset if source_location.line == 1 else 0 |
| 33 | + column_num = source_location.column + column_offset |
| 34 | + |
| 35 | + lines = _re_newline.split(body) # works a bit different from splitlines() |
| 36 | + len_lines = len(lines) |
| 37 | + |
| 38 | + def get_line(index: int) -> Optional[str]: |
| 39 | + return lines[index] if 0 <= index < len_lines else None |
| 40 | + |
| 41 | + return f"{source.name}:{line_num}:{column_num}\n" + print_prefixed_lines( |
| 42 | + [ |
| 43 | + (f"{line_num - 1}: ", get_line(line_index - 1)), |
| 44 | + (f"{line_num}: ", get_line(line_index)), |
| 45 | + ("", " " * (column_num - 1) + "^"), |
| 46 | + (f"{line_num + 1}: ", get_line(line_index + 1)), |
| 47 | + ] |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def print_prefixed_lines(lines: List[Tuple[str, Optional[str]]]) -> str: |
| 52 | + """Print lines specified like this: ["prefix", "string"]""" |
| 53 | + existing_lines = [line for line in lines if line[1] is not None] |
| 54 | + pad_len = reduce(lambda pad, line: max(pad, len(line[0])), existing_lines, 0) |
| 55 | + return "\n".join( |
| 56 | + map( |
| 57 | + lambda line: line[0].rjust(pad_len) + line[1], existing_lines # type:ignore |
| 58 | + ) |
| 59 | + ) |
0 commit comments