|
| 1 | +"""Deterministic R extraction shared with Compass. |
| 2 | +
|
| 3 | +R is intentionally source-driven: Graphify does not require an optional R |
| 4 | +grammar at runtime, while Compass keeps its grammar bundle static. Keeping the |
| 5 | +small structural contract here avoids a classified-as-code file disappearing |
| 6 | +from one implementation while preserving the useful R relationships: package |
| 7 | +imports, named functions, and direct calls between local functions. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import re |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +from graphify.extractors.base import _file_stem, _make_id |
| 15 | + |
| 16 | +_FUNCTION = re.compile( |
| 17 | + r"(?m)^[ \t]*([A-Za-z.][A-Za-z0-9._]*)[ \t]*(?:<<-|<-|=)[ \t]*function[ \t]*\(" |
| 18 | +) |
| 19 | +_IMPORT = re.compile( |
| 20 | + r"(?m)^[ \t]*(?:library|require|requireNamespace)[ \t]*\(" |
| 21 | +) |
| 22 | +_PACKAGE = re.compile( |
| 23 | + r"\s*(?:package\s*=\s*)?[\"']?([A-Za-z][A-Za-z0-9._-]*)" |
| 24 | +) |
| 25 | +_CALL = re.compile( |
| 26 | + r"([A-Za-z.][A-Za-z0-9._]*(?:(?:::|\$)[A-Za-z.][A-Za-z0-9._]*)?)[ \t]*\(" |
| 27 | +) |
| 28 | +_NON_CALLS = frozenset({"function", "if", "for", "while", "repeat", "switch", "return"}) |
| 29 | + |
| 30 | + |
| 31 | +def _mask_non_code(source: str) -> str: |
| 32 | + """Blank comments and strings without changing byte offsets or line numbers.""" |
| 33 | + out = list(source) |
| 34 | + quote: str | None = None |
| 35 | + escaped = False |
| 36 | + comment = False |
| 37 | + for index, char in enumerate(source): |
| 38 | + if comment: |
| 39 | + if char == "\n": |
| 40 | + comment = False |
| 41 | + else: |
| 42 | + out[index] = " " |
| 43 | + continue |
| 44 | + if quote is not None: |
| 45 | + if char == "\n": |
| 46 | + continue |
| 47 | + if escaped: |
| 48 | + escaped = False |
| 49 | + out[index] = " " |
| 50 | + elif char == "\\": |
| 51 | + escaped = True |
| 52 | + out[index] = " " |
| 53 | + elif char == quote: |
| 54 | + quote = None |
| 55 | + else: |
| 56 | + out[index] = " " |
| 57 | + continue |
| 58 | + if char == "#": |
| 59 | + comment = True |
| 60 | + out[index] = " " |
| 61 | + elif char in ("'", '"'): |
| 62 | + quote = char |
| 63 | + return "".join(out) |
| 64 | + |
| 65 | + |
| 66 | +def _matching_delimiter(text: str, start: int, opening: str, closing: str) -> int | None: |
| 67 | + depth = 1 |
| 68 | + for index in range(start, len(text)): |
| 69 | + if text[index] == opening: |
| 70 | + depth += 1 |
| 71 | + elif text[index] == closing: |
| 72 | + depth -= 1 |
| 73 | + if depth == 0: |
| 74 | + return index |
| 75 | + return None |
| 76 | + |
| 77 | + |
| 78 | +def extract_r(path: Path) -> dict: |
| 79 | + """Extract R package imports, named functions, and local direct calls.""" |
| 80 | + try: |
| 81 | + source = path.read_text(encoding="utf-8", errors="replace") |
| 82 | + except OSError as exc: |
| 83 | + return {"nodes": [], "edges": [], "error": str(exc)} |
| 84 | + |
| 85 | + masked = _mask_non_code(source) |
| 86 | + str_path = str(path) |
| 87 | + stem = _file_stem(path) |
| 88 | + file_nid = _make_id(str_path) |
| 89 | + nodes: list[dict] = [] |
| 90 | + edges: list[dict] = [] |
| 91 | + raw_calls: list[dict] = [] |
| 92 | + seen_ids: set[str] = set() |
| 93 | + |
| 94 | + def line_at(offset: int) -> int: |
| 95 | + return source.count("\n", 0, offset) + 1 |
| 96 | + |
| 97 | + def add_node(nid: str, label: str, line: int) -> None: |
| 98 | + if nid not in seen_ids: |
| 99 | + seen_ids.add(nid) |
| 100 | + nodes.append( |
| 101 | + { |
| 102 | + "id": nid, |
| 103 | + "label": label, |
| 104 | + "file_type": "code", |
| 105 | + "source_file": str_path, |
| 106 | + "source_location": f"L{line}", |
| 107 | + } |
| 108 | + ) |
| 109 | + |
| 110 | + def add_edge(src: str, tgt: str, relation: str, line: int) -> None: |
| 111 | + edges.append( |
| 112 | + { |
| 113 | + "source": src, |
| 114 | + "target": tgt, |
| 115 | + "relation": relation, |
| 116 | + "confidence": "EXTRACTED", |
| 117 | + "source_file": str_path, |
| 118 | + "source_location": f"L{line}", |
| 119 | + "weight": 1.0, |
| 120 | + } |
| 121 | + ) |
| 122 | + |
| 123 | + add_node(file_nid, path.name, 1) |
| 124 | + |
| 125 | + for match in _IMPORT.finditer(masked): |
| 126 | + arguments_end = _matching_delimiter(masked, match.end(), "(", ")") |
| 127 | + if arguments_end is None: |
| 128 | + continue |
| 129 | + tail = source[match.end():arguments_end] |
| 130 | + package = _PACKAGE.match(tail) |
| 131 | + if package: |
| 132 | + add_edge(file_nid, _make_id(package.group(1)), "imports", line_at(match.start())) |
| 133 | + |
| 134 | + function_specs: list[tuple[int, int, str]] = [] |
| 135 | + for match in _FUNCTION.finditer(masked): |
| 136 | + parameters_end = _matching_delimiter(masked, match.end(), "(", ")") |
| 137 | + if parameters_end is None: |
| 138 | + continue |
| 139 | + body_start = parameters_end + 1 |
| 140 | + while body_start < len(masked) and masked[body_start] in " \t\r\n": |
| 141 | + body_start += 1 |
| 142 | + if body_start < len(masked) and masked[body_start] == "{": |
| 143 | + end = _matching_delimiter(masked, body_start + 1, "{", "}") |
| 144 | + if end is None: |
| 145 | + continue |
| 146 | + else: |
| 147 | + newline = masked.find("\n", body_start) |
| 148 | + end = len(masked) - 1 if newline < 0 else newline |
| 149 | + function_specs.append((match.start(), end, match.group(1))) |
| 150 | + |
| 151 | + functions: list[dict] = [] |
| 152 | + for start, end, name in function_specs: |
| 153 | + parent = min( |
| 154 | + ( |
| 155 | + function |
| 156 | + for function in functions |
| 157 | + if function["start"] < start and end <= function["end"] |
| 158 | + ), |
| 159 | + key=lambda function: function["end"] - function["start"], |
| 160 | + default=None, |
| 161 | + ) |
| 162 | + parent_id = parent["id"] if parent else None |
| 163 | + nid = _make_id(parent_id or stem, name) |
| 164 | + line = line_at(start) |
| 165 | + add_node(nid, f"{name}()", line) |
| 166 | + add_edge(parent_id or file_nid, nid, "contains", line) |
| 167 | + functions.append( |
| 168 | + { |
| 169 | + "start": start, |
| 170 | + "end": end, |
| 171 | + "id": nid, |
| 172 | + "name": name, |
| 173 | + "parent": parent_id, |
| 174 | + } |
| 175 | + ) |
| 176 | + |
| 177 | + labels: dict[str, list[dict]] = {} |
| 178 | + for function in functions: |
| 179 | + labels.setdefault(function["name"], []).append(function) |
| 180 | + |
| 181 | + def call_target(callee: str, caller: dict) -> str | None: |
| 182 | + candidates = [ |
| 183 | + candidate |
| 184 | + for candidate in labels.get(callee, []) |
| 185 | + if candidate["id"] != caller["id"] |
| 186 | + ] |
| 187 | + children = [ |
| 188 | + candidate for candidate in candidates if candidate["parent"] == caller["id"] |
| 189 | + ] |
| 190 | + if len(children) == 1: |
| 191 | + return children[0]["id"] |
| 192 | + same_scope = [ |
| 193 | + candidate for candidate in candidates if candidate["parent"] == caller["parent"] |
| 194 | + ] |
| 195 | + if len(same_scope) == 1: |
| 196 | + return same_scope[0]["id"] |
| 197 | + if len(candidates) == 1: |
| 198 | + return candidates[0]["id"] |
| 199 | + return None |
| 200 | + |
| 201 | + seen_calls: set[tuple[str, str]] = set() |
| 202 | + for function in functions: |
| 203 | + start = function["start"] |
| 204 | + end = function["end"] |
| 205 | + caller = function["id"] |
| 206 | + body = list(masked[start:end + 1]) |
| 207 | + for nested in functions: |
| 208 | + nested_start = nested["start"] |
| 209 | + nested_end = nested["end"] |
| 210 | + if start < nested_start and nested_end <= end: |
| 211 | + for index in range(nested_start, nested_end + 1): |
| 212 | + if body[index - start] != "\n": |
| 213 | + body[index - start] = " " |
| 214 | + body_text = "".join(body) |
| 215 | + for call in _CALL.finditer(body_text): |
| 216 | + expression = call.group(1) |
| 217 | + callee = re.split(r"::|\$", expression)[-1] |
| 218 | + if callee in _NON_CALLS: |
| 219 | + continue |
| 220 | + absolute = start + call.start(1) |
| 221 | + target = call_target(callee, function) |
| 222 | + if target: |
| 223 | + pair = (caller, target) |
| 224 | + if pair not in seen_calls: |
| 225 | + seen_calls.add(pair) |
| 226 | + add_edge(caller, target, "calls", line_at(absolute)) |
| 227 | + elif callee: |
| 228 | + raw_calls.append( |
| 229 | + { |
| 230 | + "caller_nid": caller, |
| 231 | + "callee": callee, |
| 232 | + "is_member_call": "$" in expression, |
| 233 | + "source_file": str_path, |
| 234 | + "source_location": f"L{line_at(absolute)}", |
| 235 | + } |
| 236 | + ) |
| 237 | + |
| 238 | + clean_edges = [ |
| 239 | + edge |
| 240 | + for edge in edges |
| 241 | + if edge["source"] in seen_ids |
| 242 | + and (edge["target"] in seen_ids or edge["relation"] == "imports") |
| 243 | + ] |
| 244 | + return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls} |
0 commit comments