62 lines
2.1 KiB
Python
62 lines
2.1 KiB
Python
"""AST-level logical operator misuse injection for JavaScript using esprima."""
|
|
|
|
from typing import Optional
|
|
|
|
import esprima
|
|
|
|
from app.dataset.rules.base import Mutation, MutationRule
|
|
|
|
|
|
class JSLogicOperatorRule(MutationRule):
|
|
"""Swap `&&` with `||` in a boolean expression.
|
|
|
|
Uses `esprima` to locate a LogicalExpression using `&&` and replaces the
|
|
operator with `||`.
|
|
"""
|
|
|
|
name = "js_logic_operator"
|
|
language = "javascript"
|
|
defect_type = "logic_operator_misuse"
|
|
|
|
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 != "LogicalExpression" or node.operator != "&&":
|
|
continue
|
|
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="Restore `&&` for correct short-circuit logic.",
|
|
description="Replaced boolean `&&` with `||`.",
|
|
)
|
|
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)
|