first commit

This commit is contained in:
eeymoo
2026-09-19 12:54:45 +08:00
commit 6fc5b64077
126 changed files with 8601 additions and 0 deletions
@@ -0,0 +1,47 @@
"""Custom rule demonstrating pluggable extensibility (A1b)."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class UnusedVariableRule(MutationRule):
"""A custom rule: replace a variable read with an undefined name.
This is intentionally simple and demonstrates that adding a new file under
app/dataset/rules/<language>/ is enough to register a rule.
"""
name = "unused_variable_demo"
language = "python"
defect_type = "custom_demo"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.body:
first = node.body[0]
if isinstance(first, ast.Assign) and isinstance(first.targets[0], ast.Name):
var_name = first.targets[0].id
line_no = first.lineno
lines = source.splitlines(keepends=True)
line = lines[line_no - 1]
mutated_line = line.replace(var_name, "__undefined_" + var_name, 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=f"Use the original variable name '{var_name}'.",
description=f"Custom rule: replaced '{var_name}' with an undefined placeholder.",
)
return None
@@ -0,0 +1,50 @@
"""AST-level boundary condition injection for Python."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class BoundaryErrorRule(MutationRule):
"""Mutate a list-index boundary check from `< len(seq)` to `<= len(seq)`.
Uses `ast` to find comparisons guarding index access and flips the operator
so the boundary becomes off-by-one.
"""
name = "boundary_error"
language = "python"
defect_type = "boundary_condition_error"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, ast.If):
continue
test = node.test
if isinstance(test, ast.Compare) and isinstance(test.left, ast.Name):
if len(test.ops) == 1 and isinstance(test.ops[0], ast.Lt):
# i < len(x) -> i <= len(x)
comparator = test.comparators[0]
if isinstance(comparator, ast.Call) and isinstance(comparator.func, ast.Name) and comparator.func.id == "len":
lines = source.splitlines(keepends=True)
line = lines[node.lineno - 1]
mutated_line = line.replace("< len(", "<= len(", 1)
if mutated_line == line:
continue
mutated = "".join(lines[: node.lineno - 1] + [mutated_line] + lines[node.lineno:])
return Mutation(
defect_type=self.defect_type,
language=self.language,
line_start=node.lineno,
line_end=getattr(node, "end_lineno", node.lineno) or node.lineno,
mutated_source=mutated,
reference_fix="Use strict `< len(seq)` to avoid index-out-of-range.",
description="Changed index boundary check to off-by-one (<= len).",
)
return None
@@ -0,0 +1,52 @@
"""AST-level concurrency safety injection for Python."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class ConcurrencyRule(MutationRule):
"""Remove a threading.Lock.acquire/release pair to introduce race condition.
Uses `ast` to find a with-statement using a lock and replaces it with the
bare body, removing synchronization.
"""
name = "concurrency"
language = "python"
defect_type = "concurrency_issue"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, ast.With):
continue
first_item = node.items[0]
ctx = first_item.context_expr
if isinstance(ctx, ast.Call) and isinstance(ctx.func, ast.Attribute) and ctx.func.attr == "acquire":
start = node.lineno
end = getattr(node, "end_lineno", node.lineno) or node.lineno
lines = source.splitlines(keepends=True)
body = lines[start:end]
dedented = []
for line in body[1:]:
if 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 `with lock:` to protect the critical section.",
description="Removed lock acquisition, exposing a race condition.",
)
return None
@@ -0,0 +1,44 @@
"""AST-level logical operator misuse injection for Python."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class LogicOperatorRule(MutationRule):
"""Swap `and` with `or` in a boolean expression.
Uses `ast` to locate a BoolOp using `And` and replaces it with `Or`,
preserving exact source position via line replacement.
"""
name = "logic_operator"
language = "python"
defect_type = "logic_operator_misuse"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
line_no = node.lineno
lines = source.splitlines(keepends=True)
line = lines[line_no - 1]
mutated_line = line.replace(" and ", " or ", 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=getattr(node, "end_lineno", line_no) or line_no,
mutated_source=mutated,
reference_fix="Restore the original `and` operator for correct short-circuit logic.",
description="Replaced boolean `and` with `or`.",
)
return None
@@ -0,0 +1,65 @@
"""AST-level null-pointer / None-reference injection for Python."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class NoneReferenceRule(MutationRule):
"""Replace a checked variable access with an unchecked None dereference.
This rule uses the standard library `ast` module to precisely locate a
variable that is used after an `if x is not None:` guard, then removes the
guard. The mutation position is derived from AST line numbers so it is
exact and reproducible.
"""
name = "none_reference"
language = "python"
defect_type = "null_pointer"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, ast.If):
continue
test = node.test
# Match: if x is not None:
if (
isinstance(test, ast.Compare)
and isinstance(test.left, ast.Name)
and len(test.ops) == 1
and isinstance(test.ops[0], ast.IsNot)
and len(test.comparators) == 1
and isinstance(test.comparators[0], ast.Constant)
and test.comparators[0].value is None
):
var_name = test.left.id
lines = source.splitlines(keepends=True)
start = node.lineno
end = getattr(node, "end_lineno", node.lineno) or node.lineno
body_lines = lines[start:end]
dedented = []
for line in body_lines[1:]:
if line.startswith(" "):
dedented.append(line[4:])
elif line.startswith("\t"):
dedented.append(line[1:])
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} is not None:` guard before use.",
description=f"Removed None-check guard for variable '{var_name}'.",
)
return None
@@ -0,0 +1,57 @@
"""AST-level resource leak injection for Python."""
import ast
from typing import Optional
from app.dataset.rules.base import Mutation, MutationRule
class ResourceLeakRule(MutationRule):
"""Convert a `with open(...)` block into an unclosed `open(...).read()`.
Uses `ast` to locate a with-statement managing a file resource and replaces
it with a direct call chain that leaks the file handle.
"""
name = "resource_leak"
language = "python"
defect_type = "resource_not_closed"
def detect_and_mutate(self, source: str, filename: str = "") -> Optional[Mutation]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, ast.With):
continue
first_item = node.items[0]
ctx = first_item.context_expr
if isinstance(ctx, ast.Call) and isinstance(ctx.func, ast.Name) and ctx.func.id == "open":
start = node.lineno
end = getattr(node, "end_lineno", node.lineno) or node.lineno
lines = source.splitlines(keepends=True)
# Keep the with header expression but replace 'with open(...)' by 'f = open(...)'
header = lines[start - 1]
header_expr = header.split("with ", 1)[1].split(" as ", 1)[0].strip().rstrip(":\n")
var = header.split(" as ", 1)[1].strip().rstrip(":\n") if " as " in header else "f"
body = lines[start:end]
dedented = []
for line in body[1:]:
if line.startswith(" "):
dedented.append(line[4:])
else:
dedented.append(line)
replacement = [f"{var} = {header_expr}\n"] + dedented
mutated = "".join(lines[: start - 1] + replacement + lines[end:])
return Mutation(
defect_type=self.defect_type,
language=self.language,
line_start=start,
line_end=end,
mutated_source=mutated,
reference_fix="Use `with open(...) as f:` to ensure the file is closed.",
description="Replaced context-managed open() with an unclosed file handle.",
)
return None