Skip to content

Commit

Permalink
fix(hugr-py): more ruff lints + fix some typos (#1246)
Browse files Browse the repository at this point in the history
import ruff.toml from guppylang
  - turn on more lints
  - mostly auto fixes, mostly import sorting

add a config file for `typos` tool
https://github.com/crate-ci/typos?tab=readme-ov-file
- we could consider adding this to CI/pre-commit but don't want to do a
big repo-wide change right now
  - I used cli typos tool with `cargo install typos-cli`

coverage is not happy because most of the fixes are in TYPE_CHECKING
import blocks or unraised exceptions
  • Loading branch information
ss2165 authored Jul 1, 2024
1 parent 7dadadf commit f158384
Show file tree
Hide file tree
Showing 25 changed files with 297 additions and 145 deletions.
4 changes: 4 additions & 0 deletions _typos.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[default.extend-identifiers]
bck = "bck" # BiMap uses abbreviation
ser_it = "ser_it"
SerCollection = "SerCollection"
15 changes: 9 additions & 6 deletions hugr-py/src/hugr/cfg.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

import hugr.ops as ops
import hugr.val as val

from .dfg import _DfBase
from .exceptions import NoSiblingAncestor, NotInSameCfg, MismatchedExit
from .exceptions import MismatchedExit, NoSiblingAncestor, NotInSameCfg
from .hugr import Hugr, ParentBuilder
from .node_port import Node, Wire, ToNode
from .tys import TypeRow, Type
import hugr.val as val

if TYPE_CHECKING:
from .node_port import Node, ToNode, Wire
from .tys import Type, TypeRow


class Block(_DfBase[ops.DataflowBlock]):
Expand All @@ -27,13 +30,13 @@ def _wire_up_port(self, node: Node, offset: int, p: Wire) -> Type:
src_parent = self.hugr[src.node].parent
try:
super()._wire_up_port(node, offset, p)
except NoSiblingAncestor:
except NoSiblingAncestor as e:
# note this just checks if there is a common CFG ancestor
# it does not check for valid dominance between basic blocks
# that is deferred to full HUGR validation.
while cfg_node != src_parent:
if src_parent is None or src_parent == self.hugr.root:
raise NotInSameCfg(src.node.idx, node.idx)
raise NotInSameCfg(src.node.idx, node.idx) from e
src_parent = self.hugr[src_parent].parent

self.hugr.add_link(src, node.inp(offset))
Expand Down
15 changes: 10 additions & 5 deletions hugr-py/src/hugr/cond_loop.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

import hugr.ops as ops

from .dfg import _DfBase
from .hugr import Hugr, ParentBuilder
from .node_port import Node, Wire, ToNode

from .tys import Sum, TypeRow
if TYPE_CHECKING:
from .node_port import Node, ToNode, Wire
from .tys import Sum, TypeRow


class Case(_DfBase[ops.Case]):
Expand All @@ -35,7 +37,8 @@ def __init__(self, case: Case) -> None:

def _parent_conditional(self) -> Conditional:
if self._parent_cond is None:
raise ConditionalError("If must have a parent conditional.")
msg = "If must have a parent conditional."
raise ConditionalError(msg)
return self._parent_cond


Expand Down Expand Up @@ -84,11 +87,13 @@ def _update_outputs(self, outputs: TypeRow) -> None:
self.parent_op._outputs = outputs
else:
if outputs != self.parent_op._outputs:
raise ConditionalError("Mismatched case outputs.")
msg = "Mismatched case outputs."
raise ConditionalError(msg)

def add_case(self, case_id: int) -> Case:
if case_id not in self.cases:
raise ConditionalError(f"Case {case_id} out of possible range.")
msg = f"Case {case_id} out of possible range."
raise ConditionalError(msg)
input_types = self.parent_op.nth_inputs(case_id)
new_case = Case.new_nested(
ops.Case(input_types),
Expand Down
22 changes: 12 additions & 10 deletions hugr-py/src/hugr/dfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
from dataclasses import dataclass, replace
from typing import (
TYPE_CHECKING,
Iterable,
Sequence,
TypeVar,
)

Expand All @@ -13,23 +11,25 @@
import hugr.ops as ops
import hugr.val as val
from hugr.tys import (
ExtensionSet,
FunctionKind,
FunctionType,
PolyFuncType,
Type,
TypeArg,
TypeRow,
get_first_sum,
FunctionType,
TypeArg,
FunctionKind,
PolyFuncType,
ExtensionSet,
)

from .exceptions import NoSiblingAncestor
from .hugr import Hugr, ParentBuilder
from .node_port import Node, OutPort, Wire, ToNode

if TYPE_CHECKING:
from collections.abc import Iterable, Sequence

from .cfg import Cfg
from .cond_loop import Conditional, If, TailLoop
from .node_port import Node, OutPort, ToNode, Wire


DP = TypeVar("DP", bound=ops.DfParentOp)
Expand Down Expand Up @@ -210,7 +210,8 @@ def _fn_sig(self, func: ToNode) -> PolyFuncType:
case FunctionKind(sig):
signature = sig
case _:
raise ValueError("Expected 'func' to be a function")
msg = "Expected 'func' to be a function"
raise ValueError(msg)
return signature

def _wire_up(self, node: Node, ports: Iterable[Wire]) -> TypeRow:
Expand All @@ -223,7 +224,8 @@ def _get_dataflow_type(self, wire: Wire) -> Type:
port = wire.out_port()
ty = self.hugr.port_type(port)
if ty is None:
raise ValueError(f"Port {port} is not a dataflow port.")
msg = f"Port {port} is not a dataflow port."
raise ValueError(msg)
return ty

def _wire_up_port(self, node: Node, offset: int, p: Wire) -> Type:
Expand Down
10 changes: 8 additions & 2 deletions hugr-py/src/hugr/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ class NoSiblingAncestor(Exception):

@property
def msg(self):
return f"Source {self.src} has no sibling ancestor of target {self.tgt}, so cannot wire up."
return (
f"Source {self.src} has no sibling ancestor of target {self.tgt},"
" so cannot wire up."
)


@dataclass
Expand All @@ -18,7 +21,10 @@ class NotInSameCfg(Exception):

@property
def msg(self):
return f"Source {self.src} is not in the same CFG as target {self.tgt}, so cannot wire up."
return (
f"Source {self.src} is not in the same CFG as target {self.tgt},"
" so cannot wire up."
)


@dataclass
Expand Down
8 changes: 6 additions & 2 deletions hugr-py/src/hugr/function.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

import hugr.ops as ops
import hugr.val as val

from .dfg import _DfBase
from hugr.node_port import Node
from .hugr import Hugr
from .tys import TypeRow, TypeParam, PolyFuncType, Type, TypeBound

if TYPE_CHECKING:
from hugr.node_port import Node

from .tys import PolyFuncType, Type, TypeBound, TypeParam, TypeRow


@dataclass
Expand Down
24 changes: 12 additions & 12 deletions hugr-py/src/hugr/hugr.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
from __future__ import annotations

from collections.abc import Mapping
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field, replace
from typing import (
TYPE_CHECKING,
Generic,
Iterable,
Protocol,
TypeVar,
cast,
overload,
Type as PyType,
)


from hugr.ops import Op, DataflowOp, Const, Call
from hugr.tys import Type, Kind, ValueKind
from hugr.val import Value
from hugr.node_port import Direction, InPort, OutPort, ToNode, Node, _SubPort
from hugr.node_port import Direction, InPort, Node, OutPort, ToNode, _SubPort
from hugr.ops import Call, Const, DataflowOp, Op
from hugr.serialization.ops import OpType as SerialOp
from hugr.serialization.serial_hugr import SerialHugr
from hugr.tys import Kind, Type, ValueKind
from hugr.utils import BiMap

from .exceptions import ParentBeforeChild

if TYPE_CHECKING:
from hugr.val import Value


@dataclass()
class NodeData:
Expand Down Expand Up @@ -88,7 +88,7 @@ def __iter__(self):
def __len__(self) -> int:
return self.num_nodes()

def _get_typed_op(self, node: ToNode, cl: PyType[OpVar2]) -> OpVar2:
def _get_typed_op(self, node: ToNode, cl: type[OpVar2]) -> OpVar2:
op = self[node].op
assert isinstance(op, cl)
return op
Expand Down Expand Up @@ -241,11 +241,11 @@ def incoming_links(self, node: ToNode) -> Iterable[tuple[InPort, list[OutPort]]]
return self._node_links(node, self._links.bck)

def num_incoming(self, node: Node) -> int:
# connecetd links
# connected links
return sum(1 for _ in self.incoming_links(node))

def num_outgoing(self, node: ToNode) -> int:
# connecetd links
# connected links
return sum(1 for _ in self.outgoing_links(node))

# TODO: num_links and _linked_ports
Expand Down Expand Up @@ -274,7 +274,7 @@ def insert_hugr(self, hugr: Hugr, parent: ToNode | None = None) -> dict[Node, No
mapping[node_data.parent] if node_data.parent else parent
)
except KeyError as e:
raise ParentBeforeChild() from e
raise ParentBeforeChild from e
mapping[Node(idx)] = self.add_node(node_data.op, node_parent)

for src, dst in hugr._links.items():
Expand Down
23 changes: 13 additions & 10 deletions hugr-py/src/hugr/node_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@
from dataclasses import dataclass, field, replace
from enum import Enum
from typing import (
TYPE_CHECKING,
ClassVar,
Iterator,
Generic,
Protocol,
overload,
TypeVar,
Generic,
overload,
)

from typing_extensions import Self

if TYPE_CHECKING:
from collections.abc import Iterator


class Direction(Enum):
INCOMING = 0
Expand Down Expand Up @@ -57,7 +61,7 @@ def __getitem__(
) -> OutPort | Iterator[OutPort]:
return self.to_node()._index(index)

def out_port(self) -> "OutPort":
def out_port(self) -> OutPort:
return OutPort(self.to_node(), 0)

def inp(self, offset: int) -> InPort:
Expand All @@ -83,17 +87,16 @@ def _index(
) -> OutPort | Iterator[OutPort]:
match index:
case int(index):
if self._num_out_ports is not None:
if index >= self._num_out_ports:
raise IndexError("Index out of range")
if self._num_out_ports is not None and index >= self._num_out_ports:
msg = "Index out of range"
raise IndexError(msg)
return self.out(index)
case slice():
start = index.start or 0
stop = index.stop or self._num_out_ports
if stop is None:
raise ValueError(
"Stop must be specified when number of outputs unknown"
)
msg = "Stop must be specified when number of outputs unknown"
raise ValueError(msg)
step = index.step or 1
return (self[i] for i in range(start, stop, step))
case tuple(xs):
Expand Down
19 changes: 13 additions & 6 deletions hugr-py/src/hugr/ops.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Protocol, Sequence, runtime_checkable, TypeVar
from hugr.serialization.ops import BaseOp
from typing import TYPE_CHECKING, Protocol, TypeVar, runtime_checkable

import hugr.serialization.ops as sops
from hugr.utils import ser_it
import hugr.tys as tys
from hugr.node_port import Node, InPort, OutPort, Wire
import hugr.val as val
from hugr.node_port import InPort, Node, OutPort, Wire
from hugr.utils import ser_it

if TYPE_CHECKING:
from collections.abc import Sequence

from hugr.serialization.ops import BaseOp


@dataclass
Expand Down Expand Up @@ -616,11 +621,13 @@ def _fn_instantiation(
else:
# TODO substitute type args into signature to get instantiation
if instantiation is None:
raise NoConcreteFunc("Missing instantiation for polymorphic function.")
msg = "Missing instantiation for polymorphic function."
raise NoConcreteFunc(msg)
type_args = type_args or []

if len(signature.params) != len(type_args):
raise NoConcreteFunc("Mismatched number of type arguments.")
msg = "Mismatched number of type arguments."
raise NoConcreteFunc(msg)
return instantiation, list(type_args)


Expand Down
3 changes: 0 additions & 3 deletions hugr-py/src/hugr/serialization/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
from .serial_hugr import SerialHugr

__all__ = ["SerialHugr"]
Loading

0 comments on commit f158384

Please sign in to comment.