Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / patch_engine.py: 91%

336 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Apply inline patch IR to copied modeling source.""" 

16 

17from __future__ import annotations 

18 

19import ast 

20import keyword 

21from collections import defaultdict 

22from typing import Iterable 

23 

24from hyper_parallel.codegen.astkit.edits import TextEdit, apply_edits 

25from hyper_parallel.codegen.astkit.index import build_source_index 

26from hyper_parallel.codegen.inline.declaration_edits import declaration_edits 

27from hyper_parallel.codegen.inline.forward_edits import forward_extract_edits 

28from hyper_parallel.codegen.inline.definition_edits import apply_class_removals 

29from hyper_parallel.codegen.inline.ir import ( 

30 ConstructorReplacePatch, 

31 ForwardExtractPatch, 

32 InlinePatchSet, 

33) 

34 

35 

36def apply_patch_set( 

37 source_text: str, patch_set: InlinePatchSet, *, root_class_name: str | None = None, 

38) -> str: 

39 """Apply imports, constructor edits, class removals, markers, and forward bodies. 

40 

41 Args: 

42 source_text: Modeling source the patches are applied to. 

43 patch_set: Edits emitted by the inline passes. 

44 root_class_name: Observed root model class, disambiguating composed source. 

45 

46 Returns: 

47 The patched source text. 

48 """ 

49 

50 text, hits = _apply_source_declarations(source_text, patch_set) 

51 text = _apply_constructor_followups(text, patch_set, hits, root_class_name) 

52 return _apply_forward_patches(text, patch_set.forward_extracts) 

53 

54 

55def _apply_source_declarations( 

56 source_text: str, patch_set: InlinePatchSet 

57) -> tuple[str, dict[str, int]]: 

58 """Apply top-level declarations and the first constructor rewrite wave.""" 

59 index = build_source_index(source_text) 

60 edits = declaration_edits( 

61 source_text, 

62 index.import_end, 

63 index.docstring_end, 

64 patch_set.imports, 

65 patch_set.module_snippets, 

66 ) 

67 waves = _constructor_waves(list(patch_set.constructor_replaces)) 

68 hits: dict[str, int] = defaultdict(int) 

69 if waves: 

70 edits.extend(_constructor_edits(source_text, waves[0], hits)) 

71 text = apply_edits(source_text, edits) if edits else source_text 

72 for wave in waves[1:]: 

73 wave_edits = _constructor_edits(text, wave, hits) 

74 if wave_edits: 

75 text = apply_edits(text, wave_edits) 

76 return text, hits 

77 

78 

79def _apply_constructor_followups( 

80 source_text: str, 

81 patch_set: InlinePatchSet, 

82 hits: dict[str, int], 

83 root_class_name: str | None, 

84) -> str: 

85 """Apply deferred replacements, validate scopes, and remove replaced classes.""" 

86 deferred_edits = _deferred_replacement_edits( 

87 source_text, 

88 patch_set.constructor_replaces, 

89 hits, 

90 root_class_name, 

91 ) 

92 if deferred_edits: 

93 source_text = apply_edits(source_text, deferred_edits) 

94 if patch_set.constructor_replaces: 

95 _require_scoped_rewrites(patch_set.constructor_replaces, hits) 

96 if patch_set.class_removals: 

97 source_text = apply_class_removals(source_text, patch_set.class_removals) 

98 return source_text 

99 

100 

101def _apply_forward_patches( 

102 source_text: str, patches: Iterable[ForwardExtractPatch] 

103) -> str: 

104 """Apply forward extraction only after the source structure has settled.""" 

105 edits = forward_extract_edits(source_text, patches) 

106 return apply_edits(source_text, edits) if edits else source_text 

107 

108 

109def _constructor_waves( 

110 patch_list: list[ConstructorReplacePatch], 

111) -> list[list[ConstructorReplacePatch]]: 

112 """Group constructor rewrites into dependency-ordered waves. 

113 

114 Two compositions force a later wave, re-parsed from the previous 

115 wave's output: a patch whose ``old_ctor`` another remaining patch 

116 introduces (an ``A -> B`` wrap retargeted further by a ``B -> C`` 

117 patch), and a ``name`` retarget sharing its ``old_ctor`` with a 

118 ``wrap_source`` patch — the inline CP subclass retargets the 

119 *outer* wrapper call the wrap introduced, and applying the name 

120 swap first would consume the call site the wrap still needs (a 

121 scoped wrap with no call site fails loudly, so the order is not 

122 optional). 

123 """ 

124 

125 remaining = list(patch_list) 

126 waves: list[list[ConstructorReplacePatch]] = [] 

127 while remaining: 

128 introduced = { 

129 patch.new_ctor for patch in remaining if patch.new_ctor != patch.old_ctor 

130 } 

131 wave = [patch for patch in remaining if _is_wave_ready(patch, remaining, introduced)] 

132 if not wave: 

133 names = sorted({patch.old_ctor for patch in remaining}) 

134 raise ValueError( 

135 f"codegen: constructor replacement dependency cycle among {names}" 

136 ) 

137 chosen = {id(patch) for patch in wave} 

138 remaining = [patch for patch in remaining if id(patch) not in chosen] 

139 waves.append(wave) 

140 return waves 

141 

142 

143def _is_wave_ready( 

144 patch: ConstructorReplacePatch, 

145 remaining: list[ConstructorReplacePatch], 

146 introduced: set[str], 

147) -> bool: 

148 """Return whether a constructor patch has no remaining dependency.""" 

149 if patch.old_ctor in introduced: 

150 return False 

151 if patch.mode != "name": 

152 return True 

153 return not any( 

154 other is not patch 

155 and other.mode == "wrap_source" 

156 and other.old_ctor == patch.old_ctor 

157 for other in remaining 

158 ) 

159 

160 

161def _constructor_edits( 

162 source_text: str, 

163 patches: list[ConstructorReplacePatch], 

164 hits: dict[str, int], 

165) -> list[TextEdit]: 

166 """Build the edits that swap constructor calls per patch target.""" 

167 patches_by_old: dict[str, list[ConstructorReplacePatch]] = defaultdict(list) 

168 for patch in patches: 

169 if not patch.defer_to_fqns: 

170 patches_by_old[patch.old_ctor].append(patch) 

171 if not patches_by_old: 

172 return [] 

173 scopes = _scopes_by_old_ctor(patches) 

174 tree = ast.parse(source_text) 

175 offsets = _line_offsets(source_text) 

176 edits: list[TextEdit] = [] 

177 for node in ast.walk(tree): 

178 if not isinstance(node, ast.Assign): 

179 continue 

180 attr = _assigned_attr(node) 

181 if attr is None: 

182 continue 

183 call = node.value 

184 if not isinstance(call, ast.Call): 

185 continue 

186 name = _call_name(call.func) 

187 if name is None or name not in patches_by_old: 

188 continue 

189 scope = scopes[name] 

190 if scope is not None and attr not in scope: 

191 continue 

192 patch = patches_by_old[name][0] 

193 hits[name] += 1 

194 start, end = _node_span(call, offsets) 

195 replacement = _constructor_replacement(source_text, tree, node, patch, offsets) 

196 edits.append(TextEdit(start, end, replacement)) 

197 return _drop_nested_edits(edits) 

198 

199 

200def _constructor_replacement(source: str, tree: ast.Module, node: ast.Assign, 

201 patch: ConstructorReplacePatch, offsets: list[int]) -> str: 

202 """Reuse a source call, wrapping it or binding its existing config argument.""" 

203 call = node.value 

204 start, end = _node_span(call, offsets) 

205 original = source[start:end] 

206 extra = "".join(f", {arg}" for arg in patch.keyword_args) 

207 if patch.mode == "wrap_source": 

208 return f"{patch.new_ctor}(module={original}{extra})" 

209 if patch.mode == "construct": 

210 return _direct_constructor_replacement(tree, call, patch) 

211 if patch.mode == "name": 

212 _, function_end = _node_span(call.func, offsets) 

213 original = source[function_end:end] 

214 return patch.new_ctor + original 

215 if patch.mode != "config": 

216 raise ValueError(f"unknown constructor replacement mode: {patch.mode!r}") 

217 return _config_replacement(tree, node, patch, extra) 

218 

219 

220def _direct_constructor_replacement(tree: ast.Module, call: ast.Call, patch: ConstructorReplacePatch) -> str: 

221 """Keep source defaults when a concrete member has different direct-construction defaults.""" 

222 if any(isinstance(arg, ast.Starred) for arg in call.args) or any(kw.arg is None for kw in call.keywords): 

223 raise ValueError(f"codegen: {patch.old_ctor} has unpacked arguments that cannot be bound offline") 

224 positional, defaults = _source_constructor_parameters(tree, patch.old_ctor) 

225 supplied = set(positional[:len(call.args)]) | {kw.arg for kw in call.keywords} 

226 arguments = list(call.args) 

227 keywords = {kw.arg: kw.value for kw in call.keywords} 

228 keywords.update({name: value for name, value in defaults.items() if name not in supplied}) 

229 overrides = ast.parse(f"_constructor({', '.join(patch.keyword_args)})", mode="eval").body 

230 for kw in overrides.keywords: 

231 if kw.arg in positional[:len(arguments)]: 

232 arguments[positional.index(kw.arg)] = kw.value 

233 else: 

234 keywords[kw.arg] = kw.value 

235 result = ast.Call(func=ast.Name(id=patch.new_ctor, ctx=ast.Load()), args=arguments, 

236 keywords=[ast.keyword(arg=name, value=value) for name, value in keywords.items()]) 

237 return ast.unparse(result) 

238 

239 

240def _source_constructor_parameters(tree: ast.Module, name: str) -> tuple[list[str], dict[str, ast.expr]]: 

241 """Read parameter names and default expressions from the copied source without executing it.""" 

242 owner = next((item for item in tree.body if isinstance(item, ast.ClassDef) and item.name == name), None) 

243 constructor = next((item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == "__init__"), 

244 None) if owner is not None else None 

245 if constructor is None: 

246 raise ValueError(f"codegen: {name} has no source constructor for direct replacement") 

247 positional = [item.arg for item in (*constructor.args.posonlyargs, *constructor.args.args)][1:] 

248 defaults = dict(zip(positional[-len(constructor.args.defaults):], constructor.args.defaults)) 

249 defaults.update({arg.arg: value for arg, value in zip(constructor.args.kwonlyargs, constructor.args.kw_defaults) 

250 if value is not None}) 

251 return positional, defaults 

252 

253 

254def _config_replacement(tree: ast.Module, node: ast.Assign, patch: ConstructorReplacePatch, extra: str) -> str: 

255 """Bind the config from the existing source constructor without evaluating it.""" 

256 call = node.value 

257 owner = next(item for item in tree.body if isinstance(item, ast.ClassDef) and item.name == patch.old_ctor) 

258 constructor = next(item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == "__init__") 

259 names = [item.arg for item in (*constructor.args.posonlyargs, *constructor.args.args) if item.arg != "self"] 

260 arguments = dict(zip(names, call.args)) 

261 arguments.update({kw.arg: kw.value for kw in call.keywords if kw.arg is not None}) 

262 if "config" not in arguments: 

263 raise ValueError(f"codegen: {patch.old_ctor} has no source config argument") 

264 result = f"{patch.new_ctor}(config={ast.unparse(arguments['config'])}{extra})" 

265 return result + _preserved_source_attributes(constructor, node, arguments) 

266 

267 

268def _preserved_source_attributes(constructor: ast.FunctionDef, node: ast.Assign, arguments: dict) -> str: 

269 """Retain explicit source constructor identity fields such as layer indices.""" 

270 lines = [] 

271 for statement in constructor.body: 

272 if (isinstance(statement, ast.Assign) and isinstance(statement.value, ast.Name) 

273 and statement.value.id in arguments and statement.value.id != "config"): 

274 for target in statement.targets: 

275 if (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) 

276 and target.value.id == "self"): 

277 lines.append(f"\n{' ' * node.col_offset}{ast.unparse(node.targets[0])}.{target.attr} = " 

278 f"{ast.unparse(arguments[statement.value.id])}") 

279 return "".join(lines) 

280 

281 

282def _scopes_by_old_ctor( 

283 patches: Iterable[ConstructorReplacePatch], 

284) -> dict[str, set[str] | None]: 

285 """Merge each constructor's rewrite scope; ``None`` means unrestricted.""" 

286 

287 scopes: dict[str, set[str] | None] = {} 

288 for patch in patches: 

289 if not patch.scope_attrs: 

290 scopes[patch.old_ctor] = None 

291 continue 

292 merged = scopes.get(patch.old_ctor) 

293 if merged is None and patch.old_ctor in scopes: 

294 continue 

295 if merged is None: 

296 merged = scopes[patch.old_ctor] = set() 

297 merged.update(patch.scope_attrs) 

298 return scopes 

299 

300 

301def _assigned_attr(node: ast.Assign) -> str | None: 

302 """Return the stored attribute of an attribute store, else ``None``. 

303 

304 Module replacements are sunk at the assignment that installs the module, so 

305 scoping by the assigned attribute is exactly the FQN granularity the native 

306 plan used to decide the replacement. Families attach modules at more than 

307 the ``self.<attr>`` store: a loop-local ``layer.<attr>`` upgrade and a 

308 ModuleList element ``self.layers[i].<attr>`` install the same matched 

309 modules, so any attribute store yields its stored attribute -- the rule's 

310 scope set keeps the rewrite at the plan's matched-FQN granularity. 

311 """ 

312 

313 if len(node.targets) != 1: 

314 return None 

315 target = node.targets[0] 

316 return target.attr if isinstance(target, ast.Attribute) else None 

317 

318 

319def _require_scoped_rewrites( 

320 patches: Iterable[ConstructorReplacePatch], 

321 hits: dict[str, int], 

322) -> None: 

323 """Fail when a scoped rule matched FQNs but no source call site. 

324 

325 Silently dropping the rewrite would emit an artifact that no longer matches 

326 the plan that decided the replacement, so a missing call site is a 

327 generation error: the scope handling needs to learn the new shape rather 

328 than the rewrite being widened back to the whole file. 

329 """ 

330 

331 missing = sorted( 

332 {patch.old_ctor for patch in patches if patch.scope_attrs and not hits.get(patch.old_ctor)} 

333 ) 

334 if missing: 

335 raise RuntimeError( 

336 "codegen: no `self.<attr> = <ctor>(...)` call site found for " 

337 f"{missing}; the plan replaced modules of this type, so the " 

338 "replacement cannot be sunk without diverging from the plan" 

339 ) 

340 

341 

342def _deferred_replacement_edits( 

343 source_text: str, 

344 patches: Iterable[ConstructorReplacePatch], 

345 hits: dict[str, int], 

346 root_class_name: str | None, 

347) -> list[TextEdit]: 

348 """Install observed wrappers after an imported owner built its subtree. 

349 

350 Some source models inherit a decoder whose constructor lives in an 

351 installed dependency. The copied modeling unit therefore has no direct 

352 constructor call to rewrite. For a wrap-style replacement, the native 

353 operation is still expressible exactly: wait until the root model has 

354 built the observed FQNs, then replace those module attributes in place. 

355 Module-family requests also use this form: different layers can share the 

356 same source constructor while requiring distinct options and provenance. 

357 """ 

358 pending = [ 

359 patch 

360 for patch in patches 

361 if patch.scope_fqns and (patch.defer_to_fqns or not hits.get(patch.old_ctor)) 

362 ] 

363 if not pending: 

364 return [] 

365 tree = ast.parse(source_text) 

366 offsets = _line_offsets(source_text) 

367 insertions: dict[int, list[str]] = defaultdict(list) 

368 for patch in pending: 

369 if patch.mode != "wrap_source": 

370 continue 

371 loop_edit = _prepared_layer_replacement(tree, patch, root_class_name, offsets) 

372 if loop_edit is not None: 

373 insertions[loop_edit.start].append(loop_edit.replacement) 

374 hits[patch.old_ctor] += 1 

375 continue 

376 root_attr = patch.scope_fqns[0].split(".", 1)[0] 

377 constructors = _root_constructors(tree, root_attr, root_class_name) 

378 if len(constructors) != 1: 

379 continue 

380 function = constructors[0] 

381 _, end = _node_span(function.body[-1], offsets) 

382 insertions[end].append(_render_deferred_replacement(patch)) 

383 hits[patch.old_ctor] += 1 

384 return [ 

385 TextEdit(offset, offset, "".join(parts)) 

386 for offset, parts in insertions.items() 

387 ] 

388 

389 

390def _prepared_layer_replacement(tree: ast.Module, patch: ConstructorReplacePatch, 

391 root_class: str | None, offsets: list[int]) -> TextEdit | None: 

392 """Reuse an existing layer preparation loop when the child constructor is imported.""" 

393 if patch.shared_fqns: 

394 return None 

395 scope = _layer_scope(patch.scope_fqns) 

396 if scope is None: 

397 return None 

398 paths, index, prefix, suffix = scope 

399 owner = _source_constructor(tree, root_class, prefix[:-1]) 

400 if owner is None: 

401 return None 

402 candidates = _prepared_layer_aliases(owner, prefix[-1]) 

403 if len(candidates) != 1: 

404 return None 

405 loop, alias = candidates[0] 

406 if any(isinstance(node, (ast.Break, ast.Continue, ast.Return)) for node in ast.walk(loop)): 

407 return None 

408 access = ".".join([alias.targets[0].id, *suffix]) 

409 extra = "".join(f", {arg}" for arg in patch.keyword_args if not arg.startswith("module_fqn=")) 

410 body = f"{access} = {patch.new_ctor}(module={access}{extra})" 

411 if not patch.scope_complete: 

412 selected = tuple(int(path[index]) for path in paths) 

413 body = f"if {loop.target.id} in {selected!r}:\n {body}" 

414 indent = " " * alias.col_offset 

415 body = "\n" + "\n".join(indent + line for line in body.splitlines()) + "\n" 

416 _, end = _node_span(loop.body[-1], offsets) 

417 return TextEdit(end, end, body) 

418 

419 

420def _layer_scope(fqns: tuple[str, ...]) -> tuple | None: 

421 """Accept one literal indexed container and a common child suffix.""" 

422 paths = [fqn.split(".") for fqn in fqns] 

423 numeric = [index for index, part in enumerate(paths[0]) if part.isdecimal()] 

424 if len(numeric) != 1: 

425 return None 

426 index = numeric[0] 

427 prefix, suffix = paths[0][:index], paths[0][index + 1:] 

428 if not prefix or not suffix or any(path[:index] != prefix or path[index + 1:] != suffix for path in paths): 

429 return None 

430 return paths, index, prefix, suffix 

431 

432 

433def _source_constructor(tree: ast.Module, root_class: str | None, path: list[str]) -> ast.FunctionDef | None: 

434 """Follow only literal self.child = LocalClass(...) ownership in copied source.""" 

435 constructors = { 

436 cls.name: next((node for node in cls.body if isinstance(node, ast.FunctionDef) 

437 and node.name == "__init__"), None) 

438 for cls in tree.body if isinstance(cls, ast.ClassDef) 

439 } 

440 constructor = constructors.get(root_class) 

441 for name in path: 

442 if constructor is None: 

443 return None 

444 calls = [node.value for node in ast.walk(constructor) 

445 if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) 

446 and _assigned_attr(node) == name and ast.unparse(node.targets[0]) == f"self.{name}"] 

447 if len(calls) != 1: 

448 return None 

449 constructor = constructors.get(_call_name(calls[0].func)) 

450 return constructor 

451 

452 

453def _prepared_layer_aliases(owner: ast.FunctionDef, container: str) -> list[tuple[ast.For, ast.Assign]]: 

454 """Recognize native for-loops that bind layer = self.layers[index].""" 

455 candidates = [] 

456 iteration = _container_iteration(owner, container) 

457 for loop in (node for node in ast.walk(owner) if isinstance(node, ast.For) and isinstance(node.target, ast.Name)): 

458 if ast.dump(loop.iter) != iteration: 

459 continue 

460 for node in loop.body: 

461 if (isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) 

462 and isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Attribute) 

463 and ast.unparse(node.value.value) == f"self.{container}" 

464 and ast.unparse(node.value.slice) == loop.target.id): 

465 candidates.append((loop, node)) 

466 return candidates 

467 

468 

469def _container_iteration(owner: ast.FunctionDef, container: str) -> str | None: 

470 """Prove a preparation loop covers the same range used to create the ModuleList.""" 

471 for node in owner.body: 

472 if (isinstance(node, ast.Assign) and _assigned_attr(node) == container 

473 and ast.unparse(node.targets[0]) == f"self.{container}" 

474 and isinstance(node.value, ast.Call) and node.value.args 

475 and ast.unparse(node.value.func) in ("nn.ModuleList", "torch.nn.ModuleList")): 

476 value = node.value.args[0] 

477 if isinstance(value, ast.ListComp) and len(value.generators) == 1: 

478 iteration = value.generators[0].iter 

479 if (isinstance(iteration, ast.Call) and ast.unparse(iteration.func) == "range" 

480 and len(iteration.args) == 1 and not iteration.keywords): 

481 return ast.dump(iteration) 

482 return None 

483 

484 

485def _root_constructors( 

486 tree: ast.Module, root_attr: str, root_class_name: str | None, 

487) -> list[ast.FunctionDef]: 

488 """Return constructors that establish the first segment of an observed FQN.""" 

489 constructors = [] 

490 for node in tree.body: 

491 if not isinstance(node, ast.ClassDef): 

492 continue 

493 if root_class_name not in (None, node.name): 

494 continue 

495 for child in node.body: 

496 if not isinstance(child, ast.FunctionDef) or child.name != "__init__": 

497 continue 

498 if any( 

499 isinstance(target, ast.Attribute) 

500 and isinstance(target.value, ast.Name) 

501 and target.value.id == "self" 

502 and target.attr == root_attr 

503 for item in ast.walk(child) 

504 if isinstance(item, (ast.Assign, ast.AnnAssign)) 

505 for target in ( 

506 item.targets if isinstance(item, ast.Assign) else (item.target,) 

507 ) 

508 ): 

509 constructors.append(child) 

510 return constructors 

511 

512 

513def _render_deferred_replacement(patch: ConstructorReplacePatch) -> str: 

514 """Render explicit module assignments, preserving observed shared ownership.""" 

515 arguments = [arg for arg in patch.keyword_args if not arg.startswith("module_fqn=")] 

516 extra = "".join(f", {arg}" for arg in arguments) 

517 aliases = {fqn: group[0] for group in patch.shared_fqns for fqn in group[1:]} 

518 primaries = [fqn for fqn in patch.scope_fqns if fqn not in aliases] 

519 lines = [] 

520 for fqn in primaries: 

521 value = (f"{patch.new_ctor}(\n" 

522 f" module={_module_access(fqn)}, module_fqn={fqn!r}{extra})") 

523 lines.extend((f"\n # {fqn}: {patch.old_ctor} -> {patch.new_ctor}", 

524 " " + _module_assignment(fqn, value))) 

525 for fqn in patch.scope_fqns: 

526 if fqn in aliases: 

527 primary = aliases[fqn] 

528 if primary not in primaries: 

529 raise ValueError(f"codegen: shared module {fqn!r} has no replacement at {primary!r}") 

530 lines.extend((f"\n # {fqn}: shares the replacement at {primary}", 

531 " " + _module_assignment(fqn, _module_access(primary)))) 

532 return "\n".join(lines) + "\n" 

533 

534 

535def _module_access(fqn: str) -> str: 

536 """Access native child names without guessing their container type.""" 

537 expression = "self" 

538 for name in fqn.split("."): 

539 expression = (f"{expression}.{name}" if name.isidentifier() and not keyword.iskeyword(name) 

540 else f"getattr({expression}, {name!r})") 

541 return expression 

542 

543 

544def _module_assignment(fqn: str, value: str) -> str: 

545 """Keep ordinary attributes readable and support non-identifier child names.""" 

546 parent, _, name = fqn.rpartition(".") 

547 if name.isidentifier() and not keyword.iskeyword(name): 

548 return f"{_module_access(fqn)} = {value}" 

549 return f"setattr({_module_access(parent) if parent else 'self'}, {name!r}, {value})" 

550 

551 

552def _drop_nested_edits(edits: list[TextEdit]) -> list[TextEdit]: 

553 """Keep outer constructor rewrites when constructor calls are nested.""" 

554 kept: list[TextEdit] = [] 

555 covered_end = -1 

556 for edit in sorted(edits, key=lambda item: (item.start, -item.end)): 

557 if edit.start < covered_end: 

558 continue 

559 kept.append(edit) 

560 covered_end = edit.end 

561 return kept 

562 

563 

564def _call_name(node: ast.AST) -> str | None: 

565 if isinstance(node, ast.Name): 

566 return node.id 

567 if isinstance(node, ast.Attribute): 

568 return node.attr 

569 return None 

570 

571 

572def _node_span(node: ast.AST, offsets: tuple[int, ...]) -> tuple[int, int]: 

573 """Return the ``(start, end)`` source span of ``node``. 

574 

575 Decorators are part of the span: deleting only the ``def``/``class`` line 

576 would leave a dangling decorator that then applies to whatever statement 

577 follows the removed block. 

578 """ 

579 

580 if ( 

581 getattr(node, "lineno", None) is None 

582 or getattr(node, "col_offset", None) is None 

583 or getattr(node, "end_lineno", None) is None 

584 or getattr(node, "end_col_offset", None) is None 

585 ): 

586 raise ValueError(f"AST node has no source span: {type(node).__name__}") 

587 line = node.lineno 

588 column = node.col_offset 

589 decorators = getattr(node, "decorator_list", None) 

590 if decorators: 

591 first = min(decorators, key=lambda item: item.lineno) 

592 if first.lineno < line: 

593 # A decorator node starts at its expression, one column *after* the 

594 # ``@``; the span must start at the ``@`` itself, otherwise deleting 

595 # the block leaves a stray ``@`` behind. 

596 line, column = first.lineno, max(0, first.col_offset - 1) 

597 start = offsets[line - 1] + column 

598 end = offsets[node.end_lineno - 1] + node.end_col_offset 

599 return start, end 

600 

601 

602def _line_offsets(source_text: str) -> tuple[int, ...]: 

603 offsets = [0] 

604 total = 0 

605 for line in source_text.splitlines(keepends=True): 

606 total += len(line) 

607 offsets.append(total) 

608 return tuple(offsets)