Coverage for cuda / core / _utils / enum_explanations_helpers.py: 96.49%

57 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-29 01:27 +0000

1# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 

2# SPDX-License-Identifier: Apache-2.0 

3 

4"""Internal support for error-enum explanations. 

5 

6``cuda_core`` keeps frozen 13.1.1 fallback tables for older ``cuda-bindings`` 

7releases. Driver/runtime error enums carry usable ``__doc__`` text starting in 

8the 12.x backport line at ``cuda-bindings`` 12.9.6, and in the mainline 13.x 

9series at ``cuda-bindings`` 13.2.0. This module decides which source to use 

10and normalizes generated docstrings so user-facing ``CUDAError`` messages stay 

11presentable. 

12 

13The cleanup rules here were derived while validating generated enum docstrings 

14in PR #1805. Keep them narrow and remove them when codegen quirks or fallback 

15support are no longer needed. 

16""" 

17 

18from __future__ import annotations 

19 

20import importlib.metadata 

21import re 

22from collections.abc import Callable 

23from typing import Any 

24 

25_MIN_12X_BINDING_VERSION_FOR_ENUM_DOCSTRINGS = (12, 9, 6) 

26_MIN_13X_BINDING_VERSION_FOR_ENUM_DOCSTRINGS = (13, 2, 0) 

27_RST_INLINE_ROLE_RE = re.compile(r":(?:[a-z]+:)?[a-z]+:`([^`]+)`") 

28_WORDWRAP_HYPHEN_AFTER_RE = re.compile(r"(?<=[0-9A-Za-z_])- (?=[0-9A-Za-z_])") 

29_WORDWRAP_HYPHEN_BEFORE_RE = re.compile(r"(?<=[0-9A-Za-z_]) -(?=[0-9A-Za-z_])") 

30_ExplanationTable = dict[int, str | tuple[str, ...]] 

31_ExplanationTableLoader = Callable[[], _ExplanationTable] 

32 

33 

34# ``version.pyx`` cannot be reused here (circular import via ``cuda_utils``). 

35def _binding_version() -> tuple[int, int, int]: 

36 """Return the installed ``cuda-bindings`` version, or a conservative old value.""" 

37 try: 

38 parts = importlib.metadata.version("cuda-bindings").split(".")[:3] 

39 except importlib.metadata.PackageNotFoundError: 

40 return (0, 0, 0) # For very old versions of cuda-python 

41 return tuple(int(v) for v in parts) 

42 

43 

44def _binding_version_has_usable_enum_docstrings(version: tuple[int, int, int]) -> bool: 

45 """Whether released bindings are known to carry usable error-enum ``__doc__`` text.""" 

46 return ( 1aTdefgUVWXYZNOPQbcR

47 _MIN_12X_BINDING_VERSION_FOR_ENUM_DOCSTRINGS <= version < (13, 0, 0) 

48 or version >= _MIN_13X_BINDING_VERSION_FOR_ENUM_DOCSTRINGS 

49 ) 

50 

51 

52def _fix_hyphenation_wordwrap_spacing(s: str) -> str: 

53 """Remove spaces around hyphens introduced by line wrapping in generated ``__doc__`` text. 

54 

55 This targets asymmetric wrap artifacts such as ``non- linear`` or 

56 ``GPU- Direct`` while leaving intentional ``a - b`` separators alone. 

57 """ 

58 prev = None 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

59 while prev != s: 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

60 prev = s 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

61 s = _WORDWRAP_HYPHEN_AFTER_RE.sub("-", s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

62 s = _WORDWRAP_HYPHEN_BEFORE_RE.sub("-", s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

63 return s 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

64 

65 

66def clean_enum_member_docstring(doc: str | None) -> str | None: 

67 """Turn an enum member ``__doc__`` into plain text. 

68 

69 The generated enum docstrings are already close to user-facing prose, but 

70 they may contain Sphinx inline roles, line wrapping, or a small known 

71 codegen defect. Normalize only those differences so the text is suitable 

72 for error messages. 

73 """ 

74 if doc is None: 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKSbc

75 return None 1S

76 s = doc 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

77 # Known codegen bug on cudaErrorIncompatibleDriverContext. Remove once fixed 

78 # in cuda-bindings code generation. 

79 s = s.replace("\n:py:obj:`~.Interactions`", ' "Interactions ') 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

80 # Drop a leading "~." or "." after removing the surrounding RST inline role. 

81 s = _RST_INLINE_ROLE_RE.sub(lambda m: re.sub(r"^~?\.", "", m.group(1)), s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

82 # Strip simple bold emphasis markers. 

83 s = re.sub(r"\*\*([^*]+)\*\*", r"\1", s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

84 # Strip simple italic emphasis markers. 

85 s = re.sub(r"\*([^*]+)\*", r"\1", s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

86 # Collapse wrapped lines and repeated spaces. 

87 s = re.sub(r"\s+", " ", s).strip() 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

88 s = _fix_hyphenation_wordwrap_spacing(s) 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

89 return s 1ijklmnopqrhdefgstuvwxyzABCDEFGHIJKbc

90 

91 

92class DocstringBackedExplanations: 

93 """Compatibility shim exposing enum-member ``__doc__`` text via ``dict.get``. 

94 

95 Keeps the existing ``.get(int(error))`` lookup shape used by ``cuda_utils.pyx``. 

96 """ 

97 

98 __slots__ = ("_enum_type",) 

99 

100 def __init__(self, enum_type: Any) -> None: 

101 self._enum_type = enum_type 1aLMNbcR

102 

103 def get(self, code: int, default: str | None = None) -> str | None: 

104 try: 1ijklmnopqrhdefgstuLMbc

105 member = self._enum_type(code) 1ijklmnopqrhdefgstuLMbc

106 except ValueError: 1M

107 return default 1M

108 

109 raw_doc = member.__doc__ 1ijklmnopqrhdefgstuLbc

110 if raw_doc is None: 1ijklmnopqrhdefgstuLbc

111 return default 1hL

112 

113 return clean_enum_member_docstring(raw_doc) 1ijklmnopqrhdefgstubc

114 

115 

116def get_best_available_explanations( 

117 enum_type: Any, 

118 fallback: _ExplanationTable | _ExplanationTableLoader, 

119) -> DocstringBackedExplanations | _ExplanationTable: 

120 """Pick one explanation source per bindings version. 

121 

122 Use enum-member ``__doc__`` only for bindings versions known to expose 

123 usable per-member text (12.9.6+ in the 12.x backport line, 13.2.0+ in the 

124 13.x mainline). Otherwise keep using the frozen 13.1.1 fallback tables. 

125 """ 

126 if not _binding_version_has_usable_enum_docstrings(_binding_version()): 1aNOPQbcR

127 if callable(fallback): 1OPQ

128 return fallback() 1O

129 return fallback 1PQ

130 return DocstringBackedExplanations(enum_type) 1aNbcR