"""Utility to build pipeline-transformed source files."""
from __future__ import annotations
import ast
import copy
def build_generated_file_source(
transformed_func_def: ast.FunctionDef,
source_file: str,
line_offset: int,
col_offset: int,
source_lines_raw: list,
closure_vars: dict,
) -> str:
"""Build a complete, runnable .py source for the transformed kernel.
Reads the original source file and replaces the kernel function definition
(incl. decorators) with the transformed version. The ``pipeline=`` decorator kwarg
is stripped so the generated file does not re-trigger the transform if run directly.
"""
fd = copy.deepcopy(transformed_func_def)
for dec in fd.decorator_list:
if isinstance(dec, ast.Call):
dec.keywords = [kw for kw in dec.keywords if kw.arg != "pipeline"]
new_func_src = ast.unparse(fd)
try:
with open(source_file, encoding="utf-8") as f:
orig_lines = f.read().split("\n")
except OSError:
return new_func_src
start = line_offset
end = start + len(source_lines_raw)
indent = " " * col_offset
new_block = [indent + ln if ln else ln for ln in new_func_src.split("\n")]
result = orig_lines[:start] + new_block + orig_lines[end:]
return "\n".join(result) if isinstance(result, list) else result