Skip to content

Inference engine

engine

Inference engine for pyling.

Engine

Engine(doc: Document, options: Mapping[str, Any] | None = None)
Source code in pyling/engine.py
def __init__(self, doc: Document, options: Mapping[str, Any] | None = None) -> None:
    global _NEXT_CACHE_GENERATION
    self._cache_generation = _NEXT_CACHE_GENERATION
    _NEXT_CACHE_GENERATION += 1
    self._key_ids: dict[Any, int] = {}
    self._next_key_id = 1
    self.doc = doc
    self.options = dict(options or {})
    self.prefixes = doc.prefixes
    self.facts: list[Triple] = list(doc.triples)
    self._fact_set: set[Triple] = set()
    self._fact_lookup_keys: set[tuple[Any, Any, Any]] = set()
    self._facts_by_pred: dict[Any, list[Triple]] = {}
    self._facts_by_ps: dict[tuple[Any, Any], list[Triple]] = {}
    self._facts_by_po: dict[tuple[Any, Any], list[Triple]] = {}
    self._facts_by_list_component: dict[
        tuple[Any, str, tuple[int, ...], Any], list[Triple]
    ] = {}
    self._var_pred_facts: list[Triple] = []
    self._fact_index_states: dict[tuple[int, int], tuple[
        list[Triple],
        dict[Any, list[Triple]],
        dict[tuple[Any, Any], list[Triple]],
        dict[tuple[Any, Any], list[Triple]],
        dict[tuple[Any, str, tuple[int, ...], Any], list[Triple]],
        list[Triple],
        set[Triple],
        set[tuple[Any, Any, Any]],
    ]] = {}
    self._scoped_fact_lists: dict[tuple[Triple, ...], list[Triple]] = {}
    self._deep_list_subject_indexes: dict[
        tuple[Any, ...], tuple[dict[tuple[Any, ...], list[Triple]], list[Triple]]
    ] = {}
    for _tr in self.facts:
        self._index_fact(_tr)
    self._indexed_facts_obj_id = id(self.facts)
    self._indexed_facts_len = len(self.facts)
    self.derived: list[Triple] = []
    self.forward_rules: list[Rule] = list(doc.forward_rules)
    self.backward_rules: list[Rule] = list(doc.backward_rules)
    self._backward_rules_by_pred: dict[str, list[Rule]] = {}
    self._wild_backward_rules: list[Rule] = []
    for _rule in self.backward_rules:
        if len(_rule.premise) != 1:
            continue
        if isinstance(_rule.premise[0].p, Iri):
            self._backward_rules_by_pred.setdefault(_rule.premise[0].p.value, []).append(_rule)
        else:
            self._wild_backward_rules.append(_rule)
    self._backward_predicates: set[str] = {
        rule.premise[0].p.value
        for rule in self.backward_rules
        if len(rule.premise) == 1 and isinstance(rule.premise[0].p, Iri)
    }
    self._has_wild_backward_predicate = any(
        len(rule.premise) == 1 and not isinstance(rule.premise[0].p, Iri)
        for rule in self.backward_rules
    )
    self.query_rules: list[Rule] = list(doc.query_rules)
    self._rule_key_cache: dict[Rule, str] = {}
    self._rule_ids: set[str] = {self._rule_key(r) for r in self.forward_rules + self.backward_rules}
    self._fired_rule_bindings: set[tuple[int, tuple[Triple, ...]]] = set()
    self._rule_input_signatures: dict[Rule, tuple] = {}
    self._agenda_active = False
    self._agenda_queue: list[Triple] = []
    self._agenda_indexed_rules: set[Rule] = set()
    self._agenda_by_pred: dict[Any, list[_AgendaEntry]] = {}
    self._agenda_by_ps: dict[tuple[Any, Any], list[_AgendaEntry]] = {}
    self._agenda_by_po: dict[tuple[Any, Any], list[_AgendaEntry]] = {}
    self._agenda_by_pso: dict[tuple[Any, Any, Any], list[_AgendaEntry]] = {}
    self._agenda_all_entries: list[_AgendaEntry] = []
    self._fresh_counter = 0
    self._std_counter = 0
    self._standardized_term_cache: dict[str, Term] = {}
    self._rule_fact_view_active = True
    self.max_depth = int(self.options.get("max_depth", self.options.get("maxDepth", 100_000)))
    self.max_iterations = int(self.options.get("max_iterations", self.options.get("maxIterations", 1000)))
    self.skolem_salt = str(uuid.uuid4())
    self.store = None
    # Opt-in backward-goal memoization/tabling, declared with top-level
    # facts of the form `<predicate> log:memoize true.` (see the Eyeling
    # JS reference engine). See _extract_memoize_declarations and solve().
    self._memoized_predicates: set[str] = set()
    self._predicate_memo_tables: dict[tuple, dict[str, dict[str, Any]]] = {}
    self._bottom_up_memo_active: set[tuple[str, int]] = set()
    self._goal_memo_version: tuple | None = None
    self._goal_memo_table: dict[str, list[Subst]] = {}
    self._extract_memoize_declarations()

solve

solve(goals: list[Triple], subst: Subst, depth: int = 0, allow_reorder: bool = True, _visited: frozenset[Any] | None = None) -> Iterator[Subst]

Prove goals with iterative DFS and trail-backed substitutions.

Source code in pyling/engine.py
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
def solve(
    self,
    goals: list[Triple],
    subst: Subst,
    depth: int = 0,
    allow_reorder: bool = True,
    _visited: frozenset[Any] | None = None,
) -> Iterator[Subst]:
    """Prove goals with iterative DFS and trail-backed substitutions."""
    goal_memo_key: str | None = None
    goal_memo: dict[str, list[Subst]] | None = None
    if depth == 0 and not _visited and not subst:
        goal_memo = self._completed_goal_memo()
        goal_memo_key = self._completed_goal_memo_key(goals, subst, allow_reorder)
        cached = goal_memo.get(goal_memo_key)
        if cached is not None:
            for answer in cached:
                yield dict(answer)
            return

    subst_mut: Subst = dict(subst)
    trail: list[str] = []
    visited_counts: dict[Any, int] = {key: 1 for key in (_visited or frozenset())}
    visited_trail: list[Any] = []
    answer_vars = set(subst)

    def collect_vars(term: Term, target: set[str]) -> None:
        if not self._term_needs_substitution(term):
            return
        if isinstance(term, Var):
            target.add(term.name)
        elif isinstance(term, ListTerm):
            for item in term.elems:
                collect_vars(item, target)
        elif isinstance(term, OpenListTerm):
            for item in term.prefix:
                collect_vars(item, target)
            target.add(term.tail_var)
        elif isinstance(term, GraphTerm):
            for triple in term.triples:
                collect_vars(triple.s, target)
                collect_vars(triple.p, target)
                collect_vars(triple.o, target)

    for original_goal in goals:
        collect_vars(original_goal.s, answer_vars)
        collect_vars(original_goal.p, answer_vars)
        collect_vars(original_goal.o, answer_vars)
    completed_answers: list[Subst] = []

    def goal_key(goal: Triple) -> tuple[Any, Any, Any]:
        # Standardized rule variables change names at every recursive
        # call, so normalize variables for cycle detection. Blank nodes
        # remain identity-bearing terms and must not be collapsed.
        return (
            self._visited_term_key(goal.s),
            self._visited_term_key(goal.p),
            self._visited_term_key(goal.o),
        )

    def undo_to(mark: int) -> None:
        for name in reversed(trail[mark:]):
            subst_mut.pop(name, None)
        del trail[mark:]

    def push_visited(key: Any) -> None:
        visited_counts[key] = visited_counts.get(key, 0) + 1
        visited_trail.append(key)

    def undo_visited_to(mark: int) -> None:
        for key in reversed(visited_trail[mark:]):
            count = visited_counts.get(key, 0)
            if count <= 1:
                visited_counts.pop(key, None)
            else:
                visited_counts[key] = count - 1
        del visited_trail[mark:]

    def deref_trail(term: Term) -> Term:
        if not isinstance(term, Var):
            return term
        while isinstance(term, Var):
            value = subst_mut.get(term.name, _MISSING)
            if value is _MISSING:
                return term
            term = value
        return term

    def apply_subst_trail(term: Term) -> Term:
        if not self._term_needs_substitution(term):
            return term
        term = deref_trail(term)
        if isinstance(term, ListTerm):
            original = term.elems
            size = len(original)
            if size == 0:
                return term
            if size == 1:
                e0 = apply_subst_trail(original[0])
                return term if e0 == original[0] else ListTerm((e0,))
            if size == 2:
                e0 = apply_subst_trail(original[0])
                e1 = apply_subst_trail(original[1])
                return term if e0 == original[0] and e1 == original[1] else ListTerm((e0, e1))
            if size == 3:
                e0 = apply_subst_trail(original[0])
                e1 = apply_subst_trail(original[1])
                e2 = apply_subst_trail(original[2])
                return (
                    term
                    if e0 == original[0] and e1 == original[1] and e2 == original[2]
                    else ListTerm((e0, e1, e2))
                )
            elems = tuple(apply_subst_trail(item) for item in original)
            return term if elems == original else ListTerm(elems)
        if isinstance(term, OpenListTerm):
            prefix = tuple(apply_subst_trail(item) for item in term.prefix)
            tail = apply_subst_trail(Var(term.tail_var))
            if isinstance(tail, ListTerm):
                return ListTerm((*prefix, *tail.elems))
            if isinstance(tail, OpenListTerm):
                return OpenListTerm((*prefix, *tail.prefix), tail.tail_var)
            if isinstance(tail, Var):
                if prefix == term.prefix and tail.name == term.tail_var:
                    return term
                return OpenListTerm(prefix, tail.name)
            return OpenListTerm(prefix, term.tail_var)
        if isinstance(term, GraphTerm):
            triples = tuple(apply_subst_triple_trail(triple) for triple in term.triples)
            return term if triples == term.triples else GraphTerm(triples)
        return term

    def apply_subst_triple_trail(
        triple: Triple,
        ground_blanks: bool = False,
        blank_mapping: dict[str, Blank] | None = None,
    ) -> Triple:
        if ground_blanks:
            return self._instantiate_head_triple(triple, subst_mut, blank_mapping)
        s = apply_subst_trail(triple.s)
        p = apply_subst_trail(triple.p)
        o = apply_subst_trail(triple.o)
        return triple if s == triple.s and p == triple.p and o == triple.o else Triple(s, p, o)

    comparisons = {
        "equalTo", "notEqualTo", "greaterThan", "lessThan",
        "notGreaterThan", "notLessThan", "contains", "startsWith",
        "endsWith", "matches", "notMatches", "notMember",
    }

    def unbound_trail(term: Term) -> int:
        original = term
        term = deref_trail(term)
        if isinstance(original, Var) and isinstance(term, GraphTerm):
            return 0
        if isinstance(term, Var):
            return 1
        if isinstance(term, ListTerm):
            elems = term.elems
            size = len(elems)
            if size == 0:
                return 0
            if size == 1:
                return unbound_trail(elems[0])
            if size == 2:
                return unbound_trail(elems[0]) + unbound_trail(elems[1])
            if size == 3:
                return unbound_trail(elems[0]) + unbound_trail(elems[1]) + unbound_trail(elems[2])
            return sum(unbound_trail(item) for item in elems)
        if isinstance(term, GraphTerm):
            return sum(
                unbound_trail(triple.s) + unbound_trail(triple.p) + unbound_trail(triple.o)
                for triple in term.triples
            )
        return 0

    def goal_rank_trail(goal: Triple, pred: Term, handler: Callable[[BuiltinContext], list[Subst]] | None) -> tuple[int, int]:
        subject_unbound = unbound_trail(goal.s)
        object_unbound = unbound_trail(goal.o)
        variables = subject_unbound + object_unbound
        if not isinstance(pred, Iri):
            return (0, variables)
        if handler is None:
            self._ensure_fact_indexes_current()
            has_extensional_candidate = bool(self._facts_by_pred.get(self._lookup_key(pred)))
            has_backward_rule = pred.value in self._backward_predicates
            if has_backward_rule and not has_extensional_candidate and subject_unbound:
                return (1, variables)
            return (0, variables)
        if pred.value == "http://www.w3.org/2000/10/swap/list#iterate" and subject_unbound == 0:
            return (-1, variables)
        if (
            pred.value in {
                "http://www.w3.org/2000/10/swap/list#append",
                "http://www.w3.org/2000/10/swap/list#firstRest",
            }
            and object_unbound == 0
        ):
            return (-1, variables)
        local = pred.value.rsplit("#", 1)[-1]
        if local in {"collectAllIn", "forAllIn"}:
            return (1, variables)
        if local in {"includes", "notIncludes"} and isinstance(deref_trail(goal.o), Var):
            return (3, variables)
        if local in {"includes", "notIncludes"} and variables:
            return (1, variables)
        if pred.value == LOG_NS + "equalTo":
            left = deref_trail(goal.s)
            right = deref_trail(goal.o)
            if not (isinstance(left, Var) and isinstance(right, Var)):
                return (-1, variables)
        if local in comparisons and variables:
            return (2, variables)
        if subject_unbound == 0:
            return (-1, variables)
        return (2, variables)

    def select_goal_index_trail(current_goals: list[Any]) -> int:
        for index, goal in enumerate(current_goals):
            if not isinstance(goal, Triple):
                return index
            predicate = deref_trail(goal.p)
            handler = get_builtin(predicate.value) if isinstance(predicate, Iri) else None
            rank = goal_rank_trail(goal, predicate, handler)
            if handler is not None:
                if rank[0] < 0:
                    return index
            elif rank[0] == 0:
                return index
        return 0

    def occurs(name: str, value: Term) -> bool:
        value = deref_trail(value)
        if not self._term_needs_substitution(value):
            return False
        if isinstance(value, Var):
            return value.name == name
        if isinstance(value, ListTerm):
            elems = value.elems
            size = len(elems)
            if size == 0:
                return False
            if size == 1:
                return occurs(name, elems[0])
            if size == 2:
                return occurs(name, elems[0]) or occurs(name, elems[1])
            if size == 3:
                return occurs(name, elems[0]) or occurs(name, elems[1]) or occurs(name, elems[2])
            return any(occurs(name, item) for item in elems)
        if isinstance(value, OpenListTerm):
            return (
                value.tail_var == name
                or any(occurs(name, item) for item in value.prefix)
                or occurs(name, Var(value.tail_var))
            )
        if isinstance(value, GraphTerm):
            return any(
                occurs(name, triple.s) or occurs(name, triple.p) or occurs(name, triple.o)
                for triple in value.triples
            )
        return False

    def bind_var(var: Var, value: Term) -> bool:
        if var.name in subst_mut:
            return unify_term_trail(subst_mut[var.name], value)
        if isinstance(value, Var) and value.name == var.name:
            return True
        if occurs(var.name, value):
            return False
        subst_mut[var.name] = value
        trail.append(var.name)
        return True

    def unify_graphs_trail(left: tuple[Triple, ...], right: tuple[Triple, ...]) -> bool:
        if len(left) != len(right):
            return False
        used = [False] * len(right)

        def step(index: int) -> bool:
            if index >= len(left):
                return True
            current = left[index]
            for candidate_index, candidate in enumerate(right):
                if used[candidate_index]:
                    continue
                if (
                    isinstance(current.p, Iri)
                    and isinstance(candidate.p, Iri)
                    and current.p.value != candidate.p.value
                ):
                    continue
                mark = len(trail)
                if unify_triple_trail(current, candidate):
                    used[candidate_index] = True
                    if step(index + 1):
                        return True
                    used[candidate_index] = False
                undo_to(mark)
            return False

        return step(0)

    def unify_term_trail(a: Term, b: Term) -> bool:
        a = apply_subst_trail(a)
        b = apply_subst_trail(b)
        if isinstance(a, Var):
            return bind_var(a, b)
        if isinstance(b, Var):
            return bind_var(b, a)
        if isinstance(a, Iri) and a.value == RDF_NIL and isinstance(b, ListTerm) and not b.elems:
            return True
        if isinstance(b, Iri) and b.value == RDF_NIL and isinstance(a, ListTerm) and not a.elems:
            return True
        if a is b or a == b:
            return True
        if isinstance(a, Literal) and isinstance(b, Literal):
            return self.literal_equivalent(a, b)
        if isinstance(a, ListTerm) and isinstance(b, ListTerm):
            left = a.elems
            right = b.elems
            size = len(left)
            if size != len(right):
                return False
            if size == 0:
                return True
            if size == 1:
                return unify_term_trail(left[0], right[0])
            if size == 2:
                return unify_term_trail(left[0], right[0]) and unify_term_trail(left[1], right[1])
            if size == 3:
                return (
                    unify_term_trail(left[0], right[0])
                    and unify_term_trail(left[1], right[1])
                    and unify_term_trail(left[2], right[2])
                )
            for left_item, right_item in zip(left, right):
                if not unify_term_trail(left_item, right_item):
                    return False
            return True
        if isinstance(a, ListTerm):
            recovered = self.rdf_collection_to_list(b)
            if recovered is not None:
                return unify_term_trail(a, ListTerm(recovered))
        if isinstance(b, ListTerm):
            recovered = self.rdf_collection_to_list(a)
            if recovered is not None:
                return unify_term_trail(ListTerm(recovered), b)
        if isinstance(a, OpenListTerm) and isinstance(b, ListTerm):
            if len(b.elems) < len(a.prefix):
                return False
            for x, y in zip(a.prefix, b.elems):
                if not unify_term_trail(x, y):
                    return False
            return bind_var(Var(a.tail_var), ListTerm(b.elems[len(a.prefix):]))
        if isinstance(b, OpenListTerm) and isinstance(a, ListTerm):
            return unify_term_trail(b, a)
        if isinstance(a, OpenListTerm) and isinstance(b, OpenListTerm):
            common = min(len(a.prefix), len(b.prefix))
            for x, y in zip(a.prefix[:common], b.prefix[:common]):
                if not unify_term_trail(x, y):
                    return False
            if len(a.prefix) == len(b.prefix):
                return bind_var(Var(a.tail_var), Var(b.tail_var))
            if len(a.prefix) < len(b.prefix):
                return bind_var(Var(a.tail_var), OpenListTerm(b.prefix[common:], b.tail_var))
            return bind_var(Var(b.tail_var), OpenListTerm(a.prefix[common:], a.tail_var))
        if isinstance(a, GraphTerm) and isinstance(b, GraphTerm):
            return unify_graphs_trail(a.triples, b.triples)
        return False

    def unify_triple_trail(a: Triple, b: Triple) -> bool:
        return (
            unify_term_trail(a.p, b.p)
            and unify_term_trail(a.s, b.s)
            and unify_term_trail(a.o, b.o)
        )

    def apply_delta(delta: Subst) -> bool:
        for name, value in list(delta.items()):
            if not unify_term_trail(Var(name), value):
                return False
        return True

    def answer_from_current() -> Subst:
        answer: Subst = {}
        for name in answer_vars:
            value = apply_subst_trail(Var(name))
            if not (isinstance(value, Var) and value.name == name):
                answer[name] = value
        return answer

    visited_reset = object()
    Frame = dict[str, Any]
    stack: list[Frame] = [
        {"kind": "node", "goals": list(goals), "depth": depth, "reorder": allow_reorder}
    ]
    while stack:
        frame = stack.pop()
        kind = frame["kind"]
        if kind == "undo":
            undo_to(frame["subst_mark"])
            undo_visited_to(frame["visited_mark"])
            continue
        if kind == "delta_iter":
            deltas = frame["deltas"]
            while frame["index"] < len(deltas):
                delta = deltas[frame["index"]]
                frame["index"] += 1
                mark = len(trail)
                if not apply_delta(delta):
                    undo_to(mark)
                    continue
                if not frame["rest"]:
                    answer = answer_from_current()
                    if goal_memo_key is not None:
                        completed_answers.append(dict(answer))
                    yield answer
                    undo_to(mark)
                    continue
                stack.append(frame)
                stack.append({"kind": "undo", "subst_mark": mark, "visited_mark": len(visited_trail)})
                stack.append({
                    "kind": "node",
                    "goals": frame["rest"],
                    "depth": frame["depth"] + 1,
                    "reorder": frame["reorder"],
                })
                break
            continue
        if kind in {"fact_iter", "rule_fact_iter", "memo_answer_iter"}:
            items = frame["items"]
            while frame["index"] < len(items):
                item = items[frame["index"]]
                frame["index"] += 1
                mark = len(trail)
                if not unify_triple_trail(frame["goal"], item):
                    undo_to(mark)
                    continue
                if not frame["rest"]:
                    answer = answer_from_current()
                    if goal_memo_key is not None:
                        completed_answers.append(dict(answer))
                    yield answer
                    undo_to(mark)
                    continue
                stack.append(frame)
                stack.append({"kind": "undo", "subst_mark": mark, "visited_mark": len(visited_trail)})
                stack.append({
                    "kind": "node",
                    "goals": frame["rest"],
                    "depth": frame["depth"] + 1,
                    "reorder": frame["reorder"],
                })
                break
            continue
        if kind == "rule_iter":
            rules = frame["rules"]
            while frame["index"] < len(rules):
                rule = rules[frame["index"]]
                frame["index"] += 1
                if len(rule.premise) != 1:
                    continue
                std = self.standardize_apart(rule)
                mark = len(trail)
                if not unify_triple_trail(frame["goal"], std.premise[0]):
                    undo_to(mark)
                    continue
                body = list(std.conclusion)
                if frame["goal_was_visited"] and any(
                    goal_key(apply_subst_triple_trail(premise)) in visited_counts
                    for premise in body
                ):
                    undo_to(mark)
                    continue
                visited_mark = len(visited_trail)
                push_visited(frame["goal_key"])
                stack.append(frame)
                stack.append({"kind": "undo", "subst_mark": mark, "visited_mark": visited_mark})
                next_goals = body + frame["rest"]
                if frame["rest"]:
                    next_goals = body + [(visited_reset, visited_mark)] + frame["rest"]
                stack.append({
                    "kind": "node",
                    "goals": next_goals,
                    "depth": frame["depth"] + 1,
                    "reorder": False,
                })
                break
            continue

        goals_now = frame["goals"]
        depth_now = frame["depth"]
        reorder_now = frame["reorder"]
        if depth_now > self.max_depth:
            continue
        if not goals_now:
            answer = answer_from_current()
            if goal_memo_key is not None:
                completed_answers.append(dict(answer))
            yield answer
            continue
        if isinstance(goals_now[0], tuple) and goals_now[0][0] is visited_reset:
            undo_visited_to(goals_now[0][1])
            stack.append({
                "kind": "node",
                "goals": goals_now[1:],
                "depth": depth_now,
                "reorder": reorder_now,
            })
            continue

        selected = select_goal_index_trail(goals_now) if reorder_now else 0
        first = apply_subst_triple_trail(goals_now[selected])
        rest = goals_now[:selected] + goals_now[selected + 1:]

        # A registered builtin owns its predicate and does not fall through
        # to ordinary facts or backward rules.
        if isinstance(first.p, Iri):
            handler = get_builtin(first.p.value)
            if handler is not None:
                # The selected goal is already substitution-applied. Match
                # Eyeling's hot path: builtins return only the new bindings
                # introduced while evaluating this goal, not a full copy of
                # the current proof state.
                builtin_subst = (
                    subst_mut
                    if first.p.value in {
                        LOG_NS + "collectAllIn",
                        LOG_NS + "forAllIn",
                        LOG_NS + "includes",
                        LOG_NS + "notIncludes",
                    }
                    else {}
                )
                ctx = BuiltinContext(first, builtin_subst, self)
                deltas = list(handler(ctx))
                if deltas:
                    stack.append({
                        "kind": "delta_iter",
                        "deltas": deltas,
                        "index": 0,
                        "rest": rest,
                        "depth": depth_now,
                        "reorder": reorder_now,
                    })
                continue

            if first.p.value in {RDF_FIRST, RDF_REST}:
                seen_lists: set[ListTerm] = set()
                for fact in self.facts:
                    for term in (fact.s, fact.p, fact.o):
                        if isinstance(term, ListTerm) and term.elems:
                            seen_lists.add(term)
                synthetic: list[Triple] = []
                for collection in seen_lists:
                    obj = collection.elems[0] if first.p.value == RDF_FIRST else ListTerm(collection.elems[1:])
                    synthetic.append(Triple(collection, first.p, obj))
                if synthetic:
                    stack.append({
                        "kind": "fact_iter",
                        "items": synthetic,
                        "index": 0,
                        "goal": first,
                        "rest": rest,
                        "depth": depth_now,
                        "reorder": reorder_now,
                    })

        # Predicate-scoped memoization remains opt-in via log:memoize.
        if isinstance(first.p, Iri) and first.p.value in self._memoized_predicates:
            memo_key = self._predicate_memo_key(first)
            if memo_key is not None:
                table, memo_entry = self._predicate_memo_lookup(memo_key)
                if not memo_entry["complete"] and not memo_entry["computing"]:
                    bottom_up_entry = self._try_bottom_up_numeric_memo(first)
                    if bottom_up_entry is not None:
                        memo_entry = bottom_up_entry
                if memo_entry["complete"]:
                    stack.append({
                        "kind": "memo_answer_iter",
                        "items": memo_entry["answers"],
                        "index": 0,
                        "goal": first,
                        "rest": rest,
                        "depth": depth_now,
                        "reorder": reorder_now,
                    })
                    continue
                if not memo_entry["computing"]:
                    memo_entry["computing"] = True
                    memo_successors: list[Subst] = []
                    try:
                        for nxt in self.solve(
                            [first],
                            {},
                            depth_now + 1,
                            reorder_now,
                            frozenset(visited_counts),
                        ):
                            self._store_predicate_memo_answer(memo_entry, first, nxt)
                            memo_successors.append(nxt)
                    finally:
                        memo_entry["computing"] = False
                        if memo_entry["unsafe"]:
                            table.pop(memo_key, None)
                        else:
                            memo_entry["complete"] = True
                    if memo_successors:
                        stack.append({
                            "kind": "delta_iter",
                            "deltas": memo_successors,
                            "index": 0,
                            "rest": rest,
                            "depth": depth_now,
                            "reorder": reorder_now,
                        })
                    continue

        # On re-entering an ancestor goal, reject only rules whose body
        # immediately re-enters that ancestor chain. This is Eyeling's
        # inexpensive guard for direct and mutual recursion.
        first_key = goal_key(first)
        goal_was_visited = first_key in visited_counts
        # Eyeling only indexes/applies backward rules for a ground IRI
        # predicate. Variable-predicate goals range over facts.
        candidate_rules: list[Rule]
        if isinstance(first.p, Iri):
            candidate_rules = [
                *self._backward_rules_by_pred.get(first.p.value, ()),
                *self._wild_backward_rules,
            ]
        else:
            candidate_rules = []

        # Push in reverse processing order so facts are explored first, as
        # in the previous Python solver.
        if candidate_rules:
            stack.append({
                "kind": "rule_iter",
                "rules": candidate_rules,
                "index": 0,
                "goal": first,
                "goal_key": first_key,
                "goal_was_visited": goal_was_visited,
                "rest": rest,
                "depth": depth_now,
            })
        rule_facts = list(self._candidate_rule_facts(first))
        if rule_facts:
            stack.append({
                "kind": "rule_fact_iter",
                "items": rule_facts,
                "index": 0,
                "goal": first,
                "rest": rest,
                "depth": depth_now,
                "reorder": reorder_now,
            })
        facts = list(self._candidate_facts(first))
        if facts:
            stack.append({
                "kind": "fact_iter",
                "items": facts,
                "index": 0,
                "goal": first,
                "rest": rest,
                "depth": depth_now,
                "reorder": reorder_now,
            })

    if goal_memo is not None and goal_memo_key is not None:
        goal_memo[goal_memo_key] = completed_answers

standardize_term_apart

standardize_term_apart(term: Term, *, scope_key: str | None = None) -> Term

Give variables in an external term an engine-local lexical scope.

Source code in pyling/engine.py
def standardize_term_apart(self, term: Term, *, scope_key: str | None = None) -> Term:
    """Give variables in an external term an engine-local lexical scope."""
    if scope_key is not None and scope_key in self._standardized_term_cache:
        return self._standardized_term_cache[scope_key]
    standardized = self._fresh_variable_renamer("e")(term)
    if scope_key is not None:
        self._standardized_term_cache[scope_key] = standardized
    return standardized

reason_stream

reason_stream(input_data: Any = '', *, rdf: bool = False, rdf12: bool = False, input_format: str | None = None, include_input_facts_in_closure: bool = False, max_depth: int | None = None, max_iterations: int | None = None, store: Any = None) -> ReasonStreamResult

Parse input_data and run the reasoner to a fixed point.

input_data is an N3/Turtle/TriG/etc. string, a source-list mapping ({"sources": [...]}}), or an already-parsed :class:Document/AST bundle. All other reasoning options are explicit keyword arguments.

Source code in pyling/engine.py
def reason_stream(
    input_data: Any = "",
    *,
    rdf: bool = False,
    rdf12: bool = False,
    input_format: str | None = None,
    include_input_facts_in_closure: bool = False,
    max_depth: int | None = None,
    max_iterations: int | None = None,
    store: Any = None,
) -> ReasonStreamResult:
    """Parse ``input_data`` and run the reasoner to a fixed point.

    ``input_data`` is an N3/Turtle/TriG/etc. string, a source-list mapping
    (``{"sources": [...]}}``), or an already-parsed :class:`Document`/AST
    bundle. All other reasoning options are explicit keyword arguments.
    """
    options = _build_options(
        rdf=rdf,
        rdf12=rdf12,
        input_format=input_format,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
        store=store,
    )
    doc = _input_to_document(input_data, options)
    engine = Engine(doc, options)
    if store is not None:
        # For sync API, store support is in-memory during the run; run_async persists.
        engine.store = create_fact_store(store)
    return engine.run()

reason

reason(input_data: Any = '', *, rdf: bool = False, rdf12: bool = False, input_format: str | None = None, include_input_facts_in_closure: bool = False, max_depth: int | None = None, max_iterations: int | None = None, store: Any = None, ast: bool = False, proof: bool = False) -> str

Reason over input_data and return the closure rendered as N3.

Pass ast=True to get the parsed AST as a JSON string instead.

Source code in pyling/engine.py
def reason(
    input_data: Any = "",
    *,
    rdf: bool = False,
    rdf12: bool = False,
    input_format: str | None = None,
    include_input_facts_in_closure: bool = False,
    max_depth: int | None = None,
    max_iterations: int | None = None,
    store: Any = None,
    ast: bool = False,
    proof: bool = False,
) -> str:
    """Reason over ``input_data`` and return the closure rendered as N3.

    Pass ``ast=True`` to get the parsed AST as a JSON string instead.
    """
    options = _build_options(
        rdf=rdf,
        rdf12=rdf12,
        input_format=input_format,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
        store=store,
        ast=ast,
        proof=proof,
    )
    if ast:
        doc = _input_to_document(input_data, options)
        value = [
            {"_type": "PrefixEnv", "map": doc.prefixes.map, "baseIri": doc.prefixes.base_iri},
            [triple_to_primitive(t) for t in doc.triples],
            [rule_to_primitive(r) for r in doc.forward_rules],
            [rule_to_primitive(r) for r in doc.backward_rules],
        ]
        return json.dumps(value, indent=2, sort_keys=True)
    return reason_stream(
        input_data,
        rdf=rdf,
        rdf12=rdf12,
        input_format=input_format,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
        store=store,
    ).closure_n3

reason_graph

reason_graph(input_data: Any = '', *, rdf: bool = False, rdf12: bool = False, input_format: str | None = None, include_input_facts_in_closure: bool = False, max_depth: int | None = None, max_iterations: int | None = None, store: Any = None)

Reason over input and return the selected closure as an RDFLib Graph.

Source code in pyling/engine.py
def reason_graph(
    input_data: Any = "",
    *,
    rdf: bool = False,
    rdf12: bool = False,
    input_format: str | None = None,
    include_input_facts_in_closure: bool = False,
    max_depth: int | None = None,
    max_iterations: int | None = None,
    store: Any = None,
):
    """Reason over input and return the selected closure as an RDFLib Graph."""
    return reason_stream(
        input_data,
        rdf=rdf,
        rdf12=rdf12,
        input_format=input_format,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
        store=store,
    ).as_rdflib_graph(include_input_facts=include_input_facts_in_closure)

run_async async

run_async(input_data: Any = '', *, rdf: bool = False, rdf12: bool = False, input_format: str | None = None, include_input_facts_in_closure: bool = False, max_depth: int | None = None, max_iterations: int | None = None, store: Any = None, store_path: str | None = None, store_clear: bool = False) -> ReasonStreamResult

Like :func:reason_stream, but awaits a persistent fact store.

Provide either store (a fact-store spec mapping) or store_path (with optional store_clear) to persist facts across runs.

Source code in pyling/engine.py
async def run_async(
    input_data: Any = "",
    *,
    rdf: bool = False,
    rdf12: bool = False,
    input_format: str | None = None,
    include_input_facts_in_closure: bool = False,
    max_depth: int | None = None,
    max_iterations: int | None = None,
    store: Any = None,
    store_path: str | None = None,
    store_clear: bool = False,
) -> ReasonStreamResult:
    """Like :func:`reason_stream`, but awaits a persistent fact store.

    Provide either ``store`` (a fact-store spec mapping) or ``store_path``
    (with optional ``store_clear``) to persist facts across runs.
    """
    options = _build_options(
        rdf=rdf,
        rdf12=rdf12,
        input_format=input_format,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
        store=store,
        store_path=store_path,
        store_clear=store_clear,
    )
    doc = _input_to_document(input_data, options)
    engine = Engine(doc, options)
    store_opt = store or (store_path and {"name": "default", "path": store_path, "clear": store_clear})
    if store_opt:
        fact_store = create_fact_store(store_opt)
        # Load previous store facts.
        if hasattr(fact_store, "triples"):
            for tr in fact_store.triples:
                engine.add_fact(tr, inferred=False)
        result = engine.run()
        for tr in doc.triples:
            await fact_store.add(tr, "explicit")
        for tr in result.derived:
            await fact_store.add(tr, "inferred")
        result.store = fact_store
        return result
    return engine.run()

reason_message_stream

reason_message_stream(input_data: Any = '', *, include_input_facts_in_closure: bool = False, max_depth: int | None = None, max_iterations: int | None = None) -> Iterator[ReasonStreamResult]

Run rules against an RDF Message Log one replay message at a time.

Non-message sources are parsed once as rules/facts. Each yielded result is equivalent to running the reasoner over those base sources plus one replay envelope document.

Source code in pyling/engine.py
def reason_message_stream(
    input_data: Any = "",
    *,
    include_input_facts_in_closure: bool = False,
    max_depth: int | None = None,
    max_iterations: int | None = None,
) -> Iterator[ReasonStreamResult]:
    """Run rules against an RDF Message Log one replay message at a time.

    Non-message sources are parsed once as rules/facts. Each yielded result is
    equivalent to running the reasoner over those base sources plus one replay
    envelope document.
    """
    options = _build_options(
        rdf=True,
        include_input_facts_in_closure=include_input_facts_in_closure,
        max_depth=max_depth,
        max_iterations=max_iterations,
    )
    sources = _input_to_sources(input_data)
    base_docs: list[Document] = []
    message_sources: list[tuple[str, str | None]] = []
    for text, base in sources:
        if is_rdf_message_log(text):
            message_sources.append((text, base))
        elif text.strip():
            base_docs.append(_parse_source_auto(text, options, base_iri=base))
    if not message_sources:
        raise ValueError("no RDF Message Log source found")
    for text, base in message_sources:
        for message_doc in iter_rdf_message_documents(text, base_iri=base):
            doc = _merge_documents([*base_docs, message_doc])
            engine = Engine(doc, options)
            yield engine.run()