Skip to content

Commit

Permalink
A few typing and mypyc fixes, remove dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
sciyoshi committed Jun 16, 2023
1 parent 56e580d commit 34a91f3
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 23 deletions.
43 changes: 27 additions & 16 deletions prosemirror/model/content.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import re
from dataclasses import dataclass, field
from functools import cmp_to_key, reduce
from typing import (
TYPE_CHECKING,
Expand All @@ -22,25 +21,32 @@
from .schema import NodeType


@dataclass
class MatchEdge:
type: "NodeType"
next: "ContentMatch"

def __init__(self, type: "NodeType", next: "ContentMatch") -> None:
self.type = type
self.next = next


@dataclass
class WrapCacheEntry:
target: "NodeType"
computed: Optional[List["NodeType"]]

def __init__(
self, target: "NodeType", computed: Optional[List["NodeType"]]
) -> None:
self.target = target
self.computed = computed


class Active(TypedDict):
match: "ContentMatch"
type: Optional["NodeType"]
via: Optional["Active"]


@dataclass(eq=False)
class ContentMatch:
"""
Instances of this class represent a match state of a node type's
Expand All @@ -51,16 +57,21 @@ class ContentMatch:

empty: ClassVar["ContentMatch"]
valid_end: bool
next: List[MatchEdge] = field(default_factory=list, init=False)
wrap_cache: List[WrapCacheEntry] = field(default_factory=list, init=False)
next: List[MatchEdge]
wrap_cache: List[WrapCacheEntry]

def __init__(self, valid_end: bool) -> None:
self.valid_end = valid_end
self.next = []
self.wrap_cache = []

@classmethod
def parse(cls, string: str, node_types: Dict[str, "NodeType"]) -> "ContentMatch":
stream = TokenStream(string, node_types)
if stream.next is None:
if stream.next() is None:
return ContentMatch.empty
expr = parse_expr(stream)
if stream.next:
if stream.next() is not None:
stream.err("Unexpected trailing text")
match = dfa(nfa(expr))
check_for_dead_ends(match, stream)
Expand Down Expand Up @@ -218,15 +229,14 @@ def __init__(self, string: str, node_types: Dict[str, "NodeType"]) -> None:
self.pos = 0
self.tokens = [i for i in TOKEN_REGEX.findall(string) if i.strip()]

@property
def next(self) -> Optional[str]:
try:
return self.tokens[self.pos]
except IndexError:
return None

def eat(self, tok: str) -> Union[int, bool]:
if self.next == tok:
if self.next() == tok:
pos = self.pos
self.pos += 1
return pos or True
Expand Down Expand Up @@ -292,7 +302,8 @@ def parse_expr_seq(stream: TokenStream) -> Expr:
exprs = []
while True:
exprs.append(parse_expr_subscript(stream))
if not (stream.next and stream.next != ")" and stream.next != "|"):
next_ = stream.next()
if not (next_ and next_ != ")" and next_ != "|"):
break
if len(exprs) == 1:
return exprs[0]
Expand All @@ -319,7 +330,7 @@ def parse_expr_subscript(stream: TokenStream) -> Expr:


def parse_num(stream: TokenStream) -> int:
next = stream.next
next = stream.next()
assert next is not None
if NUMBER_REGEX.match(next):
stream.err(f'Expected number, got "{next}"')
Expand All @@ -332,7 +343,7 @@ def parse_expr_range(stream: TokenStream, expr: Expr) -> Expr:
min_ = parse_num(stream)
max_ = min_
if stream.eat(","):
if stream.next != "}":
if stream.next() != "}":
max_ = parse_num(stream)
else:
max_ = -1
Expand Down Expand Up @@ -363,7 +374,7 @@ def parse_expr_atom(
if not stream.eat(")"):
stream.err("missing closing patren")
return expr
elif not re.match(r"\W", cast(str, stream.next)):
elif not re.match(r"\W", cast(str, stream.next())):

def iteratee(type: "NodeType") -> Expr:
nonlocal stream
Expand All @@ -374,14 +385,14 @@ def iteratee(type: "NodeType") -> Expr:
return {"type": "name", "value": type}

exprs = [
iteratee(type) for type in resolve_name(stream, cast(str, stream.next))
iteratee(type) for type in resolve_name(stream, cast(str, stream.next()))
]
stream.pos += 1
if len(exprs) == 1:
return exprs[0]
return {"type": "choice", "exprs": exprs}
else:
stream.err(f'Unexpected token "{stream.next}"')
stream.err(f'Unexpected token "{stream.next()}"')


class Edge(TypedDict):
Expand Down
6 changes: 5 additions & 1 deletion prosemirror/model/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,11 @@ def check(self) -> None:
f"Invalid collection of marks for node {self.type.name}:"
f" {[m.type.name for m in self.marks]!r}"
)
return self.content.for_each(lambda node, *args: node.check())

def iteratee(node: "Node", offset: int, index: int) -> None:
node.check()

return self.content.for_each(iteratee)

def to_json(self) -> JSONDict:
obj: Dict[str, JSON] = {"type": self.type.name}
Expand Down
2 changes: 1 addition & 1 deletion prosemirror/model/resolvedpos.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, List, Optional, Union, cast, Callable
from typing import TYPE_CHECKING, Callable, List, Optional, Union, cast

from .mark import Mark

Expand Down
5 changes: 2 additions & 3 deletions prosemirror/model/schema.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Expand Down Expand Up @@ -87,7 +86,7 @@ def __init__(self, name: str, schema: "Schema[Any, Any]", spec: "NodeSpec") -> N
self.default_attrs = default_attrs(self.attrs)
self.content_match = None # type: ignore[assignment]
self.mark_set = None
self.inline_content = None # type: ignore[assignment]
self.inline_content = False
self.is_block = not (spec.get("inline") or name == "text")
self.is_text = name == "text"

Expand Down Expand Up @@ -413,7 +412,7 @@ def node(
self,
type: Union[str, NodeType],
attrs: Optional[Attrs] = None,
content: Optional[Union[Fragment, Node]] = None,
content: Optional[Union[Fragment, Node, List[Node]]] = None,
marks: Optional[List[Mark]] = None,
) -> Node:
if isinstance(type, str):
Expand Down
1 change: 0 additions & 1 deletion prosemirror/model/to_dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
Sequence,
Tuple,
Union,
Set,
cast,
)

Expand Down
1 change: 1 addition & 0 deletions tests/prosemirror_model/tests/test_node.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Literal

from prosemirror.model import Fragment, Schema
from prosemirror.test_builder import eq, out
from prosemirror.test_builder import test_schema as schema
Expand Down
2 changes: 1 addition & 1 deletion tests/prosemirror_transform/tests/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def n(name, *content):
return schema.nodes[name].create(None, content)
return schema.nodes[name].create(None, list(content))


def t(str, em=None):
Expand Down

0 comments on commit 34a91f3

Please sign in to comment.