Skip to content

Qualified names

How generated declarations (G.Item, G.read_goal.Outcomes) and the declarations of imported modules (syntax.lambda:normalize) are named, and how identifier-restricted consumers spell them.

names

Qualified names of declarations and of the declarations they generate.

A QVR declaration may generate further declarations: a deduction G generates its item family G.Item, its run computation G.run, and, for a selector read_goal, the outcome family G.read_goal.Outcomes. A generated declaration is named by its parent's name followed by a dotted member path, which records the declaration it came from. Identifier members use the usual qualified notation in source. The generated deduction item constructors for the two modal categories keep their category symbols.

A declaration of an imported module is named, in the single flat program that static interpretation of the module graph produces, by its module path and its name in that module, separated by : (syntax.lambda:normalize). A root module's own declarations keep their bare names. Source never spells :, so a flat name identifies its origin.

These helpers are the one place either separator is written, so every producer and consumer of generated names agrees on their spelling.

MEMBER_SEPARATOR module-attribute

MEMBER_SEPARATOR = '.'

Separates a declaration's name from the member path of what it generates.

MODULE_SEPARATOR module-attribute

MODULE_SEPARATOR = ':'

Separates a module path from a declaration name in a flat program.

TARGET_MEMBER_SEPARATOR module-attribute

TARGET_MEMBER_SEPARATOR = '__'

How identifier-restricted consumers spell a . between two segments.

TARGET_MODULE_SEPARATOR module-attribute

TARGET_MODULE_SEPARATOR = '___'

How identifier-restricted consumers spell a : between two segments.

TARGET_DRAW_SEPARATOR module-attribute

TARGET_DRAW_SEPARATOR = '____'

How identifier-restricted consumers spell a $ between two segments.

theta$z names the site z of a program drawn under theta.

TARGET_ESCAPE module-attribute

TARGET_ESCAPE = '_____'

Opens and closes an escaped run of punctuation in a target identifier.

member_name

member_name(parent: str, *members: str) -> str

The name of a declaration that parent generates.

PARAMETER DESCRIPTION
parent

The generating declaration's name, itself possibly qualified.

TYPE: str

*members

The member path below the parent, outermost first.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
str

parent.member1.member2....

RAISES DESCRIPTION
ValueError

If no member is given, the parent is empty, or a member is neither a single identifier segment nor a built-in modal category symbol.

Source code in src/quivers/qiec/names.py
def member_name(parent: str, *members: str) -> str:
    """The name of a declaration that ``parent`` generates.

    Parameters
    ----------
    parent : str
        The generating declaration's name, itself possibly qualified.
    *members : str
        The member path below the parent, outermost first.

    Returns
    -------
    str
        ``parent.member1.member2...``.

    Raises
    ------
    ValueError
        If no member is given, the parent is empty, or a member is neither a
        single identifier segment nor a built-in modal category symbol.
    """
    if not parent:
        raise ValueError("a generated name needs a non-empty parent name")
    if not members:
        raise ValueError(f"a generated name below {parent!r} needs a member")
    for member in members:
        if not _SEGMENT.fullmatch(member) and member not in _MODAL_CATEGORY_SYMBOLS:
            raise ValueError(
                f"member {member!r} of {parent!r} is not an identifier segment"
            )
    return MEMBER_SEPARATOR.join((parent, *members))

member_prefix

member_prefix(parent: str) -> str

The prefix every name generated below parent starts with.

PARAMETER DESCRIPTION
parent

The generating declaration's name.

TYPE: str

RETURNS DESCRIPTION
str

parent..

Source code in src/quivers/qiec/names.py
def member_prefix(parent: str) -> str:
    """The prefix every name generated below ``parent`` starts with.

    Parameters
    ----------
    parent : str
        The generating declaration's name.

    Returns
    -------
    str
        ``parent.``.
    """
    return parent + MEMBER_SEPARATOR

is_member_of

is_member_of(name: str, parent: str) -> bool

Whether name is generated below parent.

PARAMETER DESCRIPTION
name

A declaration name.

TYPE: str

parent

A candidate generating declaration.

TYPE: str

RETURNS DESCRIPTION
bool

Whether name is parent followed by a non-empty member path.

Source code in src/quivers/qiec/names.py
def is_member_of(name: str, parent: str) -> bool:
    """Whether ``name`` is generated below ``parent``.

    Parameters
    ----------
    name : str
        A declaration name.
    parent : str
        A candidate generating declaration.

    Returns
    -------
    bool
        Whether ``name`` is ``parent`` followed by a non-empty member path.
    """
    return name.startswith(member_prefix(parent)) and len(name) > len(parent) + 1

member_path

member_path(name: str, parent: str) -> tuple[str, ...]

The member path of name below parent.

PARAMETER DESCRIPTION
name

A name generated below parent.

TYPE: str

parent

The generating declaration.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

The member segments, outermost first.

RAISES DESCRIPTION
ValueError

If name is not generated below parent.

Source code in src/quivers/qiec/names.py
def member_path(name: str, parent: str) -> tuple[str, ...]:
    """The member path of ``name`` below ``parent``.

    Parameters
    ----------
    name : str
        A name generated below ``parent``.
    parent : str
        The generating declaration.

    Returns
    -------
    tuple[str, ...]
        The member segments, outermost first.

    Raises
    ------
    ValueError
        If ``name`` is not generated below ``parent``.
    """
    if not is_member_of(name, parent):
        raise ValueError(f"{name!r} is not generated below {parent!r}")
    return tuple(name[len(parent) + 1 :].split(MEMBER_SEPARATOR))

deduction_of

deduction_of(structural_path: tuple[str | int, ...]) -> str | None

The deduction whose elaboration a structural origin lies under.

PARAMETER DESCRIPTION
structural_path

A source origin's structural path.

TYPE: tuple[str | int, ...]

RETURNS DESCRIPTION
str | None

The deduction's name when the path is ("deductions", name, ...), else None.

Source code in src/quivers/qiec/names.py
def deduction_of(structural_path: tuple[str | int, ...]) -> str | None:
    """The deduction whose elaboration a structural origin lies under.

    Parameters
    ----------
    structural_path : tuple[str | int, ...]
        A source origin's structural path.

    Returns
    -------
    str | None
        The deduction's name when the path is ``("deductions", name, ...)``,
        else ``None``.
    """
    if (
        len(structural_path) < 2
        or structural_path[0] != "deductions"
        or not isinstance(structural_path[1], str)
    ):
        return None
    return structural_path[1]

is_generated_by

is_generated_by(name: str, parent: str, *members: str) -> bool

Whether name is exactly the declaration parent generates.

PARAMETER DESCRIPTION
name

A flat-program name.

TYPE: str

parent

The generating declaration's name, in its module or flat.

TYPE: str

*members

The member path below the parent, outermost first.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
bool

Whether name, within its module, is member_name(parent, *members), and parent, when it names a module, names the same one.

Source code in src/quivers/qiec/names.py
def is_generated_by(name: str, parent: str, *members: str) -> bool:
    """Whether ``name`` is exactly the declaration ``parent`` generates.

    Parameters
    ----------
    name : str
        A flat-program name.
    parent : str
        The generating declaration's name, in its module or flat.
    *members : str
        The member path below the parent, outermost first.

    Returns
    -------
    bool
        Whether ``name``, within its module, is ``member_name(parent,
        *members)``, and ``parent``, when it names a module, names the
        same one.
    """
    module, local = split_module(name)
    owner, parent_local = split_module(parent)
    if owner is not None and owner != module:
        return False
    return local == member_name(parent_local, *members)

local_segment

local_segment(name: str) -> str

The last segment of a name, without its module or parent.

PARAMETER DESCRIPTION
name

A plain, member, or flat-program name.

TYPE: str

RETURNS DESCRIPTION
str

Item for G.Item and for syntax.ccg:G.Item.

Source code in src/quivers/qiec/names.py
def local_segment(name: str) -> str:
    """The last segment of a name, without its module or parent.

    Parameters
    ----------
    name : str
        A plain, member, or flat-program name.

    Returns
    -------
    str
        ``Item`` for ``G.Item`` and for ``syntax.ccg:G.Item``.
    """
    return split_module(name)[1].rsplit(MEMBER_SEPARATOR, 1)[-1]

module_qualified

module_qualified(module_path: str, name: str) -> str

The flat-program name of a declaration of an imported module.

PARAMETER DESCRIPTION
module_path

The dotted module path, e.g. syntax.lambda.

TYPE: str

name

The declaration's name in its module, possibly a generated member name such as G.Item.

TYPE: str

RETURNS DESCRIPTION
str

module_path:name.

RAISES DESCRIPTION
ValueError

If either part is empty or name is already module-qualified.

Source code in src/quivers/qiec/names.py
def module_qualified(module_path: str, name: str) -> str:
    """The flat-program name of a declaration of an imported module.

    Parameters
    ----------
    module_path : str
        The dotted module path, e.g. ``syntax.lambda``.
    name : str
        The declaration's name in its module, possibly a generated member
        name such as ``G.Item``.

    Returns
    -------
    str
        ``module_path:name``.

    Raises
    ------
    ValueError
        If either part is empty or ``name`` is already module-qualified.
    """
    if not module_path or not name:
        raise ValueError("a module-qualified name needs a module path and a name")
    if MODULE_SEPARATOR in name:
        raise ValueError(f"{name!r} is already module-qualified")
    return f"{module_path}{MODULE_SEPARATOR}{name}"

split_module

split_module(name: str) -> tuple[str | None, str]

Split a flat-program name into its module path and its local name.

PARAMETER DESCRIPTION
name

A flat-program name.

TYPE: str

RETURNS DESCRIPTION
tuple[str | None, str]

The module path (None for a root module's own declaration) and the name within the module.

Source code in src/quivers/qiec/names.py
def split_module(name: str) -> tuple[str | None, str]:
    """Split a flat-program name into its module path and its local name.

    Parameters
    ----------
    name : str
        A flat-program name.

    Returns
    -------
    tuple[str | None, str]
        The module path (``None`` for a root module's own declaration)
        and the name within the module.
    """
    module, separator, local = name.partition(MODULE_SEPARATOR)
    if not separator:
        return None, name
    return module, local

source_spelling

source_spelling(name: str) -> str

How a flat-program name reads in diagnostics.

PARAMETER DESCRIPTION
name

A flat-program name.

TYPE: str

RETURNS DESCRIPTION
str

The fully qualified dotted path, syntax.lambda.normalize for syntax.lambda:normalize; a root declaration's name unchanged.

Source code in src/quivers/qiec/names.py
def source_spelling(name: str) -> str:
    """How a flat-program name reads in diagnostics.

    Parameters
    ----------
    name : str
        A flat-program name.

    Returns
    -------
    str
        The fully qualified dotted path, ``syntax.lambda.normalize`` for
        ``syntax.lambda:normalize``; a root declaration's name unchanged.
    """
    module, local = split_module(name)
    return local if module is None else f"{module}{MEMBER_SEPARATOR}{local}"

target_identifier

target_identifier(name: str) -> str

Spell a qualified name as a plain identifier, injectively.

Transpile targets and PyTorch module names admit only [A-Za-z_][A-Za-z0-9_]*. A name is read as alternating runs of ASCII letters and digits, kept as they are, and maximal runs of every other character, each spelled by where it stands and what it holds:

  • between two letter-or-digit runs, a single _ stays _, a . is __, a : is ___, and a $ is ____;
  • at the start or the end of the name, a run of one to three underscores stays as written;
  • any other run is escaped: _____ (five underscores), one code per character (u for _, d for ., m for :, s for $, l and r for the parentheses, c for ,, e for =, h for #, a for *, p for a space, b and k for the brackets, q for /, g and t for > and <, w for ?, and U<hex>Z for any other character), and _____ again.

Every underscore run of the result therefore has a length that says what it is, so source_name reads the name back and two distinct names never share a spelling. A one-module program keeps its readable spellings: G.Item is G__Item, lib.arith:shift is lib__arith___shift, and theta$z is theta____z.

PARAMETER DESCRIPTION
name

A flat-program name, a site address, or any other qualified name.

TYPE: str

RETURNS DESCRIPTION
str

The identifier spelling.

RAISES DESCRIPTION
ValueError

If name is empty or starts with a digit, which no qualified name does.

Source code in src/quivers/qiec/names.py
def target_identifier(name: str) -> str:
    """Spell a qualified name as a plain identifier, injectively.

    Transpile targets and PyTorch module names admit only
    ``[A-Za-z_][A-Za-z0-9_]*``. A name is read as alternating runs of ASCII
    letters and digits, kept as they are, and maximal runs of every other
    character, each spelled by where it stands and what it holds:

    * between two letter-or-digit runs, a single ``_`` stays ``_``, a
      ``.`` is ``__``, a ``:`` is ``___``, and a ``$`` is ``____``;
    * at the start or the end of the name, a run of one to three
      underscores stays as written;
    * any other run is escaped: ``_____`` (five underscores), one code per
      character (``u`` for ``_``, ``d`` for ``.``, ``m`` for ``:``, ``s``
      for ``$``, ``l`` and ``r`` for the parentheses, ``c`` for ``,``,
      ``e`` for ``=``, ``h`` for ``#``, ``a`` for ``*``, ``p`` for a
      space, ``b`` and ``k`` for the brackets, ``q`` for ``/``, ``g`` and
      ``t`` for ``>`` and ``<``, ``w`` for ``?``, and ``U<hex>Z`` for any other character),
      and ``_____`` again.

    Every underscore run of the result therefore has a length that says
    what it is, so `source_name` reads the name back and two distinct names
    never share a spelling. A one-module program keeps its readable
    spellings: ``G.Item`` is ``G__Item``, ``lib.arith:shift`` is
    ``lib__arith___shift``, and ``theta$z`` is ``theta____z``.

    Parameters
    ----------
    name : str
        A flat-program name, a site address, or any other qualified name.

    Returns
    -------
    str
        The identifier spelling.

    Raises
    ------
    ValueError
        If ``name`` is empty or starts with a digit, which no qualified
        name does.
    """
    if not name:
        raise ValueError("an empty name has no target spelling")
    if name[0].isascii() and name[0].isdigit():
        raise ValueError(f"{name!r} starts with a digit and is not a qualified name")
    spelled: list[str] = []
    index = 0
    while index < len(name):
        end = index
        if _word_char(name[index]):
            while end < len(name) and _word_char(name[end]):
                end += 1
            spelled.append(name[index:end])
            index = end
            continue
        while end < len(name) and not _word_char(name[end]):
            end += 1
        run = name[index:end]
        edge = index == 0 or end == len(name)
        if edge and set(run) == {"_"} and len(run) <= 3:
            spelled.append(run)
        elif not edge and run in _SHORT_RUNS:
            spelled.append(_SHORT_RUNS[run])
        else:
            spelled.append(_escape(run))
        index = end
    return "".join(spelled)

source_name

source_name(identifier: str) -> str

Read a target identifier back as the qualified name it spells.

The inverse of target_identifier: source_name(target_identifier(n)) is n for every name n it accepts.

PARAMETER DESCRIPTION
identifier

An identifier target_identifier produced.

TYPE: str

RETURNS DESCRIPTION
str

The qualified name.

RAISES DESCRIPTION
ValueError

If identifier is not a spelling target_identifier produces.

Source code in src/quivers/qiec/names.py
def source_name(identifier: str) -> str:
    """Read a target identifier back as the qualified name it spells.

    The inverse of `target_identifier`: ``source_name(target_identifier(n))``
    is ``n`` for every name ``n`` it accepts.

    Parameters
    ----------
    identifier : str
        An identifier `target_identifier` produced.

    Returns
    -------
    str
        The qualified name.

    Raises
    ------
    ValueError
        If ``identifier`` is not a spelling `target_identifier` produces.
    """
    if not identifier:
        raise ValueError("an empty identifier spells no name")
    decoded: list[str] = []
    index = 0
    while index < len(identifier):
        char = identifier[index]
        if _word_char(char):
            decoded.append(char)
            index += 1
            continue
        if char != "_":
            raise ValueError(f"{identifier!r} is not a target identifier")
        end = index
        while end < len(identifier) and identifier[end] == "_":
            end += 1
        length = end - index
        if length == len(TARGET_ESCAPE):
            text, index = _decode_escape(identifier, end)
            if index < len(identifier) and identifier[index] == "_":
                raise ValueError(f"{identifier!r} continues an escape with '_'")
            decoded.append(text)
            continue
        if length > len(TARGET_ESCAPE):
            raise ValueError(f"{identifier!r} has a run of {length} underscores")
        if index == 0 or end == len(identifier):
            if length > 3:
                raise ValueError(f"{identifier!r} has an edge run of {length}")
            decoded.append("_" * length)
        else:
            decoded.append(_SHORT_DECODING[length])
        index = end
    return "".join(decoded)

target_names

target_names(names: Iterable[str]) -> dict[str, str]

The reverse map from target identifiers to the names they spell.

PARAMETER DESCRIPTION
names

Qualified names one rendering spells.

TYPE: Iterable[str]

RETURNS DESCRIPTION
dict[str, str]

Each name's target_identifier mapped to the name, sorted by identifier. The map is a bijection because the spelling is injective.

Source code in src/quivers/qiec/names.py
def target_names(names: Iterable[str]) -> dict[str, str]:
    """The reverse map from target identifiers to the names they spell.

    Parameters
    ----------
    names : Iterable[str]
        Qualified names one rendering spells.

    Returns
    -------
    dict[str, str]
        Each name's `target_identifier` mapped to the name, sorted by
        identifier. The map is a bijection because the spelling is
        injective.
    """
    spelled = {target_identifier(name): name for name in set(names)}
    return dict(sorted(spelled.items()))