Elffuss BraidHub

kikocis/llama-stack public

main · 13.1 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7"""
8Type-safe data interchange for Python data classes.
9
10:see: https://github.com/hunyadi/strong_typing
11"""
12
13import builtins
14import dataclasses
15import inspect
16import re
17import sys
18import types
19import typing
20from dataclasses import dataclass
21from io import StringIO
22from typing import Any, Callable, Dict, Optional, Protocol, Type, TypeVar
23
24if sys.version_info >= (3, 10):
25 from typing import TypeGuard
26else:
27 from typing_extensions import TypeGuard
28
29from .inspection import (
30 DataclassInstance,
31 get_class_properties,
32 get_signature,
33 is_dataclass_type,
34 is_type_enum,
35)
36
37T = TypeVar("T")
38
39
40@dataclass
41class DocstringParam:
42 """
43 A parameter declaration in a parameter block.
44
45 :param name: The name of the parameter.
46 :param description: The description text for the parameter.
47 """
48
49 name: str
50 description: str
51 param_type: type = inspect.Signature.empty
52
53 def __str__(self) -> str:
54 return f":param {self.name}: {self.description}"
55
56
57@dataclass
58class DocstringReturns:
59 """
60 A `returns` declaration extracted from a docstring.
61
62 :param description: The description text for the return value.
63 """
64
65 description: str
66 return_type: type = inspect.Signature.empty
67
68 def __str__(self) -> str:
69 return f":returns: {self.description}"
70
71
72@dataclass
73class DocstringRaises:
74 """
75 A `raises` declaration extracted from a docstring.
76
77 :param typename: The type name of the exception raised.
78 :param description: The description associated with the exception raised.
79 """
80
81 typename: str
82 description: str
83 raise_type: type = inspect.Signature.empty
84
85 def __str__(self) -> str:
86 return f":raises {self.typename}: {self.description}"
87
88
89@dataclass
90class Docstring:
91 """
92 Represents the documentation string (a.k.a. docstring) for a type such as a (data) class or function.
93
94 A docstring is broken down into the following components:
95 * A short description, which is the first block of text in the documentation string, and ends with a double
96 newline or a parameter block.
97 * A long description, which is the optional block of text following the short description, and ends with
98 a parameter block.
99 * A parameter block of named parameter and description string pairs in ReST-style.
100 * A `returns` declaration, which adds explanation to the return value.
101 * A `raises` declaration, which adds explanation to the exception type raised by the function on error.
102
103 When the docstring is attached to a data class, it is understood as the documentation string of the class
104 `__init__` method.
105
106 :param short_description: The short description text parsed from a docstring.
107 :param long_description: The long description text parsed from a docstring.
108 :param params: The parameter block extracted from a docstring.
109 :param returns: The returns declaration extracted from a docstring.
110 """
111
112 short_description: Optional[str] = None
113 long_description: Optional[str] = None
114 params: Dict[str, DocstringParam] = dataclasses.field(default_factory=dict)
115 returns: Optional[DocstringReturns] = None
116 raises: Dict[str, DocstringRaises] = dataclasses.field(default_factory=dict)
117
118 @property
119 def full_description(self) -> Optional[str]:
120 if self.short_description and self.long_description:
121 return f"{self.short_description}\n\n{self.long_description}"
122 elif self.short_description:
123 return self.short_description
124 else:
125 return None
126
127 def __str__(self) -> str:
128 output = StringIO()
129
130 has_description = self.short_description or self.long_description
131 has_blocks = self.params or self.returns or self.raises
132
133 if has_description:
134 if self.short_description and self.long_description:
135 output.write(self.short_description)
136 output.write("\n\n")
137 output.write(self.long_description)
138 elif self.short_description:
139 output.write(self.short_description)
140
141 if has_blocks:
142 if has_description:
143 output.write("\n")
144
145 for param in self.params.values():
146 output.write("\n")
147 output.write(str(param))
148 if self.returns:
149 output.write("\n")
150 output.write(str(self.returns))
151 for raises in self.raises.values():
152 output.write("\n")
153 output.write(str(raises))
154
155 s = output.getvalue()
156 output.close()
157 return s
158
159
160def is_exception(member: object) -> TypeGuard[Type[BaseException]]:
161 return isinstance(member, type) and issubclass(member, BaseException)
162
163
164def get_exceptions(module: types.ModuleType) -> Dict[str, Type[BaseException]]:
165 "Returns all exception classes declared in a module."
166
167 return {
168 name: class_type
169 for name, class_type in inspect.getmembers(module, is_exception)
170 }
171
172
173class SupportsDoc(Protocol):
174 __doc__: Optional[str]
175
176
177def parse_type(typ: SupportsDoc) -> Docstring:
178 """
179 Parse the docstring of a type into its components.
180
181 :param typ: The type whose documentation string to parse.
182 :returns: Components of the documentation string.
183 """
184
185 doc = get_docstring(typ)
186 if doc is None:
187 return Docstring()
188
189 docstring = parse_text(doc)
190 check_docstring(typ, docstring)
191
192 # assign parameter and return types
193 if is_dataclass_type(typ):
194 properties = dict(get_class_properties(typing.cast(type, typ)))
195
196 for name, param in docstring.params.items():
197 param.param_type = properties[name]
198
199 elif inspect.isfunction(typ):
200 signature = get_signature(typ)
201 for name, param in docstring.params.items():
202 param.param_type = signature.parameters[name].annotation
203 if docstring.returns:
204 docstring.returns.return_type = signature.return_annotation
205
206 # assign exception types
207 defining_module = inspect.getmodule(typ)
208 if defining_module:
209 context: Dict[str, type] = {}
210 context.update(get_exceptions(builtins))
211 context.update(get_exceptions(defining_module))
212 for exc_name, exc in docstring.raises.items():
213 raise_type = context.get(exc_name)
214 if raise_type is None:
215 type_name = (
216 getattr(typ, "__qualname__", None)
217 or getattr(typ, "__name__", None)
218 or None
219 )
220 raise TypeError(
221 f"doc-string exception type `{exc_name}` is not an exception defined in the context of `{type_name}`"
222 )
223
224 exc.raise_type = raise_type
225
226 return docstring
227
228
229def parse_text(text: str) -> Docstring:
230 """
231 Parse a ReST-style docstring into its components.
232
233 :param text: The documentation string to parse, typically acquired as `type.__doc__`.
234 :returns: Components of the documentation string.
235 """
236
237 if not text:
238 return Docstring()
239
240 # find block that starts object metadata block (e.g. `:param p:` or `:returns:`)
241 text = inspect.cleandoc(text)
242 match = re.search("^:", text, flags=re.MULTILINE)
243 if match:
244 desc_chunk = text[: match.start()]
245 meta_chunk = text[match.start() :] # noqa: E203
246 else:
247 desc_chunk = text
248 meta_chunk = ""
249
250 # split description text into short and long description
251 parts = desc_chunk.split("\n\n", 1)
252
253 # ensure short description has no newlines
254 short_description = parts[0].strip().replace("\n", " ") or None
255
256 # ensure long description preserves its structure (e.g. preformatted text)
257 if len(parts) > 1:
258 long_description = parts[1].strip() or None
259 else:
260 long_description = None
261
262 params: Dict[str, DocstringParam] = {}
263 raises: Dict[str, DocstringRaises] = {}
264 returns = None
265 for match in re.finditer(
266 r"(^:.*?)(?=^:|\Z)", meta_chunk, flags=re.DOTALL | re.MULTILINE
267 ):
268 chunk = match.group(0)
269 if not chunk:
270 continue
271
272 args_chunk, desc_chunk = chunk.lstrip(":").split(":", 1)
273 args = args_chunk.split()
274 desc = re.sub(r"\s+", " ", desc_chunk.strip())
275
276 if len(args) > 0:
277 kw = args[0]
278 if len(args) == 2:
279 if kw == "param":
280 params[args[1]] = DocstringParam(
281 name=args[1],
282 description=desc,
283 )
284 elif kw == "raise" or kw == "raises":
285 raises[args[1]] = DocstringRaises(
286 typename=args[1],
287 description=desc,
288 )
289
290 elif len(args) == 1:
291 if kw == "return" or kw == "returns":
292 returns = DocstringReturns(description=desc)
293
294 return Docstring(
295 long_description=long_description,
296 short_description=short_description,
297 params=params,
298 returns=returns,
299 raises=raises,
300 )
301
302
303def has_default_docstring(typ: SupportsDoc) -> bool:
304 "Check if class has the auto-generated string assigned by @dataclass."
305
306 if not isinstance(typ, type):
307 return False
308
309 if is_dataclass_type(typ):
310 return (
311 typ.__doc__ is not None
312 and re.match(f"^{re.escape(typ.__name__)}[(].*[)]$", typ.__doc__)
313 is not None
314 )
315
316 if is_type_enum(typ):
317 return typ.__doc__ is not None and typ.__doc__ == "An enumeration."
318
319 return False
320
321
322def has_docstring(typ: SupportsDoc) -> bool:
323 "Check if class has a documentation string other than the auto-generated string assigned by @dataclass."
324
325 if has_default_docstring(typ):
326 return False
327
328 return bool(typ.__doc__)
329
330
331def get_docstring(typ: SupportsDoc) -> Optional[str]:
332 if typ.__doc__ is None:
333 return None
334
335 if has_default_docstring(typ):
336 return None
337
338 return typ.__doc__
339
340
341def check_docstring(
342 typ: SupportsDoc, docstring: Docstring, strict: bool = False
343) -> None:
344 """
345 Verifies the doc-string of a type.
346
347 :raises TypeError: Raised on a mismatch between doc-string parameters, and function or type signature.
348 """
349
350 if is_dataclass_type(typ):
351 check_dataclass_docstring(typ, docstring, strict)
352 elif inspect.isfunction(typ):
353 check_function_docstring(typ, docstring, strict)
354
355
356def check_dataclass_docstring(
357 typ: Type[DataclassInstance], docstring: Docstring, strict: bool = False
358) -> None:
359 """
360 Verifies the doc-string of a data-class type.
361
362 :param strict: Whether to check if all data-class members have doc-strings.
363 :raises TypeError: Raised on a mismatch between doc-string parameters and data-class members.
364 """
365
366 if not is_dataclass_type(typ):
367 raise TypeError("not a data-class type")
368
369 properties = dict(get_class_properties(typ))
370 class_name = typ.__name__
371
372 for name in docstring.params:
373 if name not in properties:
374 raise TypeError(
375 f"doc-string parameter `{name}` is not a member of the data-class `{class_name}`"
376 )
377
378 if not strict:
379 return
380
381 for name in properties:
382 if name not in docstring.params:
383 raise TypeError(
384 f"member `{name}` in data-class `{class_name}` is missing its doc-string"
385 )
386
387
388def check_function_docstring(
389 fn: Callable[..., Any], docstring: Docstring, strict: bool = False
390) -> None:
391 """
392 Verifies the doc-string of a function or member function.
393
394 :param strict: Whether to check if all function parameters and the return type have doc-strings.
395 :raises TypeError: Raised on a mismatch between doc-string parameters and function signature.
396 """
397
398 signature = get_signature(fn)
399 func_name = fn.__qualname__
400
401 for name in docstring.params:
402 if name not in signature.parameters:
403 raise TypeError(
404 f"doc-string parameter `{name}` is absent from signature of function `{func_name}`"
405 )
406
407 if (
408 docstring.returns is not None
409 and signature.return_annotation is inspect.Signature.empty
410 ):
411 raise TypeError(
412 f"doc-string has returns description in function `{func_name}` with no return type annotation"
413 )
414
415 if not strict:
416 return
417
418 for name, param in signature.parameters.items():
419 # ignore `self` in member function signatures
420 if name == "self" and (
421 param.kind is inspect.Parameter.POSITIONAL_ONLY
422 or param.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
423 ):
424 continue
425
426 if name not in docstring.params:
427 raise TypeError(
428 f"function parameter `{name}` in `{func_name}` is missing its doc-string"
429 )
430
431 if (
432 signature.return_annotation is not inspect.Signature.empty
433 and docstring.returns is None
434 ):
435 raise TypeError(
436 f"function `{func_name}` has no returns description in its doc-string"
437 )