first commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
"""AST-level boundary error injection for Java using javalang."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import javalang
|
||||
|
||||
from app.dataset.rules.base import Mutation, MutationRule
|
||||
|
||||
|
||||
class JavaBoundaryErrorRule(MutationRule):
|
||||
"""Mutate array length boundary from `<` to `<=`.
|
||||
|
||||
Uses `javalang` to locate a binary comparison against `.length` and flips
|
||||
the operator to introduce an off-by-one access.
|
||||
"""
|
||||
|
||||
name = "java_boundary_error"
|
||||
language = "java"
|
||||
defect_type = "boundary_condition_error"
|
||||
|
||||
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
|
||||
right = node.operandr
|
||||
if isinstance(right, javalang.tree.MemberReference) and right.member == "length":
|
||||
# BinaryOperation itself may lack position; use enclosing statement
|
||||
if_statement = next((n for n in path if isinstance(n, javalang.tree.IfStatement)), None)
|
||||
pos = if_statement.position if if_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:
|
||||
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 ArrayIndexOutOfBoundsException.",
|
||||
description="Changed array boundary check to off-by-one (<= length).",
|
||||
)
|
||||
return None
|
||||
Reference in New Issue
Block a user