| 1 |
from __future__ import annotations |
| 2 |
import dataclasses as dc |
| 3 |
import copy |
| 4 |
import enum |
| 5 |
import functools |
| 6 |
import inspect |
| 7 |
from collections.abc import Iterable, Iterator, Sequence |
| 8 |
from typing import Final, Any, TYPE_CHECKING |
| 9 |
if TYPE_CHECKING: |
| 10 |
from libclinic.converter import CConverter |
| 11 |
from libclinic.converters import self_converter |
| 12 |
from libclinic.return_converters import CReturnConverter |
| 13 |
from libclinic.app import Clinic |
| 14 |
|
| 15 |
from libclinic import VersionTuple, unspecified |
| 16 |
|
| 17 |
|
| 18 |
ClassDict = dict[str, "Class"] |
| 19 |
ModuleDict = dict[str, "Module"] |
| 20 |
ParamDict = dict[str, "Parameter"] |
| 21 |
|
| 22 |
|
| 23 |
@dc.dataclass(repr=False) |
| 24 |
class Module: |
| 25 |
name: str |
| 26 |
module: Module | Clinic |
| 27 |
|
| 28 |
def __post_init__(self) -> None: |
| 29 |
self.parent = self.module |
| 30 |
self.modules: ModuleDict = {} |
| 31 |
self.classes: ClassDict = {} |
| 32 |
self.functions: list[Function] = [] |
| 33 |
|
| 34 |
def __repr__(self) -> str: |
| 35 |
return "<clinic.Module " + repr(self.name) + " at " + str(id(self)) + ">" |
| 36 |
|
| 37 |
|
| 38 |
@dc.dataclass(repr=False) |
| 39 |
class Class: |
| 40 |
name: str |
| 41 |
module: Module | Clinic |
| 42 |
cls: Class | None |
| 43 |
typedef: str |
| 44 |
type_object: str |
| 45 |
|
| 46 |
def __post_init__(self) -> None: |
| 47 |
self.parent = self.cls or self.module |
| 48 |
self.classes: ClassDict = {} |
| 49 |
self.functions: list[Function] = [] |
| 50 |
|
| 51 |
def __repr__(self) -> str: |
| 52 |
return "<clinic.Class " + repr(self.name) + " at " + str(id(self)) + ">" |
| 53 |
|
| 54 |
|
| 55 |
class FunctionKind(enum.Enum): |
| 56 |
CALLABLE = enum.auto() |
| 57 |
STATIC_METHOD = enum.auto() |
| 58 |
CLASS_METHOD = enum.auto() |
| 59 |
METHOD_INIT = enum.auto() |
| 60 |
METHOD_NEW = enum.auto() |
| 61 |
GETTER = enum.auto() |
| 62 |
SETTER = enum.auto() |
| 63 |
|
| 64 |
@functools.cached_property |
| 65 |
def new_or_init(self) -> bool: |
| 66 |
return self in {FunctionKind.METHOD_INIT, FunctionKind.METHOD_NEW} |
| 67 |
|
| 68 |
def __repr__(self) -> str: |
| 69 |
return f"<clinic.FunctionKind.{self.name}>" |
| 70 |
|
| 71 |
|
| 72 |
CALLABLE: Final = FunctionKind.CALLABLE |
| 73 |
STATIC_METHOD: Final = FunctionKind.STATIC_METHOD |
| 74 |
CLASS_METHOD: Final = FunctionKind.CLASS_METHOD |
| 75 |
METHOD_INIT: Final = FunctionKind.METHOD_INIT |
| 76 |
METHOD_NEW: Final = FunctionKind.METHOD_NEW |
| 77 |
GETTER: Final = FunctionKind.GETTER |
| 78 |
SETTER: Final = FunctionKind.SETTER |
| 79 |
|
| 80 |
|
| 81 |
@dc.dataclass(repr=False) |
| 82 |
class Function: |
| 83 |
""" |
| 84 |
Mutable duck type for inspect.Function. |
| 85 |
|
| 86 |
docstring - a str containing |
| 87 |
* embedded line breaks |
| 88 |
* text outdented to the left margin |
| 89 |
* no trailing whitespace. |
| 90 |
It will always be true that |
| 91 |
(not docstring) or ((not docstring[0].isspace()) and (docstring.rstrip() == docstring)) |
| 92 |
""" |
| 93 |
parameters: ParamDict = dc.field(default_factory=dict) |
| 94 |
_: dc.KW_ONLY |
| 95 |
name: str |
| 96 |
module: Module | Clinic |
| 97 |
cls: Class | None |
| 98 |
c_basename: str |
| 99 |
full_name: str |
| 100 |
return_converter: CReturnConverter |
| 101 |
kind: FunctionKind |
| 102 |
coexist: bool |
| 103 |
return_annotation: object = inspect.Signature.empty |
| 104 |
docstring: str = '' |
| 105 |
# docstring_only means "don't generate a machine-readable |
| 106 |
# signature, just a normal docstring". it's True for |
| 107 |
# functions with optional groups because we can't represent |
| 108 |
# those accurately with inspect.Signature in 3.4. |
| 109 |
docstring_only: bool = False |
| 110 |
forced_text_signature: str | None = None |
| 111 |
critical_section: bool = False |
| 112 |
disable_fastcall: bool = False |
| 113 |
target_critical_section: list[str] = dc.field(default_factory=list) |
| 114 |
|
| 115 |
def __post_init__(self) -> None: |
| 116 |
self.parent = self.cls or self.module |
| 117 |
self.self_converter: self_converter | None = None |
| 118 |
self.__render_parameters__: list[Parameter] | None = None |
| 119 |
|
| 120 |
@functools.cached_property |
| 121 |
def displayname(self) -> str: |
| 122 |
"""Pretty-printable name.""" |
| 123 |
if self.kind.new_or_init: |
| 124 |
assert isinstance(self.cls, Class) |
| 125 |
return self.cls.name |
| 126 |
else: |
| 127 |
return self.name |
| 128 |
|
| 129 |
@functools.cached_property |
| 130 |
def fulldisplayname(self) -> str: |
| 131 |
parent: Class | Module | Clinic | None |
| 132 |
if self.kind.new_or_init: |
| 133 |
parent = getattr(self.cls, "parent", None) |
| 134 |
else: |
| 135 |
parent = self.parent |
| 136 |
name = self.displayname |
| 137 |
while isinstance(parent, (Module, Class)): |
| 138 |
name = f"{parent.name}.{name}" |
| 139 |
parent = parent.parent |
| 140 |
return name |
| 141 |
|
| 142 |
@property |
| 143 |
def render_parameters(self) -> list[Parameter]: |
| 144 |
if not self.__render_parameters__: |
| 145 |
l: list[Parameter] = [] |
| 146 |
self.__render_parameters__ = l |
| 147 |
for p in self.parameters.values(): |
| 148 |
p = p.copy() |
| 149 |
p.converter.pre_render() |
| 150 |
l.append(p) |
| 151 |
return self.__render_parameters__ |
| 152 |
|
| 153 |
@property |
| 154 |
def methoddef_flags(self) -> str | None: |
| 155 |
if self.kind.new_or_init: |
| 156 |
return None |
| 157 |
flags = [] |
| 158 |
match self.kind: |
| 159 |
case FunctionKind.CLASS_METHOD: |
| 160 |
flags.append('METH_CLASS') |
| 161 |
case FunctionKind.STATIC_METHOD: |
| 162 |
flags.append('METH_STATIC') |
| 163 |
case _ as kind: |
| 164 |
acceptable_kinds = {FunctionKind.CALLABLE, FunctionKind.GETTER, FunctionKind.SETTER} |
| 165 |
assert kind in acceptable_kinds, f"unknown kind: {kind!r}" |
| 166 |
if self.coexist: |
| 167 |
flags.append('METH_COEXIST') |
| 168 |
return '|'.join(flags) |
| 169 |
|
| 170 |
def __repr__(self) -> str: |
| 171 |
return f'<clinic.Function {self.name!r}>' |
| 172 |
|
| 173 |
def copy(self, **overrides: Any) -> Function: |
| 174 |
f = dc.replace(self, **overrides) |
| 175 |
f.parameters = { |
| 176 |
name: value.copy(function=f) |
| 177 |
for name, value in f.parameters.items() |
| 178 |
} |
| 179 |
return f |
| 180 |
|
| 181 |
|
| 182 |
@dc.dataclass(repr=False, slots=True) |
| 183 |
class Parameter: |
| 184 |
""" |
| 185 |
Mutable duck type of inspect.Parameter. |
| 186 |
""" |
| 187 |
name: str |
| 188 |
kind: inspect._ParameterKind |
| 189 |
_: dc.KW_ONLY |
| 190 |
default: object = inspect.Parameter.empty |
| 191 |
function: Function |
| 192 |
converter: CConverter |
| 193 |
annotation: object = inspect.Parameter.empty |
| 194 |
docstring: str = '' |
| 195 |
group: int = 0 |
| 196 |
# (`None` signifies that there is no deprecation) |
| 197 |
deprecated_positional: VersionTuple | None = None |
| 198 |
deprecated_keyword: VersionTuple | None = None |
| 199 |
right_bracket_count: int = dc.field(init=False, default=0) |
| 200 |
|
| 201 |
def __repr__(self) -> str: |
| 202 |
return f'<clinic.Parameter {self.name!r}>' |
| 203 |
|
| 204 |
def is_keyword_only(self) -> bool: |
| 205 |
return self.kind == inspect.Parameter.KEYWORD_ONLY |
| 206 |
|
| 207 |
def is_positional_only(self) -> bool: |
| 208 |
return self.kind == inspect.Parameter.POSITIONAL_ONLY |
| 209 |
|
| 210 |
def is_vararg(self) -> bool: |
| 211 |
return self.kind == inspect.Parameter.VAR_POSITIONAL |
| 212 |
|
| 213 |
def is_optional(self) -> bool: |
| 214 |
return not self.is_vararg() and (self.default is not unspecified) |
| 215 |
|
| 216 |
def copy( |
| 217 |
self, |
| 218 |
/, |
| 219 |
*, |
| 220 |
converter: CConverter | None = None, |
| 221 |
function: Function | None = None, |
| 222 |
**overrides: Any |
| 223 |
) -> Parameter: |
| 224 |
function = function or self.function |
| 225 |
if not converter: |
| 226 |
converter = copy.copy(self.converter) |
| 227 |
converter.function = function |
| 228 |
return dc.replace(self, **overrides, function=function, converter=converter) |
| 229 |
|
| 230 |
def get_displayname(self, i: int) -> str: |
| 231 |
if i == 0: |
| 232 |
return 'argument' |
| 233 |
if not self.is_positional_only(): |
| 234 |
return f'argument {self.name!r}' |
| 235 |
else: |
| 236 |
return f'argument {i}' |
| 237 |
|
| 238 |
def render_docstring(self) -> str: |
| 239 |
lines = [f" {self.name}"] |
| 240 |
lines.extend(f" {line}" for line in self.docstring.split("\n")) |
| 241 |
return "\n".join(lines).rstrip() |
| 242 |
|
| 243 |
|
| 244 |
ParamTuple = tuple["Parameter", ...] |
| 245 |
|
| 246 |
|
| 247 |
def permute_left_option_groups( |
| 248 |
l: Sequence[Iterable[Parameter]] |
| 249 |
) -> Iterator[ParamTuple]: |
| 250 |
""" |
| 251 |
Given [(1,), (2,), (3,)], should yield: |
| 252 |
() |
| 253 |
(3,) |
| 254 |
(2, 3) |
| 255 |
(1, 2, 3) |
| 256 |
""" |
| 257 |
yield tuple() |
| 258 |
accumulator: list[Parameter] = [] |
| 259 |
for group in reversed(l): |
| 260 |
accumulator = list(group) + accumulator |
| 261 |
yield tuple(accumulator) |
| 262 |
|
| 263 |
|
| 264 |
def permute_right_option_groups( |
| 265 |
l: Sequence[Iterable[Parameter]] |
| 266 |
) -> Iterator[ParamTuple]: |
| 267 |
""" |
| 268 |
Given [(1,), (2,), (3,)], should yield: |
| 269 |
() |
| 270 |
(1,) |
| 271 |
(1, 2) |
| 272 |
(1, 2, 3) |
| 273 |
""" |
| 274 |
yield tuple() |
| 275 |
accumulator: list[Parameter] = [] |
| 276 |
for group in l: |
| 277 |
accumulator.extend(group) |
| 278 |
yield tuple(accumulator) |
| 279 |
|
| 280 |
|
| 281 |
def permute_optional_groups( |
| 282 |
left: Sequence[Iterable[Parameter]], |
| 283 |
required: Iterable[Parameter], |
| 284 |
right: Sequence[Iterable[Parameter]] |
| 285 |
) -> tuple[ParamTuple, ...]: |
| 286 |
""" |
| 287 |
Generator function that computes the set of acceptable |
| 288 |
argument lists for the provided iterables of |
| 289 |
argument groups. (Actually it generates a tuple of tuples.) |
| 290 |
|
| 291 |
Algorithm: prefer left options over right options. |
| 292 |
|
| 293 |
If required is empty, left must also be empty. |
| 294 |
""" |
| 295 |
required = tuple(required) |
| 296 |
if not required: |
| 297 |
if left: |
| 298 |
raise ValueError("required is empty but left is not") |
| 299 |
|
| 300 |
accumulator: list[ParamTuple] = [] |
| 301 |
counts = set() |
| 302 |
for r in permute_right_option_groups(right): |
| 303 |
for l in permute_left_option_groups(left): |
| 304 |
t = l + required + r |
| 305 |
if len(t) in counts: |
| 306 |
continue |
| 307 |
counts.add(len(t)) |
| 308 |
accumulator.append(t) |
| 309 |
|
| 310 |
accumulator.sort(key=len) |
| 311 |
return tuple(accumulator) |