diff --git a/folly/coro/scripts/co_bt.py b/folly/coro/scripts/co_bt.py index 77181ca9630..2f2b0214bfc 100755 --- a/folly/coro/scripts/co_bt.py +++ b/folly/coro/scripts/co_bt.py @@ -98,7 +98,7 @@ def to_hex(self) -> str: pass @abc.abstractmethod - def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: + def get_file_name_and_line(self) -> tuple[str, int] | None: """ Returns the file name and line number of the value. Assumes the value is a pointer to an instruction. @@ -107,7 +107,7 @@ def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: pass @abc.abstractmethod - def get_func_name(self) -> Optional[str]: + def get_func_name(self) -> str | None: """ Returns the function name of the value. Returns None if the name could not be found @@ -206,7 +206,7 @@ def from_addr(addr: DebuggerValue) -> "StackFrame": def get_async_stack_root_addr( - debugger_value_class: Type[DebuggerValue], + debugger_value_class: type[DebuggerValue], ) -> DebuggerValue: """ Returns a pointer to the top-most async stack root, or a nullptr if none @@ -259,7 +259,7 @@ def get_async_stack_root_addr( return async_stack_root_holder.value -def print_async_stack_addrs(addrs: List[DebuggerValue]) -> None: +def print_async_stack_addrs(addrs: list[DebuggerValue]) -> None: if len(addrs) == 0: print("No async operation detected") return @@ -282,11 +282,11 @@ def print_async_stack_addrs(addrs: List[DebuggerValue]) -> None: def get_async_stack_addrs_from_initial_frame( async_stack_frame_addr: DebuggerValue, -) -> List[DebuggerValue]: +) -> list[DebuggerValue]: """ Gets the list of async stack frames rooted at the current frame """ - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] while not async_stack_frame_addr.is_nullptr(): async_stack_frame = AsyncStackFrame.from_addr(async_stack_frame_addr) addrs.append(async_stack_frame.instruction_pointer) @@ -297,12 +297,12 @@ def get_async_stack_addrs_from_initial_frame( def walk_normal_stack( normal_stack_frame_addr: DebuggerValue, normal_stack_frame_stop_addr: DebuggerValue, -) -> List[DebuggerValue]: +) -> list[DebuggerValue]: """ Returns the list of return addresses in the normal stack. Does not include stop_addr """ - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] while not normal_stack_frame_addr.is_nullptr(): normal_stack_frame = StackFrame.from_addr(normal_stack_frame_addr) if ( @@ -320,7 +320,7 @@ def walk_normal_stack( @dataclass class WalkAsyncStackResult: - addrs: List[DebuggerValue] + addrs: list[DebuggerValue] # Normal stack frame to start the next normal stack walk normal_stack_frame_addr: DebuggerValue normal_stack_frame_stop_addr: DebuggerValue @@ -330,14 +330,14 @@ class WalkAsyncStackResult: def walk_async_stack( - debugger_value_class: Type[DebuggerValue], + debugger_value_class: type[DebuggerValue], async_stack_frame_addr: DebuggerValue, ) -> WalkAsyncStackResult: """ Walks the async stack and returns the next normal stack and async stack addresses to walk. """ - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] normal_stack_frame_addr = debugger_value_class.nullptr() normal_stack_frame_stop_addr = debugger_value_class.nullptr() async_stack_frame_next_addr = debugger_value_class.nullptr() @@ -390,8 +390,8 @@ def walk_async_stack( def get_async_stack_addrs( - debugger_value_class: Type[DebuggerValue], -) -> List[DebuggerValue]: + debugger_value_class: type[DebuggerValue], +) -> list[DebuggerValue]: """ Gets the async stack trace, including normal stack frames with async stack frames. @@ -414,7 +414,7 @@ def get_async_stack_addrs( async_stack_root = AsyncStackRoot.from_addr(async_stack_root_addr) normal_stack_frame_addr = debugger_value_class.get_register("rbp") normal_stack_frame_stop_addr = async_stack_root.stack_frame_ptr - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] addrs.append(debugger_value_class.get_register("pc")) async_stack_frame_addr = async_stack_root.top_frame @@ -437,7 +437,7 @@ def get_async_stack_addrs( return addrs -def print_async_stack_root_addrs(addrs: List[DebuggerValue]) -> None: +def print_async_stack_root_addrs(addrs: list[DebuggerValue]) -> None: if len(addrs) == 0: print("No async stack roots detected") return @@ -468,12 +468,12 @@ def print_async_stack_root_addrs(addrs: List[DebuggerValue]) -> None: def get_async_stack_root_addrs( - debugger_value_class: Type[DebuggerValue], -) -> List[DebuggerValue]: + debugger_value_class: type[DebuggerValue], +) -> list[DebuggerValue]: """ Gets all the async stack roots that exist for the current thread. """ - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] async_stack_root_addr = get_async_stack_root_addr(debugger_value_class) while not async_stack_root_addr.is_nullptr(): addrs.append(async_stack_root_addr) @@ -483,11 +483,11 @@ def get_async_stack_root_addrs( def backtrace_command( - debugger_value_class: Type[DebuggerValue], - stack_root: Optional[str], + debugger_value_class: type[DebuggerValue], + stack_root: str | None, ) -> None: try: - addrs: List[DebuggerValue] = [] + addrs: list[DebuggerValue] = [] if stack_root: async_stack_root_addr = debugger_value_class.parse_and_eval(stack_root) if not async_stack_root_addr.is_nullptr(): @@ -503,7 +503,7 @@ def backtrace_command( traceback.print_exception(*sys.exc_info()) -def async_stack_roots_command(debugger_value_class: Type[DebuggerValue]) -> None: +def async_stack_roots_command(debugger_value_class: type[DebuggerValue]) -> None: addrs = get_async_stack_root_addrs(debugger_value_class) print_async_stack_root_addrs(addrs) @@ -529,7 +529,7 @@ class DebuggerType(enum.Enum): LLDB = 1 -debugger_type: Optional[DebuggerType] = None +debugger_type: DebuggerType | None = None if debugger_type is None: # noqa: C901 try: import gdb @@ -592,7 +592,7 @@ def int_value(self) -> int: def to_hex(self) -> str: return f"{int(self.value):#0{18}x}" - def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: + def get_file_name_and_line(self) -> tuple[str, int] | None: regex = re.compile(r"Line (\d+) of (.*) starts at.*") output = GdbValue.execute( f"info line *{self.to_hex()}", @@ -606,7 +606,7 @@ def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: else None ) - def get_func_name(self) -> Optional[str]: + def get_func_name(self) -> str | None: regex = re.compile(r"(.*) \+ \d+ in section.* of .*") output = GdbValue.execute( f"info symbol {self.to_hex()}", @@ -622,7 +622,7 @@ def __eq__(self, other) -> bool: class GdbCoroBacktraceCommand(gdb.Command): def __init__(self): print(co_bt_info()) - super(GdbCoroBacktraceCommand, self).__init__("co_bt", gdb.COMMAND_USER) + super().__init__("co_bt", gdb.COMMAND_USER) def invoke(self, arg: str, from_tty: bool): backtrace_command(GdbValue, arg) @@ -630,9 +630,7 @@ def invoke(self, arg: str, from_tty: bool): class GdbCoroAsyncStackRootsCommand(gdb.Command): def __init__(self): print(co_async_stack_root_info()) - super(GdbCoroAsyncStackRootsCommand, self).__init__( - "co_async_stack_roots", gdb.COMMAND_USER - ) + super().__init__("co_async_stack_roots", gdb.COMMAND_USER) def invoke(self, arg: str, from_tty: bool): async_stack_roots_command(GdbValue) @@ -650,7 +648,7 @@ class LldbValue(DebuggerValue): LLDB implementation of a debugger value """ - exe_ctx: ClassVar[Optional[lldb.SBExecutionContext]] = None + exe_ctx: ClassVar[lldb.SBExecutionContext | None] = None next_name_num: ClassVar[int] = 0 value: lldb.SBValue @@ -752,7 +750,7 @@ def _get_symbol_context(self) -> "lldb.SBSymbolContext": address, lldb.eSymbolContextEverything ) - def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: + def get_file_name_and_line(self) -> tuple[str, int] | None: symbol_context = self._get_symbol_context() line_entry = symbol_context.GetLineEntry() path = line_entry.GetFileSpec().fullpath @@ -760,7 +758,7 @@ def get_file_name_and_line(self) -> Optional[Tuple[str, int]]: return (path, line_entry.GetLine()) return None - def get_func_name(self) -> Optional[str]: + def get_func_name(self) -> str | None: symbol_context = self._get_symbol_context() if symbol_context.GetFunction().IsValid(): return symbol_context.GetFunction().GetDisplayName() diff --git a/folly/fibers/scripts/gdb.py b/folly/fibers/scripts/gdb.py index ebbf4180b0a..ccb629181d4 100644 --- a/folly/fibers/scripts/gdb.py +++ b/folly/fibers/scripts/gdb.py @@ -37,7 +37,7 @@ def __init__(self, val): state = self.val["state_"] d = gdb.types.make_enum_dict(state.type) - d = dict((v, k) for k, v in d.items()) + d = {v: k for k, v in d.items()} self.state = d[int(state)] def state_to_string(self): @@ -122,7 +122,7 @@ def __call__(self, *args): class GetFiberXMethodMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): - super(GetFiberXMethodMatcher, self).__init__("Fiber address method matcher") + super().__init__("Fiber address method matcher") self.worker = GetFiberXMethodWorker() def match(self, class_type, method_name): @@ -147,7 +147,7 @@ def __call__(self, *args): class FiberXMethodMatcher(gdb.xmethod.XMethodMatcher): def __init__(self): - super(FiberXMethodMatcher, self).__init__("Fiber method matcher") + super().__init__("Fiber method matcher") self.worker = FiberXMethodWorker() def match(self, class_type, method_name): @@ -212,7 +212,7 @@ def set_fiber(cls, fiber): ) def __init__(self): - super(FiberUnwinder, self).__init__("Fiber unwinder") + super().__init__("Fiber unwinder") self.fiber_context_ptr = None self.fiber = None @@ -319,7 +319,7 @@ class FiberCommand(gdb.Command): """ def __init__(self): - super(FiberCommand, self).__init__("fiber", gdb.COMMAND_USER, prefix=True) + super().__init__("fiber", gdb.COMMAND_USER, prefix=True) @use_language("c++") def invoke(self, arg, from_tty): @@ -331,7 +331,7 @@ def invoke(self, arg, from_tty): print("No fiber selected") else: info = FiberInfo(FiberUnwinder.instance.fiber) - print("[Current fiber is {id} ({info})]".format(id=info.id, info=info)) + print(f"[Current fiber is {info.id} ({info})]") return # look up fiber @@ -351,7 +351,7 @@ class FiberNameCommand(gdb.Command): If NAME is not given, then any existing name is removed""" def __init__(self): - super(FiberNameCommand, self).__init__("fiber name", gdb.COMMAND_USER) + super().__init__("fiber name", gdb.COMMAND_USER) def invoke(self, arg, from_tty): fiber = FiberUnwinder.get_fiber() @@ -371,9 +371,7 @@ class FiberInfoCommand(gdb.Command): """ def __init__(self): - super(FiberInfoCommand, self).__init__( - "info fibers", gdb.COMMAND_STATUS, prefix=True - ) + super().__init__("info fibers", gdb.COMMAND_STATUS, prefix=True) def trace_info(self, fiber, skip=()): # get the fiber symbol info if we can @@ -422,7 +420,7 @@ def invoke(self, arg, to_tty): for (mid, fid), info in get_fiber_info(only, managers=True): # track that we've seen this fiber/manager if fid: - seen.add("{}.{}".format(mid, fid)) + seen.add(f"{mid}.{fid}") seen.add(str(mid)) # If it's a manager, print the header and continue @@ -468,7 +466,7 @@ class FiberApplyCommand(gdb.Command): """ def __init__(self): - super(FiberApplyCommand, self).__init__("fiber apply", gdb.COMMAND_USER) + super().__init__("fiber apply", gdb.COMMAND_USER) def usage(self): raise gdb.Error("usage: fiber apply [ FIBER_FILTER [ ... ] | apply ] COMMAND") @@ -497,7 +495,7 @@ def invoke(self, arg, from_tty): try: # loop over, activating and running command in turn for _, info in get_fiber_info(targets): - print("Fiber {id} ({info})".format(id=info.id, info=info)) + print(f"Fiber {info.id} ({info})") fiber_activate(info.fiber) gdb.execute(command, from_tty=from_tty) finally: @@ -509,9 +507,7 @@ class FiberDeactivateCommand(gdb.Command): """Deactivates fiber processing, returning to normal thread processing""" def __init__(self): - super(FiberDeactivateCommand, self).__init__( - "fiber deactivate", gdb.COMMAND_USER - ) + super().__init__("fiber deactivate", gdb.COMMAND_USER) def invoke(self, arg, from_tty): if arg: @@ -529,9 +525,7 @@ class SetFiberCommand(gdb.Command): """Generic command for setting how fibers are handled""" def __init__(self): - super(SetFiberCommand, self).__init__( - "set fiber", gdb.COMMAND_DATA, prefix=True - ) + super().__init__("set fiber", gdb.COMMAND_DATA, prefix=True) def invoke(self, arg, from_tty): print('"set fiber" must be followed by the name of a fiber subcommand') @@ -544,9 +538,7 @@ class ShowFiberCommand(gdb.Command): REGISTRY = set() def __init__(self): - super(ShowFiberCommand, self).__init__( - "show fiber", gdb.COMMAND_DATA, prefix=True - ) + super().__init__("show fiber", gdb.COMMAND_DATA, prefix=True) def invoke(self, arg, from_tty): for name in sorted(self.REGISTRY): @@ -561,7 +553,7 @@ class FiberParameter(gdb.Parameter): """track fiber parameters to print all on "show fiber" command""" def __init__(self, name, *args, **kwds): - super(FiberParameter, self).__init__(name, *args, **kwds) + super().__init__(name, *args, **kwds) (category, _, parameter) = name.partition(" ") assert category == "fiber" ShowFiberCommand.REGISTRY.add(parameter) @@ -574,7 +566,7 @@ class FiberManagerPrintLimitParameter(FiberParameter): set_doc = "Set limit of fibers of a fiber manager to print" def __init__(self): - super(FiberManagerPrintLimitParameter, self).__init__( + super().__init__( "fiber manager-print-limit", gdb.COMMAND_DATA, gdb.PARAM_UINTEGER ) self.value = 100 @@ -596,7 +588,7 @@ class FiberInfoFrameSkipWordsParameter(FiberParameter): set_doc = "Set words to skip frames of in fiber info printing" def __init__(self): - super(FiberInfoFrameSkipWordsParameter, self).__init__( + super().__init__( "fiber info-frame-skip-words", gdb.COMMAND_DATA, gdb.PARAM_STRING ) self.value = "folly::fibers wait" @@ -604,7 +596,7 @@ def __init__(self): class Shortcut(gdb.Function): def __init__(self, function_name, value_lambda): - super(Shortcut, self).__init__(function_name) + super().__init__(function_name) self.value_lambda = value_lambda def invoke(self, *args): @@ -631,7 +623,7 @@ def __new__(cls, fiber): return cached # otherwise create a new one - obj = super(FiberInfo, cls).__new__(cls) + obj = super().__new__(cls) obj.fiber = fiber obj._name = "" obj.mid = None @@ -676,7 +668,7 @@ def __str__(self): return "Fiber {address} ({state}){name}".format( address=self.fiber.address, state=FiberPrinter(self.fiber).state_to_string(), - name=' "{}"'.format(self._name) if self._name else "", + name=f' "{self._name}"' if self._name else "", ) def __eq__(self, other): @@ -737,7 +729,7 @@ def get_fiber_info(only=None, managers=False): # first check if pre-cached if mid in get_fiber_info.cache: for fid, info in get_fiber_info.cache[mid].items(): - fiber_id = "{}.{}".format(mid, fid) + fiber_id = f"{mid}.{fid}" if not only or str(mid) in only or fiber_id in only: yield ((mid, fid), info) continue @@ -753,7 +745,7 @@ def get_fiber_info(only=None, managers=False): info.fid = fid fibers[fid] = info # output only if matching the filter - fiber_id = "{}.{}".format(mid, fid) + fiber_id = f"{mid}.{fid}" if not only or str(mid) in only or fiber_id in only: yield ((mid, fid), info) fid += 1 diff --git a/folly/logging/test/fatal_test.py b/folly/logging/test/fatal_test.py index ae6a44af6ef..46fb9c63c21 100644 --- a/folly/logging/test/fatal_test.py +++ b/folly/logging/test/fatal_test.py @@ -69,7 +69,7 @@ def is_debug_build(self): elif out.strip() == b"DEBUG=0": return False else: - self.fail("unexpected output from --check_debug: {}".format(out)) + self.fail(f"unexpected output from --check_debug: {out}") def get_crash_regex(self, msg=b"test program crashing!", glog=True): if glog: @@ -232,7 +232,7 @@ def _test_xcheck_cmp( args = ["--crash=no", "--" + flag, str(value)] if expect_failure: err = self.run_helper(*args) - expected_msg = "Check failed: FLAGS_%s %s 0 (%s vs. 0)%s" % ( + expected_msg = "Check failed: FLAGS_{} {} 0 ({} vs. 0){}".format( flag, op, value, diff --git a/folly/logging/test/log_after_main.py b/folly/logging/test/log_after_main.py index 4d25efb6e33..6138b2f8057 100644 --- a/folly/logging/test/log_after_main.py +++ b/folly/logging/test/log_after_main.py @@ -24,7 +24,7 @@ def find_helper(self, name, env_var): if path: if not os.access(path, os.X_OK): raise Exception( - "path specified by $%s does not exist: %r" % (env_var, path) + "path specified by ${} does not exist: {!r}".format(env_var, path) ) return path @@ -39,13 +39,12 @@ def find_helper(self, name, env_var): path = os.path.join(d, name) if os.access(path, os.X_OK): return path - raise Exception("unable to find helper program %r" % (name,)) + raise Exception("unable to find helper program {!r}".format(name)) def run_helper(self, cmd): return subprocess.run( cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, encoding="utf-8", errors="surrogateescape", ) @@ -55,7 +54,7 @@ def test_log_after_main(self): proc = self.run_helper([helper]) self.assertEqual(proc.stdout, "") self.assertIn("main running", proc.stderr) - self.assertEqual(proc.returncode, 0, "stderr: %s" % (proc.stderr,)) + self.assertEqual(proc.returncode, 0, "stderr: {}".format(proc.stderr)) def test_log_after_main_no_init(self): helper = self.find_helper( @@ -63,4 +62,4 @@ def test_log_after_main_no_init(self): ) proc = self.run_helper([helper]) self.assertEqual(proc.stdout, "") - self.assertEqual(proc.returncode, 0, "stderr: %s" % (proc.stderr,)) + self.assertEqual(proc.returncode, 0, "stderr: {}".format(proc.stderr)) diff --git a/folly/support/gdb.py b/folly/support/gdb.py index 084e3b1c168..66902e3d2ef 100644 --- a/folly/support/gdb.py +++ b/folly/support/gdb.py @@ -34,7 +34,7 @@ def escape_byte(b): else: # Escape non-printable bytes with octal, which is what GDB # uses when natively printing strings. - return "\\{0:03o}".format(b) + return f"\\{b:03o}" def repr_string(v, length): @@ -158,11 +158,11 @@ def to_string(self): if self.val["family_"] == socket.AF_INET: addr = self.val["addr_"]["ipV4Addr"]["addr_"]["bytes_"]["_M_elems"] for i in range(0, 4): - result += "{:d}.".format(int(addr[i])) + result += f"{int(addr[i]):d}." elif self.val["family_"] == socket.AF_INET6: addr = self.val["addr_"]["ipV6Addr"]["addr_"]["bytes_"]["_M_elems"] for i in range(0, 8): - result += "{:02x}{:02x}:".format(int(addr[2 * i]), int(addr[2 * i + 1])) + result += f"{int(addr[2 * i]):02x}{int(addr[2 * i + 1]):02x}:" else: return "unknown address family {}".format(self.val["family_"]) return result[:-1] @@ -315,8 +315,7 @@ def format_count(i): @staticmethod def flatten(list): for elt in list: - for i in elt: - yield i + yield from elt def children(self): counter = map(self.format_count, itertools.count())