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
|
||||
@@ -0,0 +1,69 @@
|
||||
"""AST-level concurrency issue injection for Java using javalang."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import javalang
|
||||
|
||||
from app.dataset.rules.base import Mutation, MutationRule
|
||||
|
||||
|
||||
class JavaConcurrencyRule(MutationRule):
|
||||
"""Remove a synchronized block to expose a race condition.
|
||||
|
||||
Uses `javalang` to locate `synchronized (lock) { ... }` and replaces it
|
||||
with the bare block body.
|
||||
"""
|
||||
|
||||
name = "java_concurrency"
|
||||
language = "java"
|
||||
defect_type = "concurrency_issue"
|
||||
|
||||
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.SynchronizedStatement):
|
||||
continue
|
||||
pos = node.position
|
||||
if not pos:
|
||||
continue
|
||||
lines = source.splitlines(keepends=True)
|
||||
start = pos.line
|
||||
# Estimate end by braces of the synchronized block
|
||||
end = start
|
||||
depth = 0
|
||||
for idx in range(start - 1, len(lines)):
|
||||
depth += lines[idx].count("{") - lines[idx].count("}")
|
||||
if depth > 0:
|
||||
end = idx + 1
|
||||
if depth <= 0 and idx > start - 1:
|
||||
end = idx + 1
|
||||
break
|
||||
body_lines = lines[start - 1:end]
|
||||
# drop header line and closing brace line, keep body; body is at same
|
||||
# indentation as the synchronized header minus one level
|
||||
inner = body_lines[1:-1] if len(body_lines) > 2 else []
|
||||
dedented = []
|
||||
for line in inner:
|
||||
if line.startswith(" "):
|
||||
dedented.append(" " + line[12:])
|
||||
elif line.startswith(" "):
|
||||
dedented.append(" " + line[8:])
|
||||
elif line.startswith(" "):
|
||||
dedented.append(line[4:])
|
||||
else:
|
||||
dedented.append(line)
|
||||
mutated = "".join(lines[: start - 1] + dedented + lines[end:])
|
||||
return Mutation(
|
||||
defect_type=self.defect_type,
|
||||
language=self.language,
|
||||
line_start=start,
|
||||
line_end=end,
|
||||
mutated_source=mutated,
|
||||
reference_fix="Restore `synchronized (lock)` to protect the critical section.",
|
||||
description="Removed synchronized block, exposing a race condition.",
|
||||
)
|
||||
return None
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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
|
||||
@@ -0,0 +1,75 @@
|
||||
"""AST-level null-pointer injection for Java using javalang."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import javalang
|
||||
|
||||
from app.dataset.rules.base import Mutation, MutationRule
|
||||
|
||||
|
||||
class JavaNoneReferenceRule(MutationRule):
|
||||
"""Remove a null-check guard in Java source.
|
||||
|
||||
Uses the pure-Python `javalang` parser to locate an `if (x != null)` guard
|
||||
and remove it, leaving the dereference unprotected. This keeps mutation
|
||||
semantics precise without regex/text replacement.
|
||||
"""
|
||||
|
||||
name = "java_none_reference"
|
||||
language = "java"
|
||||
defect_type = "null_pointer"
|
||||
|
||||
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.IfStatement):
|
||||
continue
|
||||
cond = node.condition
|
||||
# Match: x != null
|
||||
if (
|
||||
isinstance(cond, javalang.tree.BinaryOperation)
|
||||
and cond.operator == "!="
|
||||
and isinstance(cond.operandr, javalang.tree.Literal)
|
||||
and cond.operandr.value == "null"
|
||||
):
|
||||
var_name = getattr(cond.operandl, "member", str(cond.operandl))
|
||||
lines = source.splitlines(keepends=True)
|
||||
start = node.position.line if node.position else 1
|
||||
# Estimate end line by finding matching brace (simplistic)
|
||||
end = start
|
||||
depth = 0
|
||||
for idx in range(start - 1, len(lines)):
|
||||
depth += lines[idx].count("{") - lines[idx].count("}")
|
||||
if depth > 0:
|
||||
end = idx + 1
|
||||
if depth <= 0 and idx > start - 1:
|
||||
end = idx + 1
|
||||
break
|
||||
body_lines = lines[start - 1:end]
|
||||
# keep body lines between header and closing brace, dedent one level
|
||||
inner = body_lines[1:-1] if len(body_lines) > 2 else []
|
||||
dedented = []
|
||||
for line in inner:
|
||||
if line.startswith(" "):
|
||||
dedented.append(" " + line[12:])
|
||||
elif line.startswith(" "):
|
||||
dedented.append(" " + line[8:])
|
||||
elif line.startswith(" "):
|
||||
dedented.append(line[4:])
|
||||
else:
|
||||
dedented.append(line)
|
||||
mutated = "".join(lines[: start - 1] + dedented + lines[end:])
|
||||
return Mutation(
|
||||
defect_type=self.defect_type,
|
||||
language=self.language,
|
||||
line_start=start,
|
||||
line_end=end,
|
||||
mutated_source=mutated,
|
||||
reference_fix=f"Add `if ({var_name} != null)` guard before dereferencing.",
|
||||
description=f"Removed null-check guard for '{var_name}'.",
|
||||
)
|
||||
return None
|
||||
@@ -0,0 +1,50 @@
|
||||
"""AST-level resource leak injection for Java using javalang."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import javalang
|
||||
|
||||
from app.dataset.rules.base import Mutation, MutationRule
|
||||
|
||||
|
||||
class JavaResourceLeakRule(MutationRule):
|
||||
"""Replace try-with-resources with a plain try block, leaking the resource.
|
||||
|
||||
Uses `javalang` to locate a try-with-resources statement and removes the
|
||||
resource specification, leaving the stream unclosed.
|
||||
"""
|
||||
|
||||
name = "java_resource_leak"
|
||||
language = "java"
|
||||
defect_type = "resource_not_closed"
|
||||
|
||||
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.TryStatement):
|
||||
continue
|
||||
if not node.resources:
|
||||
continue
|
||||
pos = node.position
|
||||
if not pos:
|
||||
continue
|
||||
lines = source.splitlines(keepends=True)
|
||||
start = pos.line
|
||||
# Find the resource clause line e.g. try (BufferedReader br = ...)
|
||||
resource_line = lines[start - 1]
|
||||
new_header = resource_line.split("(", 1)[0].rstrip() + " {\n"
|
||||
mutated = "".join(lines[: start - 1] + [new_header] + lines[start:])
|
||||
return Mutation(
|
||||
defect_type=self.defect_type,
|
||||
language=self.language,
|
||||
line_start=start,
|
||||
line_end=start,
|
||||
mutated_source=mutated,
|
||||
reference_fix="Use try-with-resources or explicitly close the stream in finally.",
|
||||
description="Removed try-with-resources, leaking the acquired resource.",
|
||||
)
|
||||
return None
|
||||
Reference in New Issue
Block a user