Skip to content

Commit

Permalink
Fix schema.py
Browse files Browse the repository at this point in the history
schema.py type-checks, but raises exception at runtime because Struct is
referenced before it is defined. This commit
- moves definition of Type to the top
- uses string names for forward type references
- replaces T with covariant TypeT
- fixes missing type parameter in Struct definition
  • Loading branch information
michalgr committed Nov 21, 2023
1 parent c52e092 commit 9c28279
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
25 changes: 16 additions & 9 deletions projects/jdwp/defs/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@

from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Generic, TypeVar, Type as TypeAlias
from typing import Optional, Generic, TypeVar, Type as TypeAlias, Union
from collections.abc import Mapping
from enum import Enum
from collections.abc import Set, Sequence
from projects.jdwp.defs.constants import ErrorType


Type = Union[
"PrimitiveType",
"Array",
"TaggedUnion",
"IntegralType",
"ArrayLength",
"Struct",
"UnionTag",
]


class PrimitiveType(Enum):
"""Primitive type class."""

Expand Down Expand Up @@ -72,27 +83,23 @@ class UnionTag(Generic[EnumT]):
value: TypeAlias[EnumT]


Type = (
PrimitiveType | Array | TaggedUnion | IntegralType | ArrayLength | Struct | UnionTag
)

T = TypeVar("T", bound=Type)
TypeT = TypeVar("TypeT", bound=Type, covariant=True)


@dataclass(frozen=True)
class Field(Generic[T]):
class Field(Generic[TypeT]):
"""Field class."""

name: str
type: T
type: TypeT
description: str


@dataclass(frozen=True)
class Struct:
"""Struct class."""

fields: Sequence[Field]
fields: Sequence[Field[Type]]


@dataclass(frozen=True)
Expand Down
5 changes: 4 additions & 1 deletion projects/jdwp/tests/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@

python_test(
name = "tests",
srcs = glob(["*.py"]),
deps = [
"//projects/jdwp:lib",
],
srcs = glob(["**/*.py"]),
)
8 changes: 8 additions & 0 deletions projects/jdwp/tests/defs/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.

import unittest


class SchemaTests(unittest.TestCase):
def test_schema_can_be_imported(self):
from projects.jdwp.defs.schema import PrimitiveType

0 comments on commit 9c28279

Please sign in to comment.