Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 30 additions & 32 deletions fusil/python/write_python_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,25 +733,24 @@ def _fuzz_one_class(self, class_idx: int, class_name_str: str, class_type: type)

num_constructor_args = class_arg_number(class_name_str, class_type)
self.write(0, f"{instance_var_name} = None # Initialize instance variable")
# PoC of the indentation context manager: `with self.indented():` replaces the
# addLevel(1)/restoreLevel(self.base_level - 1) bookkeeping -- the block's nesting now
# mirrors the generated code's nesting and the level can't leak. Output is unchanged
# (guarded by tests/python/test_golden_output.py).
self.write(0, "try:")
self.addLevel(1)
self.write(
0, f"{instance_var_name} = callFunc('{prefix}_init', '{class_name_str}',"
) # prefix was from original _fuzz_one_class
self._write_arguments_for_call_lines(num_constructor_args, 1) # Indent args by 1
self.write(0, " )") # Close callFunc
self.restoreLevel(self.base_level - 1) # Exit try's indentation (level 1)
with self.indented():
self.write(0, f"{instance_var_name} = callFunc('{prefix}_init', '{class_name_str}',")
self._write_arguments_for_call_lines(num_constructor_args, 1) # Indent args by 1
self.write(0, " )") # Close callFunc
self.write(0, "except Exception as e_instantiate:")
self.addLevel(1) # Indent for except block contents
self.write(0, f"{instance_var_name} = None")
self.write_print_to_stderr(
0, # This 0 is relative to current base_level (which is parent's level + 1)
f'"[{prefix}] Failed to instantiate {class_name_str}: {{e_instantiate.__class__.__name__}} {{e_instantiate}}"',
)
# instance_var_name remains None if already set, or if callFunc returned None
# If callFunc might not set instance_var_name on error, set it explicitly:
self.write(0, f"{instance_var_name} = None")
self.restoreLevel(self.base_level - 1) # Exit except's indentation
with self.indented():
self.write(0, f"{instance_var_name} = None")
self.write_print_to_stderr(
0,
f'"[{prefix}] Failed to instantiate {class_name_str}: {{e_instantiate.__class__.__name__}} {{e_instantiate}}"',
)
# callFunc may not set instance_var_name on error, so set it explicitly.
self.write(0, f"{instance_var_name} = None")
self.emptyLine()

self._dispatch_fuzz_on_instance(
Expand All @@ -765,21 +764,20 @@ def _fuzz_one_class(self, class_idx: int, class_name_str: str, class_type: type)
self.write(
0, f"if {instance_var_name} is not None and {instance_var_name} is not SENTINEL_VALUE:"
)
current_level = self.addLevel(1)
# class_type is the type object of the class that was "instantiated"
self._fuzz_methods_on_object_or_specific_types(
current_prefix=f"{prefix}m", # prefix from _fuzz_one_class context, e.g., "o1m", "c1m"
target_obj_expr_str=instance_var_name,
target_obj_class_name=class_name_str, # Original class name string
target_obj_actual_type_obj=class_type, # The actual type object
num_method_calls_to_make=self.options.methods_number,
)
self.write(0, f"del {instance_var_name} # Cleanup instance")
self.write_print_to_stderr(
0, f'"[{prefix}] -explicit garbage collection for class instance-"'
)
self.write(0, "collect()")
self.restoreLevel(current_level)
with self.indented():
# class_type is the type object of the class that was "instantiated"
self._fuzz_methods_on_object_or_specific_types(
current_prefix=f"{prefix}m", # e.g. "o1m", "c1m"
target_obj_expr_str=instance_var_name,
target_obj_class_name=class_name_str, # Original class name string
target_obj_actual_type_obj=class_type, # The actual type object
num_method_calls_to_make=self.options.methods_number,
)
self.write(0, f"del {instance_var_name} # Cleanup instance")
self.write_print_to_stderr(
0, f'"[{prefix}] -explicit garbage collection for class instance-"'
)
self.write(0, "collect()")
self.emptyLine()

MAX_FUZZ_GENERATION_DEPTH = 2 # Adjust as needed; 3-5 is usually a good start
Expand Down
17 changes: 17 additions & 0 deletions fusil/write_code.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
import textwrap
from contextlib import contextmanager
from os import chmod
from textwrap import dedent

Expand Down Expand Up @@ -76,6 +77,22 @@ def restoreLevel(self, level):
raise ValueError("Negative indentation level in restoreLevel()")
self.base_level = level

@contextmanager
def indented(self, delta=1):
"""Scoped indentation: emit lines `delta` levels deeper inside the block, then
restore the previous level on exit (including on exception).

Replaces the manual ``saved = self.addLevel(1); ...; self.restoreLevel(saved)``
bookkeeping (and the error-prone ``restoreLevel(self.base_level - 1)`` form) with a
block whose nesting matches the generated code's nesting and can't leak a level.
Named ``indented`` (not ``indent``) because ``self.indent`` is the indent string.
"""
saved = self.addLevel(delta)
try:
yield
finally:
self.restoreLevel(saved)

def indentLine(self, level, text):
if not isinstance(text, str):
text = str(text, "ASCII")
Expand Down
11 changes: 9 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,15 @@ namespaces = false
[tool.ruff]
line-length = 100
target-version = "py313"
# Legacy / parked code is not maintained to the lint/format standard.
extend-exclude = ["fusil/notworking", "fuzzers/notworking", "tools/notworking"]
# Legacy / parked code is not maintained to the lint/format standard; the golden/
# directory holds generated fuzzer output (snapshots) that must stay byte-for-byte as
# emitted -- linting/formatting it is meaningless and would break the snapshots.
extend-exclude = [
"fusil/notworking",
"fuzzers/notworking",
"tools/notworking",
"tests/python/golden",
]

[tool.ruff.lint]
# Default rule set (pyflakes F + a subset of pycodestyle E) plus import sorting (I).
Expand Down
Loading
Loading