Skip to content

Source identity

Core hashes beside the grammar-keyed hashes of a source's bytes and of its alpha-normalized statements.

identity

Content identity of QVR source: core hashes beside source hashes.

A program has two identities, recorded separately:

  • its core identity: the content hash of every checked QIEC declaration (module_hashes), domain-separated by the core format, so any surface syntax that elaborates to the same core has the same hashes and a syntactic migration hop preserves them;
  • its source identity: one hash per top-level statement of the source, keyed by the panproto commit of the grammar the source is written in, plus the hash of the exact bytes.

A statement's source hash is alpha-normalized as far as the source's own name analysis (analyze_names) reaches: comments, blank lines, indentation width, spacing, and number spelling are dropped; a name the statement declares becomes its position among the statement's declarations; a local binder and the references it binds become the ordinal of the name's first occurrence; and a reference to a name another statement declares becomes that statement's source hash, with mutually referring statements hashed as one canonically ordered component, as in the core. Every other token (keywords, operators, literals, option keys, builtin names, the labels of a deduction's body) is kept as written.

The source identity covers what the checked core does not yet record (a relation's arcs, a loss, a declared morphism type, the learnability of a deduction rule, ...), which is why a fit is keyed by both. Because it is a function of the surface syntax, a migration hop may change it, and it is recorded with the grammar commit it was computed under.

IdentityError

Bases: ValueError

A source cannot be identified: it does not parse or does not check.

SourceHash didactic-model

SourceHash(*, grammar: str, digest: str)

Bases: Model

The hash of a source's exact bytes.

PARAMETER DESCRIPTION
grammar

The panproto schema commit of the grammar the source is written in.

TYPE: str

digest

The BLAKE3 digest of the bytes.

TYPE: str

StatementHash didactic-model

StatementHash(*, kind: str, names: tuple[str, ...], hash: str)

Bases: Model

The alpha-normalized source hash of one top-level statement.

PARAMETER DESCRIPTION
kind

The statement's grammar kind (program_decl, object_decl, ...).

TYPE: str

names

The names it declares, in order (metadata).

TYPE: tuple[str, ...]

hash

Its source hash: the component hash when no other statement refers back to it, else <component>.<member>.

TYPE: str

ProgramIdentity didactic-model

ProgramIdentity(*, core: ModuleHashes, statements: tuple[StatementHash, ...], source: SourceHash, digest: str)

Bases: Model

Every identity of one checked source.

PARAMETER DESCRIPTION
core

The core hashes of its checked declarations.

TYPE: ModuleHashes

statements

The source hash of each top-level statement, in source order.

TYPE: tuple[StatementHash, ...]

source

The hash of the exact bytes.

TYPE: SourceHash

digest

The digest of the core module digest and the multiset of statement hashes under the grammar commit: what a fit of this program is keyed by.

TYPE: str

head_grammar

head_grammar() -> str

The panproto schema commit of the grammar this checkout parses.

RETURNS DESCRIPTION
str

The commit pinned for HEAD in the migration manifest.

Source code in src/quivers/incremental/identity.py
def head_grammar() -> str:
    """The panproto schema commit of the grammar this checkout parses.

    Returns
    -------
    str
        The commit pinned for ``HEAD`` in the migration manifest.
    """
    return SCHEMA_COMMITS["HEAD"]

source_hash

source_hash(source: bytes, *, grammar: str) -> SourceHash

The hash of a source's exact bytes.

PARAMETER DESCRIPTION
source

The bytes.

TYPE: bytes

grammar

The schema commit of the grammar they are written in.

TYPE: str

RETURNS DESCRIPTION
SourceHash

The grammar commit with the BLAKE3 digest of the bytes.

Source code in src/quivers/incremental/identity.py
def source_hash(source: bytes, *, grammar: str) -> SourceHash:
    """The hash of a source's exact bytes.

    Parameters
    ----------
    source : bytes
        The bytes.
    grammar : str
        The schema commit of the grammar they are written in.

    Returns
    -------
    SourceHash
        The grammar commit with the BLAKE3 digest of the bytes.
    """
    return SourceHash(grammar=grammar, digest=content_digest(source))

statement_hashes

statement_hashes(source: bytes, tree: _Tree, names: FileNames) -> tuple[StatementHash, ...]

The alpha-normalized source hash of every top-level statement.

PARAMETER DESCRIPTION
source

The file's bytes.

TYPE: bytes

tree

Its parse tree.

TYPE: _Tree

names

Its name analysis.

TYPE: FileNames

RETURNS DESCRIPTION
tuple[StatementHash, ...]

One hash per statement, in source order. A statement's hash covers the hashes of the statements it refers to, so it changes when they do; statements that refer to one another are hashed as one component.

RAISES DESCRIPTION
IdentityError

If a reference cannot be resolved.

Source code in src/quivers/incremental/identity.py
def statement_hashes(
    source: bytes, tree: _Tree, names: FileNames
) -> tuple[StatementHash, ...]:
    """The alpha-normalized source hash of every top-level statement.

    Parameters
    ----------
    source : bytes
        The file's bytes.
    tree : _Tree
        Its parse tree.
    names : FileNames
        Its name analysis.

    Returns
    -------
    tuple[StatementHash, ...]
        One hash per statement, in source order. A statement's hash covers
        the hashes of the statements it refers to, so it changes when they
        do; statements that refer to one another are hashed as one component.

    Raises
    ------
    IdentityError
        If a reference cannot be resolved.
    """
    normalizer = _SourceNormalizer(source, tree, names)
    edges = normalizer.dependencies()
    resolved: dict[int, CoreJson] = {}
    hashes: dict[int, str] = {}
    for component in _statement_components(edges):
        members = set(component)

        def serialize(order: list[int], *, erase: bool = False) -> str:
            """The component's serialization in one member order.

            Parameters
            ----------
            order : list[int]
                The members, in the order to serialize them.
            erase : bool
                Whether references into the component are erased rather
                than numbered by position.

            Returns
            -------
            str
                The canonical JSON of the members' forms.
            """
            positions: dict[int, CoreJson] = {
                member: ({"$self": None} if erase else {"$self": i})
                for i, member in enumerate(order)
            }
            forms = [
                normalizer.form(
                    normalizer.statements[member], {**resolved, **positions}, []
                )
                for member in order
            ]
            return canonical_json(forms)

        if len(component) == 1:
            order = component
        else:
            colors: dict[int, str] = {}
            successors: dict[int, tuple[int, ...]] = {}
            for member in component:
                internal: list[int] = []
                form = normalizer.form(
                    normalizer.statements[member],
                    {**resolved, **{item: {"$self": None} for item in members}},
                    internal,
                )
                colors[member] = tagged_digest("statement-cycle-free", form)
                successors[member] = tuple(item for item in internal if item in members)
            order = canonical_order(component, colors, successors, serialize)
        unit = tagged_digest("statements", json.loads(serialize(order)))
        for position, member in enumerate(order):
            hashes[member] = unit if len(order) == 1 else f"{unit}.{position}"
            resolved[member] = hashes[member]
    return tuple(
        StatementHash(
            kind=statement.kind,
            names=statement.declared,
            hash=hashes[statement.index],
        )
        for statement in normalizer.statements
    )

check_source

check_source(source: bytes, *, module_name: str, file_path: str, roots: tuple[str | Path, ...] = ()) -> QiecModule

Interpret and check a source, with its imports, down to its QIEC module.

The source is the root of a module graph (quivers.dsl.modules): its imports are found in the standard library and below roots, and the flat program is what is checked and hashed.

PARAMETER DESCRIPTION
source

The source.

TYPE: bytes

module_name

The name stable identities derive from (metadata of every hash).

TYPE: str

file_path

The path diagnostics name.

TYPE: str

roots

Directories the source's imported module paths are relative to.

TYPE: tuple[str | Path, ...] DEFAULT: ()

RETURNS DESCRIPTION
QiecModule

The checked module.

RAISES DESCRIPTION
IdentityError

If the source does not parse, its module graph does not load or resolve, its QIEC lowering reports a diagnostic (located in the module it comes from), or a program was not elaborated. A module that failed to check has no meaning to hash, and a module missing a program would hash as if the program were absent.

Source code in src/quivers/incremental/identity.py
def check_source(
    source: bytes,
    *,
    module_name: str,
    file_path: str,
    roots: tuple[str | Path, ...] = (),
) -> QiecModule:
    """Interpret and check a source, with its imports, down to its QIEC module.

    The source is the root of a module graph (`quivers.dsl.modules`): its
    imports are found in the standard library and below ``roots``, and the
    flat program is what is checked and hashed.

    Parameters
    ----------
    source : bytes
        The source.
    module_name : str
        The name stable identities derive from (metadata of every hash).
    file_path : str
        The path diagnostics name.
    roots : tuple[str | Path, ...]
        Directories the source's imported module paths are relative to.

    Returns
    -------
    QiecModule
        The checked module.

    Raises
    ------
    IdentityError
        If the source does not parse, its module graph does not load or
        resolve, its QIEC lowering reports a diagnostic (located in the
        module it comes from), or a program was not elaborated. A module that failed to check has no
        meaning to hash, and a module missing a program would hash as if the
        program were absent.
    """
    try:
        flat = interpret_source(source.decode("utf-8"), label=file_path, roots=roots)
    except Exception as error:
        raise IdentityError(f"{file_path}: {error}") from error
    analysis = analyze_module(
        flat.module,
        module_name=module_name,
        file_path=file_path,
        compile_categorical=False,
    )
    if analysis.qiec_diagnostics:
        diagnostic = analysis.qiec_diagnostics[0]
        located = flat.source_map.locate(diagnostic.line, diagnostic.col)
        where = (
            f"{located.file}:{located.line}:{located.column}"
            if located is not None
            else f"{file_path}:{diagnostic.line}:{diagnostic.col}"
        )
        raise IdentityError(f"{where}: [{diagnostic.code}] {diagnostic.message}")
    module = analysis.qiec_module
    if module is None:
        raise IdentityError(f"{file_path}: the source has no checked QIEC module")
    return module

statements_digest

statements_digest(source: str | bytes, *, file_path: str = '<source>', grammar: str | None = None) -> str

The digest of a source's statement hashes, without checking it.

PARAMETER DESCRIPTION
source

The source text.

TYPE: str or bytes

file_path

The path diagnostics name.

TYPE: str DEFAULT: '<source>'

grammar

The schema commit of the grammar the source is written in; head_grammar when None.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
str

The digest of the grammar commit and the multiset of the statements' alpha-normalized source hashes: invariant under renaming, reordering, comments, and formatting, and changed by any other edit to any statement.

RAISES DESCRIPTION
IdentityError

If the source does not parse.

Source code in src/quivers/incremental/identity.py
def statements_digest(
    source: str | bytes,
    *,
    file_path: str = "<source>",
    grammar: str | None = None,
) -> str:
    """The digest of a source's statement hashes, without checking it.

    Parameters
    ----------
    source : str or bytes
        The source text.
    file_path : str
        The path diagnostics name.
    grammar : str or None
        The schema commit of the grammar the source is written in;
        `head_grammar` when None.

    Returns
    -------
    str
        The digest of the grammar commit and the multiset of the statements'
        alpha-normalized source hashes: invariant under renaming, reordering,
        comments, and formatting, and changed by any other edit to any
        statement.

    Raises
    ------
    IdentityError
        If the source does not parse.
    """
    data = source.encode("utf-8") if isinstance(source, str) else source
    commit = head_grammar() if grammar is None else grammar
    try:
        tree = parse_tree(data, file_path)
        names = file_names(tree, file_path)
    except Exception as error:
        raise IdentityError(f"{file_path}: {error}") from error
    pairs: list[CoreJson] = [
        [kind, digest]
        for kind, digest in sorted(
            (statement.kind, statement.hash)
            for statement in statement_hashes(data, tree, names)
        )
    ]
    return tagged_digest("statements-digest", [commit, pairs])

identify

identify(source: str | bytes, *, module_name: str, file_path: str = '<source>', grammar: str | None = None, roots: tuple[str | Path, ...] = ()) -> ProgramIdentity

Every identity of one source file.

PARAMETER DESCRIPTION
source

The source text.

TYPE: str or bytes

module_name

The module name stable identities derive from.

TYPE: str

file_path

The path diagnostics name.

TYPE: str DEFAULT: '<source>'

grammar

The schema commit of the grammar the source is written in; head_grammar when None.

TYPE: str or None DEFAULT: None

roots

Directories the source's imported module paths are relative to.

TYPE: tuple[str | Path, ...] DEFAULT: ()

RETURNS DESCRIPTION
ProgramIdentity

Its core hashes, statement source hashes, and source hash.

RAISES DESCRIPTION
IdentityError

If the source does not parse or check.

Source code in src/quivers/incremental/identity.py
def identify(
    source: str | bytes,
    *,
    module_name: str,
    file_path: str = "<source>",
    grammar: str | None = None,
    roots: tuple[str | Path, ...] = (),
) -> ProgramIdentity:
    """Every identity of one source file.

    Parameters
    ----------
    source : str or bytes
        The source text.
    module_name : str
        The module name stable identities derive from.
    file_path : str
        The path diagnostics name.
    grammar : str or None
        The schema commit of the grammar the source is written in;
        `head_grammar` when None.
    roots : tuple[str | Path, ...]
        Directories the source's imported module paths are relative to.

    Returns
    -------
    ProgramIdentity
        Its core hashes, statement source hashes, and source hash.

    Raises
    ------
    IdentityError
        If the source does not parse or check.
    """
    data = source.encode("utf-8") if isinstance(source, str) else source
    commit = head_grammar() if grammar is None else grammar
    module = check_source(
        data, module_name=module_name, file_path=file_path, roots=roots
    )
    core = ModuleContent(module).hashes
    tree = parse_tree(data, file_path)
    statements = statement_hashes(data, tree, file_names(tree, file_path))
    pairs: list[CoreJson] = [
        [kind, digest]
        for kind, digest in sorted(
            (statement.kind, statement.hash) for statement in statements
        )
    ]
    digest = tagged_digest("program", [core.module, commit, pairs])
    return ProgramIdentity(
        core=core,
        statements=statements,
        source=source_hash(data, grammar=commit),
        digest=digest,
    )