1/*  Part of Extended Libraries for SWI-Prolog
    2
    3    Author:        Edison Mera
    4    E-mail:        efmera@gmail.com
    5    WWW:           https://github.com/edisonm/xlibrary
    6    Copyright (C): 2026, Process Design Center, Breda, The Netherlands.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(local_dynamic,
   36          [ % context
   37            with_local_dynamic/2,
   38            with_local_dynamic/3,
   39
   40            % mutation
   41            ld_asserta/1,
   42            ld_asserta/2,
   43            ld_assertz/1,
   44            ld_assertz/2,
   45            ld_retract/1,
   46            ld_retract/2,
   47            ld_retractall/1,
   48            ld_retractall/2,
   49
   50            % querying
   51            ld_call/1,
   52            ld_call/2
   53    
   54          ]).

local_dynamic

Scoped dynamic predicates.

This module provides a disciplined way to use dynamic predicates with a well-defined scope and lifetime. Dynamic predicates declared through with_local_dynamic/2 or with_local_dynamic/3 exist only for the duration of a goal and are automatically cleaned up on exit, regardless of success, failure, or exception.

The intent is to allow temporary or working-memory-style use of dynamic predicates without relying on global state, while preserving normal Prolog semantics such as backtracking, logical update semantics, and indexing (JITI).

A local dynamic context is introduced using with_local_dynamic/… . Within this context, predicates described by a schema (a list of Name/Arity pairs, optionally module-qualified) may be asserted, retracted, and called using the ld_* predicates. Outside the context, these predicates are not visible logically.

Dynamic predicate definitions are reused internally and cleared using retractall/1 with most-general heads. This avoids unbounded growth of dynamic predicate definitions, keeps cleanup efficient, and preserves predicate identity and indexing across invocations.

Contexts are thread-local: each thread has its own independent set of local dynamic predicates. No synchronization is required between threads, but it is the caller’s responsibility to ensure that a local dynamic context is not accessed after its scope has ended.

The public API mirrors Prolog’s built-in dynamic database predicates:

Implicit ld_* operations refer to the most recently entered local dynamic context; explicit forms accept a Scope argument to select a specific context.

This module is intended for temporary data, working memories, rule engines, planners, and similar patterns where dynamic predicates are convenient but global visibility is undesirable. */

  105:- meta_predicate with_local_dynamic(:, -, 0).  106:- meta_predicate with_local_dynamic(:, 0).  107
  108/*
  109  ld_relation(Store, Pattern, Pred, Module)
  110
  111  Store   : store identifier (atom)
  112  Pattern : relation Pattern
  113  Pred    : internal predicate head
  114  Module  : context module
  115*/
  116
  117:- dynamic ld_relation/4.  118:- volatile ld_relation/4.  119
  120% Keep a pool of released predicates for reusage
  121:- dynamic ld_released/3.  122:- volatile ld_released/3.  123
  124% private API lifecycle
 ld_new(+Schema, +M, -Store)
Create a new store. Schema is a list of Name/Arity pairs.
  131ld_new(Schema, M, Store) :-
  132    must_be(list, Schema),
  133    gensym(ld_, Store),
  134    forall(
  135        member(Name/Arity, Schema),
  136        ld_define_relation(Store, M, Name, Arity)
  137    ).
  138
  139ld_define_relation(Store, M, Name, Arity) :-
  140    must_be(atom, Name),
  141    must_be(integer, Arity),
  142    functor(Patt, Name, Arity),
  143    (   retract(ld_released(Patt, M, Term))
  144    ->  true
  145    ;   gensym(Name, Pred),
  146        Patt =.. [Name | Args],
  147        Term =.. [Pred | Args],
  148        dynamic(M:Pred/Arity),
  149        volatile(M:Pred/Arity)
  150    ),
  151    % NOTE:
  152    % ld_relation/4 entries are asserted with asserta/1 so that
  153    % implicit operations (ld_assertz/1, ld_query/1, etc.)
  154    % always target the most recently entered with_local_dynamic/… scope.
  155    asserta(ld_relation(Store, Patt, M, Term)).
 ld_free(+Store)
Destroy a store and all its data, remove all data from all patterns in the store, and Add the released relations to the released table
  164ld_free(Store) :-
  165    forall(
  166        retract(ld_relation(Store, Patt, M, Term)),
  167        (   retractall(M:Term),
  168            asserta(ld_released(Patt, M, Term))
  169        )).
 with_local_dynamic(:Schema, :Goal) is det
 with_local_dynamic(:Schema, -Scope, :Goal) is det
Execute Goal in a context where the dynamic predicates described by Schema exist only locally and for the duration of Goal.

Schema is a list of Name/Arity pairs (optionally module-qualified) defining the relations available in the local dynamic context. Any clauses asserted into these predicates are visible only within Goal and are automatically removed on exit, regardless of success, failure, or exception.

Predicates in the schema are reused across invocations and cleared using retractall/1, avoiding unbounded growth of dynamic predicate definitions and preserving indexing (JITI) information.

Scope, when provided, is an identifier for the local dynamic context and can be used with the explicit ld_* predicates. If omitted, the most recently entered local dynamic context is used implicitly.

This predicate provides scoped, volatile dynamic predicates and is intended as a disciplined alternative to using global dynamics for temporary or working-memory data.

  195with_local_dynamic(M:Schema, Store, Goal) :-
  196    setup_call_cleanup(
  197        ld_new(Schema, M, Store),
  198        Goal,
  199        ld_free(Store)
  200    ).
 ld_assertz(+Store, +Fact)
Insert a fact at the end in the store
  206ld_assertz(Store, Fact) :-
  207    ld_pred(Store, Fact, Term),
  208    assertz(Term).
 ld_asserta(+Store, +Fact)
Insert a fact at the beginning in the store
  214ld_asserta(Store, Fact) :-
  215    ld_pred(Store, Fact, Term),
  216    asserta(Term).
 ld_retract(+Store, +Pattern)
Delete a fact matching Pattern from the store. Could retract more facts on backtracking
  223ld_retract(Store, Pattern) :-
  224    ld_pred(Store, Pattern, Term),
  225    retract(Term).
 ld_retractall(+Store, +Pattern)
Delete all facts matching Pattern from the store.
  231ld_retractall(Store, Pattern) :-
  232    ld_pred(Store, Pattern, Term),
  233    retractall(Term).
 ld_call(+Store, +Pattern)
Query a pattern nondeterministically.
  239ld_call(Store, Pattern) :-
  240    ld_pred(Store, Pattern, Term),
  241    call(Term).
  242
  243with_local_dynamic(Schema, Goal) :-
  244    with_local_dynamic(Schema, _, Goal).
  245
  246ld_asserta(Fact) :-
  247    ld_asserta(_, Fact).
  248
  249ld_assertz(Fact) :-
  250    ld_assertz(_, Fact).
  251
  252ld_call(Fact) :-
  253    ld_call(_, Fact).
  254
  255ld_retract(Fact) :-
  256    ld_retract(_, Fact).
  257
  258ld_retractall(Fact) :-
  259    ld_retractall(_, Fact).
 ld_pred(+Store, +Pattern, -Term)
Resolve the internal predicate for a fact.
  265ld_pred(Store, Pattern, M:Term) :-
  266    ld_relation(Store, Pattern, M, Term),
  267    !.
  268ld_pred(Store, Pattern, _) :-
  269    domain_error(local_dynamic(Store), Pattern).
  270
  271/*
  272example :-
  273    with_local_dynamic([edge/2], S1,
  274        with_local_dynamic([edge/2], S2,
  275            (   ld_assertz(S1, edge(a,b)),
  276                ld_assertz(S2, edge(b,c)),
  277
  278                ld_call(S1, edge(X,Y)),
  279                format("S1: ~w -> ~w~n", [X,Y]),
  280
  281                ld_call(S2, edge(U,V)),
  282                format("S2: ~w -> ~w~n", [U,V]),
  283
  284                ld_call(edge(M,N)),
  285                format("S3: ~w -> ~w~n", [M,N])
  286            )
  287        )).
  288*/