diff --git a/.github/workflows/ci.python.yml b/.github/workflows/ci.python.yml index 081f3e77..b9a26ca0 100644 --- a/.github/workflows/ci.python.yml +++ b/.github/workflows/ci.python.yml @@ -52,6 +52,9 @@ jobs: echo $HATCH_ENV echo "$HATCH_ENV/bin" >> $GITHUB_PATH + - name: Install Node Dependencies + run: npm ci + - name: Get Pyright Version id: pyright-version run: | diff --git a/python/package-lock.json b/python/package-lock.json index e7d0f0a6..bef7e494 100644 --- a/python/package-lock.json +++ b/python/package-lock.json @@ -9,12 +9,353 @@ "version": "0.3.0", "license": "MIT", "devDependencies": { - "pyright": "1.1.358" + "pyright": "1.1.358", + "typescript": "^7.0.2" }, "engines": { "node": ">=24.22.1" } }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -44,6 +385,41 @@ "optionalDependencies": { "fsevents": "~2.3.3" } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } } } } diff --git a/python/package.json b/python/package.json index ebbb13f3..e126bfe3 100644 --- a/python/package.json +++ b/python/package.json @@ -12,6 +12,7 @@ "node": ">=24.22.1" }, "devDependencies": { - "pyright": "1.1.358" + "pyright": "1.1.358", + "typescript": "^7.0.2" } } diff --git a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py index f9999deb..ba766803 100644 --- a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py +++ b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py @@ -244,17 +244,60 @@ def visit(current: type, current_type_arguments: dict[object, object]) -> None: return result -def _declaring_class(py_type: type, attr_name: str) -> type: +def _field_owners(py_type: type) -> dict[str, tuple[type, bool]]: + """ + Map each dataclass field of `py_type` to the class that declares it, and whether + that class is also the first one in the MRO to annotate the name. + + With multiple inheritance the two can differ: `@dataclass` takes every field of + the first base, including the ones that base only inherits, while the merged + annotations follow the MRO. A base's fields are inherited as the same objects, + so the class that declares the winning field is the one that annotates the name + and holds that object in its own field table. A subclass that is not decorated + reaches the table of its base through attribute lookup, but creates no field. + """ + declared: list[tuple[type, dict[str, Any]]] = [] for base in py_type.__mro__: # `inspect.get_annotations` returns only the annotations a class declares itself, # and also works when they are evaluated lazily (Python 3.14). try: - own_annotations = inspect.get_annotations(base) + declared.append((base, inspect.get_annotations(base))) except Exception: continue - if attr_name in own_annotations: - return base - return py_type + result: dict[str, tuple[type, bool]] = {} + fields: dict[str, Field[Any]] = getattr(py_type, "__dataclass_fields__", {}) + for attr_name, field in fields.items(): + first: type | None = None + owner: type | None = None + for base, annotations in declared: + if attr_name not in annotations: + continue + if first is None: + first = base + if vars(base).get("__dataclass_fields__", {}).get(attr_name) is field: + owner = base + break + owner = owner or first or py_type + result[attr_name] = (owner, owner is (first or py_type)) + return result + + +def _winning_type_hints(py_type: type, field_owners: dict[str, tuple[type, bool]] | None = None) -> dict[str, Any]: + """ + The type hints of `py_type`, with each dataclass field typed by the class that + declares the winning field. Other classes are only resolved when they are needed. + """ + type_hints = get_type_hints(py_type, include_extras=True) + if field_owners is None: + field_owners = _field_owners(py_type) + type_hints_by_owner: dict[type, dict[str, Any]] = {} + for attr_name, (owner, is_first) in field_owners.items(): + if is_first: + continue + if owner not in type_hints_by_owner: + type_hints_by_owner[owner] = get_type_hints(owner, include_extras=True) + type_hints[attr_name] = type_hints_by_owner[owner][attr_name] + return type_hints def _base_interface_properties(base_type_hints: list[tuple[type, dict[str, Any]]], attr_name: str) -> list[tuple[bool, bool]]: @@ -283,10 +326,8 @@ def _base_interface_properties(base_type_hints: list[tuple[type, dict[str, Any]] return result -def _resolve_init_var_type(py_type: type, attr_name: str, init_var_type: object) -> Any: +def _resolve_init_var_type(owner: type, init_var_type: object) -> Any: """Resolve quoted types inside `InitVar[...]`, which `get_type_hints` does not look into.""" - owner = _declaring_class(py_type, attr_name) - def holder() -> None: ... holder.__annotations__ = {"value": init_var_type} @@ -524,7 +565,10 @@ def declare_type(py_type: object): else: type_params = None - annotated_members = get_type_hints(py_type, include_extras=True) + # The merged annotations follow the MRO, but with multiple inheritance the + # winning dataclass field can come from a class later in it. + field_owners = _field_owners(py_type) + annotated_members = _winning_type_hints(py_type, field_owners) raw_but_filtered_bases: list[type] = [ base @@ -533,10 +577,13 @@ def declare_type(py_type: object): ] base_attributes: OrderedDict[str, set[object]] = OrderedDict() base_type_hints: list[tuple[type, dict[str, Any]]] = [] + base_field_owners: list[dict[str, tuple[type, bool]]] = [] for base in raw_but_filtered_bases: base_origin = get_origin(base) or base - type_hints_of_base = get_type_hints(base_origin, include_extras=True) + field_owners_of_base = _field_owners(base_origin) + type_hints_of_base = _winning_type_hints(base_origin, field_owners_of_base) base_type_hints.append((base_origin, type_hints_of_base)) + base_field_owners.append(field_owners_of_base) for prop, type_hint in type_hints_of_base.items(): base_attributes.setdefault(prop, set()).add(type_hint) bases: list[TypeNode] = [convert_to_type_node(base) for base in raw_but_filtered_bases] @@ -571,7 +618,9 @@ def declare_type(py_type: object): inherited_type_arguments = _inherited_type_arguments(py_type) projected_init_vars: dict[str, None] = {} + projected_fields_by_base: list[dict[str, None]] = [{} for _ in base_type_hints] for attr_name, field in cast(Dataclassish, py_type).__dataclass_fields__.items(): + owner = field_owners[attr_name][0] type_hint = annotated_members[attr_name] base_properties = _base_interface_properties(base_type_hints, attr_name) base_has_init_var = any(from_init_var for _, from_init_var in base_properties) @@ -604,6 +653,28 @@ def declare_type(py_type: object): # Python overrides need not be TypeScript subtypes. Project the # inherited input away and declare the winning constructor type. projected_init_vars[attr_name] = None + if not is_init_var and owner is not py_type: + # A field this class only inherits keeps the type of the winning field. + # With multiple inheritance, another base can declare the name with a + # field of its own, whose type the winning one need not satisfy, so + # that base's declaration is projected away unless the two agree. + declared_type = _substitute_type_arguments(type_hint, inherited_type_arguments.get(owner, {})) + for index, (base, base_hints) in enumerate(base_type_hints): + base_field = getattr(base, "__dataclass_fields__", {}).get(attr_name) + base_hint = base_hints.get(attr_name) + if ( + base_field is None + or base_field is field + or base_hint is ClassVar + or get_origin(base_hint) is ClassVar + ): + continue + base_owner = base_field_owners[index].get(attr_name, (base, True))[0] + base_type = _substitute_type_arguments(base_hint, inherited_type_arguments.get(base_owner, {})) + base_optional = not(base_field.default is MISSING and base_field.default_factory is MISSING) + if base_type == declared_type and base_optional == optional: + continue + projected_fields_by_base[index][attr_name] = None if is_init_var: if not in_constructor: continue @@ -622,7 +693,7 @@ def declare_type(py_type: object): type_hint = cast(Any, Any) elif isinstance(type_hint, InitVar): try: - type_hint = _resolve_init_var_type(py_type, attr_name, cast(Any, type_hint).type) + type_hint = _resolve_init_var_type(owner, cast(Any, type_hint).type) except NameError as exc: errors.append( f"Cannot resolve '{exc.name}' in the InitVar annotation of '{py_type.__name__}.{attr_name}'." @@ -632,21 +703,29 @@ def declare_type(py_type: object): # parameter, which is not a type parameter of the class being declared. type_hint = _substitute_type_arguments( type_hint, - inherited_type_arguments.get(_declaring_class(py_type, attr_name), {}), + inherited_type_arguments.get(owner, {}), ) prop = declare_property(attr_name, type_hint, is_typeddict_attribute=False, optionality_default=optional, fallback_comment=inline_comments.get(attr_name, "")) properties.append(prop) - if projected_init_vars: + projected_by_base = [ + {**projected_init_vars, **projected_fields} + for projected_fields in projected_fields_by_base + ] + if any(projected_by_base): uses_omit = True if any(parameter.name == "Omit" for parameter in type_params or []): errors.append( - f"Cannot use the type parameter name 'Omit' in '{py_type.__name__}' when InitVar inheritance requires TypeScript's built-in Omit utility." + f"Cannot use the type parameter name 'Omit' in '{py_type.__name__}' when dataclass inheritance requires TypeScript's built-in Omit utility." ) - projected_keys = UnionTypeNode([LiteralTypeNode(name) for name in projected_init_vars]) bases = [ - TypeReferenceNode(IdentifierNode("Omit"), [base, projected_keys]) - for base in bases + TypeReferenceNode( + IdentifierNode("Omit"), + [base, UnionTypeNode([LiteralTypeNode(name) for name in projected])], + ) + if projected + else base + for base, projected in zip(bases, projected_by_base) ] reserve_name(py_type) @@ -701,7 +780,7 @@ def get_type_argument_nodes(py_type: object, count: int, default: TypeNode) -> l if uses_omit and "Omit" in used_names: errors.append( - "Cannot use the schema type name 'Omit' when InitVar inheritance requires TypeScript's built-in Omit utility." + "Cannot use the schema type name 'Omit' when dataclass inheritance requires TypeScript's built-in Omit utility." ) return TypeScriptNodeTranslationResult(type_declarations, errors) diff --git a/python/tests/test_dataclass_diamond_inheritance.py b/python/tests/test_dataclass_diamond_inheritance.py new file mode 100644 index 00000000..718be4ef --- /dev/null +++ b/python/tests/test_dataclass_diamond_inheritance.py @@ -0,0 +1,327 @@ +import shutil +import subprocess +from dataclasses import InitVar, dataclass +from pathlib import Path +from typing import Any, Generic, TypeVar + +import pytest +from pydantic import TypeAdapter, ValidationError + +from typechat import python_type_to_typescript_schema + +T = TypeVar("T") + + +@dataclass +class InitVariableBase: + value: InitVar[int] + + +@dataclass +class UnchangedInitVariable(InitVariableBase): + pass + + +@dataclass +class ChangedInitVariable(InitVariableBase): + value: InitVar[str] # type: ignore + + +@dataclass +class InitVariableDiamond(UnchangedInitVariable, ChangedInitVariable): + pass + + +@dataclass +class InitVariableDiamondChangedFirst(ChangedInitVariable, UnchangedInitVariable): # type: ignore + pass + + +@dataclass +class ChangedToField(InitVariableBase): + value: str # type: ignore + + +@dataclass +class InitVariableOverFieldDiamond(UnchangedInitVariable, ChangedToField): + pass + + +@dataclass +class DiamondDescendant(InitVariableOverFieldDiamond): + value: str + + +@dataclass +class FieldBase: + value: int + + +@dataclass +class UnchangedField(FieldBase): + pass + + +@dataclass +class ChangedField(FieldBase): + value: str # type: ignore + + +@dataclass +class FieldDiamond(UnchangedField, ChangedField): + pass + + +@dataclass +class UnionFieldBase: + value: int | str + + +@dataclass +class UnchangedUnionField(UnionFieldBase): + pass + + +@dataclass +class NarrowedUnionField(UnionFieldBase): + value: str # type: ignore + + +@dataclass +class NarrowedUnionFieldDiamond(UnchangedUnionField, NarrowedUnionField): + pass + + +@dataclass +class AgreeingLeft: + value: int + + +@dataclass +class AgreeingRight: + value: int + + +@dataclass +class AgreeingFields(AgreeingLeft, AgreeingRight): + pass + + +@dataclass +class GenericFieldBase(Generic[T]): + value: T + + +@dataclass +class IntGenericField(GenericFieldBase[int]): + pass + + +@dataclass +class AgreeingGenericFields(IntGenericField, AgreeingRight): + pass + + +@dataclass +class DefaultedLeft: + value: int = 0 + + +@dataclass +class DefaultWinsOverRequired(DefaultedLeft, AgreeingRight): + pass + + +@dataclass +class UndecoratedInitVariableBase: + value: InitVar[int] + + +class UndecoratedInitVariable(UndecoratedInitVariableBase): + # Not decorated, so it creates no field of its own. + value: InitVar[str] # type: ignore + + +@dataclass +class UndecoratedUnchangedInitVariable(UndecoratedInitVariable): + pass + + +@dataclass +class UndecoratedChangedInitVariable(UndecoratedInitVariable): + value: InitVar[int] # type: ignore + + +@dataclass +class UndecoratedInitVariableDiamond(UndecoratedUnchangedInitVariable, UndecoratedChangedInitVariable): + pass + + +@dataclass +class GenericInitVariableBase(Generic[T]): + value: InitVar[T] + + +@dataclass +class UnchangedGenericInitVariable(GenericInitVariableBase[int]): + pass + + +@dataclass +class ChangedGenericInitVariable(GenericInitVariableBase[int]): + value: InitVar[str] # type: ignore + + +@dataclass +class GenericInitVariableDiamond(UnchangedGenericInitVariable, ChangedGenericInitVariable): + pass + + +@dataclass +class QuotedTarget: + name: str + + +@dataclass +class QuotedInitVariableBase: + value: InitVar["list[QuotedTarget]"] + + +@dataclass +class UnchangedQuotedInitVariable(QuotedInitVariableBase): + pass + + +@dataclass +class ChangedQuotedInitVariable(QuotedInitVariableBase): + value: InitVar[str] # type: ignore + + +@dataclass +class QuotedInitVariableDiamond(UnchangedQuotedInitVariable, ChangedQuotedInitVariable): + pass + + +def interface_body(target: type[Any]) -> str: + result = python_type_to_typescript_schema(target) + assert not result.errors + schema = result.typescript_schema_str + start = schema.index(f"interface {target.__name__}") + return schema[start : schema.index("}\n", start)] + + +def accepts(target: type[Any], value: object) -> bool: + try: + TypeAdapter(target).validate_python({"value": value}) + except ValidationError: + return False + return True + + +@pytest.mark.parametrize( + ("target", "expected", "accepted", "rejected"), + [ + (InitVariableDiamond, "number", 1, "text"), + (InitVariableDiamondChangedFirst, "string", "text", 1), + (FieldDiamond, "number", 1, "text"), + (NarrowedUnionFieldDiamond, "number | string", 1, None), + (UndecoratedInitVariableDiamond, "number", 1, "text"), + ], +) +def test_diamond_uses_the_type_of_the_winning_field( + target: type[Any], expected: str, accepted: object, rejected: object +) -> None: + assert f" value: {expected};\n" in interface_body(target) + assert accepts(target, accepted) + assert not accepts(target, rejected) + + +def test_diamond_applies_the_type_arguments_of_the_winning_field() -> None: + assert " value: number;\n" in interface_body(GenericInitVariableDiamond) + + +def test_diamond_resolves_a_quoted_type_where_the_winning_field_is_declared() -> None: + assert " value: QuotedTarget[];\n" in interface_body(QuotedInitVariableDiamond) + + +def test_diamond_projects_the_losing_init_variable_away() -> None: + assert interface_body(InitVariableDiamond).startswith( + 'interface InitVariableDiamond extends Omit, Omit {\n' + ) + + +def test_descendant_sees_the_winning_init_variable_of_a_diamond() -> None: + assert " value: number;\n" in interface_body(InitVariableOverFieldDiamond) + body = interface_body(DiamondDescendant) + assert body.startswith('interface DiamondDescendant extends Omit {\n') + assert " value: string;\n" in body + + +@pytest.mark.parametrize( + ("target", "header"), + [ + ( + NarrowedUnionFieldDiamond, + 'interface NarrowedUnionFieldDiamond extends UnchangedUnionField, Omit {\n', + ), + ( + DefaultWinsOverRequired, + 'interface DefaultWinsOverRequired extends DefaultedLeft, Omit {\n', + ), + (AgreeingFields, "interface AgreeingFields extends AgreeingLeft, AgreeingRight {\n"), + (AgreeingGenericFields, "interface AgreeingGenericFields extends IntGenericField, AgreeingRight {\n"), + ], +) +def test_diamond_projects_the_losing_field_away_only_where_it_differs(target: type[Any], header: str) -> None: + assert interface_body(target).startswith(header) + + +def test_agreeing_bases_do_not_need_the_omit_utility() -> None: + @dataclass + class Omit(AgreeingLeft, AgreeingRight): + pass + + assert not python_type_to_typescript_schema(Omit).errors + + +def test_undecorated_subclass_does_not_own_the_inherited_field() -> None: + # The class reannotates the name but creates no field, so the constructor + # still takes the type of the field its base declares. + assert " value: number;\n" in interface_body(UndecoratedInitVariable) + assert accepts(UndecoratedInitVariable, 1) + assert not accepts(UndecoratedInitVariable, "text") + + +_TSC = Path(__file__).parents[1] / "node_modules" / "typescript" / "bin" / "tsc" + + +@pytest.mark.parametrize( + "target", + [ + InitVariableDiamond, + InitVariableDiamondChangedFirst, + DiamondDescendant, + NarrowedUnionFieldDiamond, + DefaultWinsOverRequired, + AgreeingFields, + AgreeingGenericFields, + UndecoratedInitVariableDiamond, + GenericInitVariableDiamond, + QuotedInitVariableDiamond, + ], +) +def test_diamond_schema_compiles(target: type[Any], tmp_path: Path) -> None: + node = shutil.which("node") + if node is None or not _TSC.exists(): + pytest.skip("TypeScript is not installed; run `npm ci` in the python directory.") + result = python_type_to_typescript_schema(target) + assert not result.errors + schema = tmp_path / "schema.ts" + schema.write_text(result.typescript_schema_str, encoding="utf-8") + completed = subprocess.run( + [node, str(_TSC), "--strict", "--noEmit", str(schema)], + capture_output=True, + text=True, + encoding="utf-8", + ) + assert completed.returncode == 0, completed.stdout + completed.stderr diff --git a/python/tests/test_dataclass_initvars.py b/python/tests/test_dataclass_initvars.py index 4edd81c1..7cbe27ed 100644 --- a/python/tests/test_dataclass_initvars.py +++ b/python/tests/test_dataclass_initvars.py @@ -489,7 +489,7 @@ class Omit(RequiredInitVariableBase): result = python_type_to_typescript_schema(Omit) assert result.errors == [ - "Cannot use the schema type name 'Omit' when InitVar inheritance requires TypeScript's built-in Omit utility." + "Cannot use the schema type name 'Omit' when dataclass inheritance requires TypeScript's built-in Omit utility." ] @@ -510,7 +510,7 @@ class GenericOverride(GenericInitVariable[Omit], Generic[Omit]): result = python_type_to_typescript_schema(GenericOverride) assert result.errors == [ - "Cannot use the type parameter name 'Omit' in 'GenericOverride' when InitVar inheritance requires TypeScript's built-in Omit utility." + "Cannot use the type parameter name 'Omit' in 'GenericOverride' when dataclass inheritance requires TypeScript's built-in Omit utility." ]