53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
"""AST-level logical operator misuse injection for Java using javalang."""
|
|
|
|
from typing import Optional
|
|
|
|
import javalang
|
|
|
|
from app.dataset.rules.base import Mutation, MutationRule
|
|
|
|
|
|
class JavaLogicOperatorRule(MutationRule):
|
|
"""Swap `&&` with `||` in a boolean expression.
|
|
|
|
Uses `javalang` to locate a binary operation with `&&` and replaces the
|
|
operator with `||`.
|
|
"""
|
|
|
|
name = "java_logic_operator"
|
|
language = "java"
|
|
defect_type = "logic_operator_misuse"
|
|
|
|
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
|
|
try:
|
|
tree = javalang.parse.parse(source)
|
|
except Exception:
|
|
return None
|
|
|
|
for path, node in tree:
|
|
if not isinstance(node, javalang.tree.BinaryOperation):
|
|
continue
|
|
if node.operator != "&&":
|
|
continue
|
|
return_statement = next((n for n in path if isinstance(n, javalang.tree.ReturnStatement)), None)
|
|
pos = return_statement.position if return_statement else node.position
|
|
if not pos:
|
|
continue
|
|
lines = source.splitlines(keepends=True)
|
|
line_no = pos.line
|
|
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 conjunction semantics.",
|
|
description="Replaced boolean `&&` with `||`.",
|
|
)
|
|
return None
|