# -*- coding: utf-8 -*-
"""Format and Value Rules
============================
.. module:: pcapkit.utilities.conformance
:mod:`pcapkit.utilities.conformance` holds what a reader calls where a value it can
read past is wrong, as ruled on :issue:`3234`: :func:`nonconforming` where the
value breaks a format or value rule its specification sets -- a length cap, a
reserved or must-be-zero field, an out-of-range value, a forbidden combination --
and :func:`anomalous` where the specification is silent but the value is odd. A
construction is refused the first and a parse warns of it, while both only warn of
the second, unless the engine :mod:`pcapkit` is set to mimic accepts or refuses the
value. A failure that leaves nothing more to decode is neither, and its parse still
refuses.
.. versionadded:: 1.10.0
"""
from typing import TYPE_CHECKING
from pcapkit.utilities.contextvars import constructing
from pcapkit.utilities.exceptions import ProtocolError, stacklevel
from pcapkit.utilities.warnings import ProtocolWarning, warn
if TYPE_CHECKING:
from typing import Optional
from typing_extensions import Literal
__all__ = ['nonconforming', 'anomalous']
[docs]
def anomalous(message: 'str', *, mimic: 'Optional[Literal["accept", "refuse"]]' = None) -> 'None':
"""Report an odd value its specification is silent on, which the reader reads on past.
A reader calls it once per offending field. It follows
:func:`nonconforming`, but for a construction with no ``mimic`` given,
which it warns of rather than refuses, since no rule refuses the value:
.. list-table::
:header-rows: 1
* - ``mimic``
- Parse
- Rebuild (``from_data``)
- Construction (``from_fields``)
* - :data:`None`
- warns
- warns
- warns
* - ``'accept'``
- nothing
- nothing
- nothing
* - ``'refuse'``
- raises
- warns
- raises
Args:
message: What is odd, led by the protocol's alias.
mimic: As for :func:`nonconforming`.
Raises:
ProtocolError: As the table says, quiet under a next-layer fallback.
Warns:
ProtocolWarning: As the table says, through
:func:`~pcapkit.utilities.warnings.warn`.
"""
_report(message, mimic, refused=False)
def _report(message: 'str', mimic: 'Optional[Literal["accept", "refuse"]]', *, refused: 'bool') -> 'None':
"""Raise, warn or do nothing, for :func:`nonconforming` and :func:`anomalous`.
Args:
message: What is wrong.
mimic: What the engine mimicked does with the value.
refused: Whether a rule refuses the value, so that a construction
is refused it with no ``mimic`` given.
"""
if mimic == 'accept':
return
built = constructing.get()
if built != 'data' and (mimic == 'refuse' or (refused and built == 'fields')):
raise ProtocolError(message)
warn(message, ProtocolWarning, stacklevel=stacklevel())