|
| 1 | +"""Built-in extension adding support for dataclasses. |
| 2 | +
|
| 3 | +This extension re-creates `__init__` methods of dataclasses |
| 4 | +during static analysis. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import ast |
| 10 | +from contextlib import suppress |
| 11 | +from functools import lru_cache |
| 12 | +from typing import Any, cast |
| 13 | + |
| 14 | +from griffe.dataclasses import Attribute, Class, Decorator, Function, Module, Parameter, Parameters |
| 15 | +from griffe.enumerations import ParameterKind |
| 16 | +from griffe.expressions import ( |
| 17 | + Expr, |
| 18 | + ExprAttribute, |
| 19 | + ExprCall, |
| 20 | + ExprDict, |
| 21 | +) |
| 22 | +from griffe.extensions.base import Extension |
| 23 | + |
| 24 | + |
| 25 | +def _dataclass_decorator(decorators: list[Decorator]) -> Expr | None: |
| 26 | + for decorator in decorators: |
| 27 | + if isinstance(decorator.value, Expr) and decorator.value.canonical_path == "dataclasses.dataclass": |
| 28 | + return decorator.value |
| 29 | + return None |
| 30 | + |
| 31 | + |
| 32 | +def _expr_args(expr: Expr) -> dict[str, str | Expr]: |
| 33 | + args = {} |
| 34 | + if isinstance(expr, ExprCall): |
| 35 | + for argument in expr.arguments: |
| 36 | + try: |
| 37 | + args[argument.name] = argument.value # type: ignore[union-attr] |
| 38 | + except AttributeError: |
| 39 | + # Argument is a unpacked variable. |
| 40 | + with suppress(Exception): |
| 41 | + collection = expr.function.parent.modules_collection # type: ignore[attr-defined] |
| 42 | + var = collection[argument.value.canonical_path] # type: ignore[union-attr] |
| 43 | + args.update(_expr_args(var.value)) |
| 44 | + elif isinstance(expr, ExprDict): |
| 45 | + args.update({ast.literal_eval(str(key)): value for key, value in zip(expr.keys, expr.values)}) |
| 46 | + return args |
| 47 | + |
| 48 | + |
| 49 | +def _dataclass_arguments(decorators: list[Decorator]) -> dict[str, Any]: |
| 50 | + if (expr := _dataclass_decorator(decorators)) and isinstance(expr, ExprCall): |
| 51 | + return _expr_args(expr) |
| 52 | + return {} |
| 53 | + |
| 54 | + |
| 55 | +def _field_arguments(attribute: Attribute) -> dict[str, Any]: |
| 56 | + if attribute.value: |
| 57 | + value = attribute.value |
| 58 | + if isinstance(value, ExprAttribute): |
| 59 | + value = value.last |
| 60 | + if isinstance(value, ExprCall) and value.canonical_path == "dataclasses.field": |
| 61 | + return _expr_args(value) |
| 62 | + return {} |
| 63 | + |
| 64 | + |
| 65 | +@lru_cache(maxsize=None) |
| 66 | +def _dataclass_parameters(class_: Class) -> list[Parameter]: |
| 67 | + # Fetch `@dataclass` arguments if any. |
| 68 | + dec_args = _dataclass_arguments(class_.decorators) |
| 69 | + |
| 70 | + # Parameters not added to `__init__`, return empty list. |
| 71 | + if dec_args.get("init") == "False": |
| 72 | + return [] |
| 73 | + |
| 74 | + # All parameters marked as keyword-only. |
| 75 | + kw_only = dec_args.get("kw_only") == "True" |
| 76 | + |
| 77 | + # Iterate on current attributes to find parameters. |
| 78 | + parameters = [] |
| 79 | + for member in class_.members.values(): |
| 80 | + if member.is_attribute: |
| 81 | + member = cast(Attribute, member) |
| 82 | + |
| 83 | + # Start of keyword-only parameters. |
| 84 | + if isinstance(member.annotation, Expr) and member.annotation.canonical_path == "dataclasses.KW_ONLY": |
| 85 | + kw_only = True |
| 86 | + continue |
| 87 | + |
| 88 | + # Fetch `field` arguments if any. |
| 89 | + field_args = _field_arguments(member) |
| 90 | + |
| 91 | + # Parameter not added to `__init__`, skip it. |
| 92 | + if field_args.get("init") == "False": |
| 93 | + continue |
| 94 | + |
| 95 | + # Determine parameter kind. |
| 96 | + kind = ( |
| 97 | + ParameterKind.keyword_only |
| 98 | + if kw_only or field_args.get("kw_only") == "True" |
| 99 | + else ParameterKind.positional_or_keyword |
| 100 | + ) |
| 101 | + |
| 102 | + # Determine parameter default. |
| 103 | + if "default_factory" in field_args: |
| 104 | + default = ExprCall(function=field_args["default_factory"], arguments=[]) |
| 105 | + else: |
| 106 | + default = field_args.get("default", None if field_args else member.value) |
| 107 | + |
| 108 | + # Add parameter to the list. |
| 109 | + parameters.append( |
| 110 | + Parameter( |
| 111 | + member.name, |
| 112 | + annotation=member.annotation, |
| 113 | + kind=kind, |
| 114 | + default=default, |
| 115 | + ), |
| 116 | + ) |
| 117 | + |
| 118 | + return parameters |
| 119 | + |
| 120 | + |
| 121 | +def _reorder_parameters(parameters: list[Parameter]) -> list[Parameter]: |
| 122 | + # De-duplicate, overwriting previous parameters. |
| 123 | + params_dict = {param.name: param for param in parameters} |
| 124 | + |
| 125 | + # Re-order, putting positional-only in front and keyword-only at the end. |
| 126 | + pos_only = [] |
| 127 | + pos_kw = [] |
| 128 | + kw_only = [] |
| 129 | + for param in params_dict.values(): |
| 130 | + if param.kind is ParameterKind.positional_only: |
| 131 | + pos_only.append(param) |
| 132 | + elif param.kind is ParameterKind.keyword_only: |
| 133 | + kw_only.append(param) |
| 134 | + else: |
| 135 | + pos_kw.append(param) |
| 136 | + return pos_only + pos_kw + kw_only |
| 137 | + |
| 138 | + |
| 139 | +def _set_dataclass_init(class_: Class) -> None: |
| 140 | + # Retrieve parameters from all parent dataclasses. |
| 141 | + parameters = [] |
| 142 | + try: |
| 143 | + mro = class_.mro() |
| 144 | + except ValueError: |
| 145 | + mro = () # type: ignore[assignment] |
| 146 | + for parent in reversed(mro): |
| 147 | + if _dataclass_decorator(parent.decorators): |
| 148 | + parameters.extend(_dataclass_parameters(parent)) |
| 149 | + # At least one parent dataclass makes the current class a dataclass: |
| 150 | + # that's how `dataclasses.is_dataclass` works. |
| 151 | + class_.labels.add("dataclass") |
| 152 | + |
| 153 | + # If the class is not decorated with `@dataclass`, skip it. |
| 154 | + if not _dataclass_decorator(class_.decorators): |
| 155 | + return |
| 156 | + |
| 157 | + # Add current class parameters. |
| 158 | + parameters.extend(_dataclass_parameters(class_)) |
| 159 | + |
| 160 | + # Create `__init__` method with re-ordered parameters. |
| 161 | + init = Function( |
| 162 | + "__init__", |
| 163 | + lineno=0, |
| 164 | + endlineno=0, |
| 165 | + parent=class_, |
| 166 | + parameters=Parameters( |
| 167 | + Parameter(name="self", annotation=None, kind=ParameterKind.positional_or_keyword, default=None), |
| 168 | + *_reorder_parameters(parameters), |
| 169 | + ), |
| 170 | + returns="None", |
| 171 | + ) |
| 172 | + class_.set_member("__init__", init) |
| 173 | + |
| 174 | + |
| 175 | +def _apply_recursively(mod_cls: Module | Class, processed: set[str]) -> None: |
| 176 | + if mod_cls.canonical_path in processed: |
| 177 | + return |
| 178 | + processed.add(mod_cls.canonical_path) |
| 179 | + if isinstance(mod_cls, Class): |
| 180 | + if "__init__" not in mod_cls.members: |
| 181 | + _set_dataclass_init(mod_cls) |
| 182 | + for member in mod_cls.members.values(): |
| 183 | + if not member.is_alias and member.is_class: |
| 184 | + _apply_recursively(member, processed) # type: ignore[arg-type] |
| 185 | + elif isinstance(mod_cls, Module): |
| 186 | + for member in mod_cls.members.values(): |
| 187 | + if not member.is_alias and (member.is_module or member.is_class): |
| 188 | + _apply_recursively(member, processed) # type: ignore[arg-type] |
| 189 | + |
| 190 | + |
| 191 | +class DataclassesExtension(Extension): |
| 192 | + """Built-in extension adding support for dataclasses. |
| 193 | +
|
| 194 | + This extension creates `__init__` methods of dataclasses |
| 195 | + if they don't already exist. |
| 196 | + """ |
| 197 | + |
| 198 | + def on_package_loaded(self, *, pkg: Module) -> None: |
| 199 | + """Hook for loaded packages. |
| 200 | +
|
| 201 | + Parameters: |
| 202 | + pkg: The loaded package. |
| 203 | + """ |
| 204 | + _apply_recursively(pkg, set()) |
0 commit comments