Yield (name, start_line, end_line) for each function in a C file. 1-indexed and inclusive. Deliberately simple: this codebase is clang-formatted, so a definition starts at column 0 and its body brace opens at nesting depth 0. Constructs whose declaration has no '(' before the brace
(path)
| 86 | |
| 87 | |
| 88 | def function_spans(path): |
| 89 | """Yield (name, start_line, end_line) for each function in a C file. |
| 90 | |
| 91 | 1-indexed and inclusive. Deliberately simple: this codebase is |
| 92 | clang-formatted, so a definition starts at column 0 and its body brace |
| 93 | opens at nesting depth 0. Constructs whose declaration has no '(' before |
| 94 | the brace (structs, enums, initializers) are skipped. |
| 95 | """ |
| 96 | src = path.read_text(encoding="utf-8", errors="replace") |
| 97 | lines = src.splitlines() |
| 98 | clean = strip_noise(src).splitlines() |
| 99 | |
| 100 | depth = 0 |
| 101 | decl_start = 0 |
| 102 | for idx, line in enumerate(clean): |
| 103 | if depth == 0 and line[:1] not in ("", " ", "\t", "#"): |
| 104 | # Candidate start of a top-level declaration. |
| 105 | if idx == 0 or clean[idx - 1].strip() == "" or clean[idx - 1].rstrip().endswith(("}", ";")): |
| 106 | decl_start = idx |
| 107 | opened = line.count("{") |
| 108 | closed = line.count("}") |
| 109 | if depth == 0 and opened: |
| 110 | decl_text = " ".join(clean[decl_start:idx + 1]) |
| 111 | head = decl_text.split("{", 1)[0] |
| 112 | if "(" in head: |
| 113 | name_match = None |
| 114 | for m in re.finditer(r"([A-Za-z_]\w*)\s*\(", head): |
| 115 | name_match = m |
| 116 | break |
| 117 | if name_match: |
| 118 | body_start = decl_start |
| 119 | d = depth + opened - closed |
| 120 | if d > 0: |
| 121 | end = idx |
| 122 | j = idx |
| 123 | while j + 1 < len(clean) and d > 0: |
| 124 | j += 1 |
| 125 | d += clean[j].count("{") - clean[j].count("}") |
| 126 | end = j |
| 127 | yield (name_match.group(1), body_start + 1, end + 1, |
| 128 | "\n".join(l.rstrip() for l in lines[body_start:end + 1])) |
| 129 | depth += opened - closed |
| 130 | if depth < 0: |
| 131 | depth = 0 |
| 132 | |
| 133 | |
| 134 | def enclosing(path, line): |
no test coverage detected