"""The parts of a file that given lines lie in, by the names a prediction uses for them. Where each language's boundaries come from: - Python, a path ending .py: the standard `ast` module. A part is a function or class, named with the classes and functions around it, as in `Plan.branch`; a top-level assignment, by the name it sets; or `(module)` for any other top-level line. - Markdown, a path ending .md: the heading lines outside fenced code. A part is the nearest heading above, spelt as its line, as in `## Goals`; `(top)` before the first. - Any other file, and Python that doesn't parse: no names, so diff_parts falls back to line ranges.""" import ast import re import typing MODULE = "(module)" TOP = "(top)" HEADING = re.compile(r"#{1,6} \S") FENCE = re.compile(r" {0,3}(```|~~~)") DEFINITION = ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef def part_names(path: str, text: str, lines: typing.Iterable[int]) -> set[str] | None: """The part each of lines, counted from 1, lies in; None where the file's kind has no names.""" if path.endswith(".py"): return python_parts(text, lines) if path.endswith(".md"): return markdown_parts(text, lines) return None def python_parts(text: str, lines: typing.Iterable[int]) -> set[str] | None: try: tree = ast.parse(text) except (SyntaxError, ValueError): return None if not tree.body: return {MODULE} # Each top-level statement's first and last line, then each part's with its name. statements = [(first_line(statement), statement.end_lineno or statement.lineno) for statement in tree.body] spans = [(*lines_, assigned(statement)) for lines_, statement in zip(statements, tree.body) if not isinstance(statement, DEFINITION)] spans.extend(nested(tree, "")) def name(line: int) -> str: # A line between two statements, such as a comment, goes with the one below it; one after the last, with the last. if not any(first <= line <= last for first, last in statements): line = min((first for first, _ in statements if first > line), default=statements[-1][0]) return max((span for span in spans if span[0] <= line <= span[1]), key=lambda span: span[0])[2] return {name(line) for line in lines} def nested(node: ast.AST, prefix: str) -> list[tuple[int, int, str]]: """Each function and class under node, at any depth, named from prefix.""" found = [] for child in ast.iter_child_nodes(node): if isinstance(child, DEFINITION): found.append((first_line(child), child.end_lineno or child.lineno, prefix + child.name)) found.extend(nested(child, f"{prefix}{child.name}.")) else: found.extend(nested(child, prefix)) return found def first_line(statement: ast.stmt) -> int: """A statement's first line, which is its first decorator's where it has one.""" return min([statement.lineno, *(decorator.lineno for decorator in getattr(statement, "decorator_list", []))]) def assigned(statement: ast.stmt) -> str: """The part a top-level statement that is no function or class makes: the one name it assigns, else the module.""" targets = statement.targets if isinstance(statement, ast.Assign) else [statement.target] if isinstance(statement, ast.AnnAssign) else [] return targets[0].id if len(targets) == 1 and isinstance(targets[0], ast.Name) else MODULE def markdown_parts(text: str, lines: typing.Iterable[int]) -> set[str]: wanted, names = set(lines), set() heading, fenced = TOP, False for number, line in enumerate(text.splitlines(), 1): if FENCE.match(line): fenced = not fenced elif not fenced and HEADING.match(line): heading = line.rstrip() if number in wanted: names.add(heading) # A line past the end, as a deletion at the end names, lies under the last heading. return names | ({heading} if any(line > len(text.splitlines()) for line in wanted) else set())