"""AST-level boundary error injection for JavaScript using esprima.""" from typing import Optional import esprima from app.dataset.rules.base import Mutation, MutationRule class JSBoundaryErrorRule(MutationRule): """Mutate array length boundary from `<` to `<=`. Uses `esprima` to locate a binary expression comparing against `.length` and flips the operator. """ name = "js_boundary_error" language = "javascript" defect_type = "boundary_condition_error" def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]: # Modern JS is usually ESM: try module grammar first, then script. try: tree = esprima.parseModule(source, loc=True) except Exception: try: tree = esprima.parseScript(source, loc=True) except Exception: return None for node in self._walk(tree): if node.type != "BinaryExpression" or node.operator != "<": continue right = node.right if right.type == "MemberExpression" and getattr(right.property, "name", None) == "length": line_no = node.loc.start.line lines = source.splitlines(keepends=True) line = lines[line_no - 1] mutated_line = line.replace("<", "<=", 1) if mutated_line == line: continue mutated = "".join(lines[:line_no - 1] + [mutated_line] + lines[line_no:]) return Mutation( defect_type=self.defect_type, language=self.language, line_start=line_no, line_end=line_no, mutated_source=mutated, reference_fix="Use strict `< length` to avoid out-of-bounds access.", description="Changed array boundary check to off-by-one (<= length).", ) return None def _walk(self, node): yield node for key in getattr(node, "__dict__", {}): child = getattr(node, key) if isinstance(child, list): for item in child: if hasattr(item, "type"): yield from self._walk(item) elif hasattr(child, "type"): yield from self._walk(child)