From 3ffa60dd94f733996b67230d592fcba1cdf3be50 Mon Sep 17 00:00:00 2001 From: "Yang, Bo" Date: Fri, 25 Sep 2026 06:06:55 +0000 Subject: [PATCH] hash_consing 0.1.0: hash-consed terms and a load-time clause rewrite, as an SWI-Prolog pack Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 62 ++ .gitignore | 2 + README.md | 59 +- pack.pl | 7 + prolog/hash_consing.pl | 956 +++++++++++++++++++ test/hash_consing_fixtures/inner_dispatch.pl | 47 + test/hash_consing_fixtures/plain.pl | 9 + test/hash_consing_fixtures/reconfigured.pl | 8 + test/hash_consing_fixtures/spines.pl | 14 + test/hash_consing_fixtures/steps.pl | 22 + test/hash_consing_rewrite.pl | 298 ++++++ test/hash_consing_rewrite.sh | 15 + test/hash_consing_rewrite_baseline.txt | 385 ++++++++ 13 files changed, 1882 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 pack.pl create mode 100644 prolog/hash_consing.pl create mode 100644 test/hash_consing_fixtures/inner_dispatch.pl create mode 100644 test/hash_consing_fixtures/plain.pl create mode 100644 test/hash_consing_fixtures/reconfigured.pl create mode 100644 test/hash_consing_fixtures/spines.pl create mode 100644 test/hash_consing_fixtures/steps.pl create mode 100644 test/hash_consing_rewrite.pl create mode 100755 test/hash_consing_rewrite.sh create mode 100644 test/hash_consing_rewrite_baseline.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b5cad5e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,62 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: fabasoad/setup-prolog-action@v1 + - name: Rewrite test + run: test/hash_consing_rewrite.sh | diff - test/hash_consing_rewrite_baseline.txt + - name: The pack installs and loads + run: | + mkdir -p "$RUNNER_TEMP/packs" + swipl -g "pack_install('.', [pack_directory('$RUNNER_TEMP/packs'), interactive(false), register(false)]), use_module(library(hash_consing))" -t halt + + version: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: fabasoad/setup-prolog-action@v1 + - name: pack.pl names a version above every release + run: | + VERSION="$(swipl -g "read_file_to_terms('pack.pl', Terms, []), memberchk(version(Version), Terms), write(Version)" -t halt)" + test -n "$VERSION" + if git rev-parse --quiet --verify "refs/tags/V$VERSION" > /dev/null; then + echo "V$VERSION is already released; raise version/1 in pack.pl" >&2 + exit 1 + fi + LATEST="$(git tag --list 'V*' | sed 's/^V//' | sort -V | tail -n 1)" + if [ -n "$LATEST" ]; then + test "$(printf '%s\n%s\n' "$LATEST" "$VERSION" | sort -V | tail -n 1)" = "$VERSION" + fi + + publish: + needs: test + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: fabasoad/setup-prolog-action@v1 + - name: swipl pack publish + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git branch --set-upstream-to=origin/main main + swipl -g "pack_publish('.', [sign(false), branch(main), interactive(false)])" -t halt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e261fb0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# pack_install('.') links the pack directory here and writes its bookkeeping file into it. +/status.db diff --git a/README.md b/README.md index 52b905f..9e81b10 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,57 @@ -# interning -Hash-consed terms for SWI-Prolog, and a load-time clause rewrite that makes a program use them +# hash_consing + +[![CI](https://github.com/Atry/hash_consing/actions/workflows/ci.yml/badge.svg)](https://github.com/Atry/hash_consing/actions/workflows/ci.yml) + +Hash-consed terms for SWI-Prolog, and a load-time rewrite that makes a +program use them. A file is written as the program that does not intern and +names the constructors to intern; every clause read after that directive +refers to their instances by Ids, each wrapping a node handle of one trie, +and the store is canonical: the same term has the same Id. + +## Install + +```prolog +?- pack_install(hash_consing). +``` + +## Use + +```prolog +:- module(steps, [step/2, built/2]). +:- use_module(library(hash_consing), []). +:- hash_consing:rewritten([apply(*, _), lambda(_), variable(_)]). + +step(apply(lambda(Body), Argument), beta(Body, Argument)). + +built(Function, Applied) :- + Applied = apply(Function, variable(0)). +``` + +A term that did not come through the rewrite crosses the boundary with +`hash_consing:internalized/3`, and `hash_consing:externalized/2` turns Ids back +into terms. The module comment of [`prolog/hash_consing.pl`](prolog/hash_consing.pl) +is the reference: the relation `intern/2`, the Id and its shape, the +templates, the rewrite of a clause, the two rules for a file that opts in, +and the known defects. + +## Test + +```sh +test/hash_consing_rewrite.sh | diff - test/hash_consing_rewrite_baseline.txt +``` + +prints nothing when the rewrite and `intern/2` behave as specified. + +## Contributing and releases + +Open pull requests against `main`. `main` changes only by merging a pull +request with a merge commit, and every merge into `main` is a release: +CI runs `swipl pack publish` on the merged `main`, which tags `V` +from the `version/1` of `pack.pl`, installs the pack from this repository +in an isolated directory and registers it with the SWI-Prolog pack server. +A pull request into `main` must therefore raise `version/1` above every +released version; a required check enforces it. + +## License + +MIT. See [`LICENSE`](LICENSE). diff --git a/pack.pl b/pack.pl new file mode 100644 index 0000000..5e51f93 --- /dev/null +++ b/pack.pl @@ -0,0 +1,7 @@ +name(hash_consing). +version('0.1.0'). +title('Hash-consed terms by clause rewriting'). +keywords([interning, 'hash-consing', trie, term_expansion]). +author('Yang, Bo', 'yang-bo@yang-bo.com'). +home('https://github.com/Atry/hash_consing'). +download('https://github.com/Atry/hash_consing.git'). diff --git a/prolog/hash_consing.pl b/prolog/hash_consing.pl new file mode 100644 index 0000000..e55adc0 --- /dev/null +++ b/prolog/hash_consing.pl @@ -0,0 +1,956 @@ +:- module(hash_consing, + [ intern/2, % ?Term, ?Id + externalized/2, % +TermWithIds, -External + internalized/3, % +Constructors, +External, -TermWithIds + rewritten/1 % +Constructors + ]). + +/** hash_consing: hash-consed terms whose Ids record a configurable shape, and a term rewrite that makes a program use them + +A GENERIC LIBRARY: it knows no constructor of any calculus and keeps no +configuration but the templates files declare. + +HOW TO USE IT. A file is written as the program that does not intern, loads +this library and names the constructors to intern, each by a template: + + :- module(steps, [step/2, built/2]). + :- use_module(library(hash_consing), []). + :- hash_consing:rewritten([apply(*, _), lambda(_), variable(_)]). + + step(apply(lambda(Body), Argument), beta(Body, Argument)). + + built(Function, Applied) :- + Applied = apply(Function, variable(0)). + +Files that hand such terms to each other declare the same templates, most +simply by including one file that holds the directive. Code that did not go +through the rewrite crosses the boundary explicitly: + + ?- hash_consing:internalized([apply(*, _), lambda(_), variable(_)], + apply(lambda(variable(0)), variable(1)), Id), + steps:step(Id, Result), + hash_consing:externalized(Result, External). + Id = '__hash_consed_apply/2'('lambda/1', ), + External = beta(variable(0), variable(1)). + +With the list `[]` the file loads unchanged, which is the program without +interning. The test `test/hash_consing_rewrite.sh` prints what the rewrite +makes of its fixtures, `test/hash_consing_fixtures/`, and is the place to +read exact rewritten clauses. + +`intern(?Term, ?Id)` IS ONE RELATION WITH TWO DIRECTIONS (user, 2026-09-17: +a binary predicate that upserts forwards and looks up backwards). Term is a +ground term whose rewritten subterms are Ids already. Called with Id bound it +looks the term up (and with Term bound as well it is a check that inserts +nothing); called with Id unbound, or bound to an Id pattern whose Handle is +unbound, it inserts Term unless it is there and answers its Id; a value that +is no Id matches nothing and the call fails, as a pattern that does not match +fails without interning (user ruling, 2026-09-17: an uninterned instance at +an Id position fails to unify rather than raising). The store is canonical +(the same term, the same Id), idempotent and monotone (it only grows and +backtracking does not shrink it), so an answer once given is never +contradicted. An Id is abstract: only `==`, `intern/2` and the two boundary +predicates look at it. + +AN ID IS `'__hash_consed_Name/Arity'(Handle)` OR +`'__hash_consed_Name/Arity'(Shape, Handle)`. Name/Arity is the root constructor +of the term and Handle the node handle of one trie, the store. The root is in +the functor name so that the rewrite turns a head pattern `apply(F, X)` into +an Id pattern that first argument indexing tells apart by constructor, and a +value of another constructor, or no Id at all, fails at head unification +without a lookup (probe, 2026-09-17: with one functor for every Id, 156 ms +against 0.9 ms for 1000 calls over 2000 clauses). The prefix follows +SWI-Prolog's convention for names a library synthesises +(`library(apply_macros)`'s `'__aux_maplist/N_...'`); a leading `$` is reserved +for the system. + +THE SHAPE is there for clauses told apart by an INNER constructor, + + step(apply(lambda(Body), Argument)) :- ... + step(apply(closure_a(Capture), Argument)) :- ... + +whose heads would otherwise be one Id pattern, every candidate clause paying +a lookup before it fails. Shape is ONE ATOM that spells the constructors +found below the root, as far as the constructor's template says (user, +2026-09-20: the Id keeps one layer, the shape may have several; the layers +are joined into one atom, not kept as several shapes; how deep is +configurable). The heads above become +`step('__hash_consed_apply/2'('lambda/1', Handle))` and +`step('__hash_consed_apply/2'('closure_a/1', Handle))`, and the deep index +SWI-Prolog builds on the first argument of the first argument tells them +apart without a lookup (benchmark, 2026-09-20: 1000 calls over 2000 +such clauses, 621 ms without the shape and 3 ms with it; upserts 46 percent +slower; the store no larger). + +THE ID STILL HAS ONE LAYER. The shape is not in the functor name, because a +shallow pattern `apply(F, X)` has to match the Ids of every shape and the set +of inner constructors is open across files; and the Id holds no Id of a +subterm, because a truncation would give one term two spellings and split +`==` and the table keys. A shape is a function of the content and the +template, so the Handle determines it and the store stays canonical. + +THE CONFIGURATION IS A TEMPLATE, one syntax for every constructor (user, +2026-09-20: one syntax, not three; the template names the constructor, so no +indicator beside it; a depth of zero is another feature and is not offered). +An element of the directive's list is the constructor applied to one of these +at each argument position (a constructor of arity zero is its atom): + + _ nothing is recorded about the argument + * the root constructor of the argument is recorded + a nested template the root constructor is recorded and, when it is the + template's constructor, the template goes on below + it; alternatives are joined by `;` + +`lambda(_)` records the root only and its Ids are +`'__hash_consed_lambda/1'(Handle)`. `apply(*, _)` +gives `apply(lambda(B), X)` the shape `'lambda/1'`; with +`apply(apply(*, _), _)`, `apply(apply(lambda(B), Y), X)` has the shape +`'apply/2(lambda/1)'` and `apply(lambda(B), X)` still `'lambda/1'`. An +argument that is no Id is written `-`. The reading has a precedent in +SWI-Prolog's mode-directed tabling, `:- table path(_, _, min)`. + +THE SHAPE IS A FUNCTION OF THE TERM AND OF ITS OWN TEMPLATE, and of nothing +else: at a `*` the root is read off the functor name of the argument's Id, +with no lookup; each nested template costs an upsert one `trie_term/2` on the +argument's Id. The spelling of a shape is remembered in a trie keyed by its +structure, so an atom is built once per structure; the atoms are finitely +many, bounded by the templates and the constructors. + +AT COMPILE TIME a pattern that determines everything its template records +gets the atom written into the head; a pattern that determines only part of +it gets an unbound shape, which is correct (the constructors of the pattern +are still checked by the lookups of the body) and unindexed. A nested +template reads the argument's own arguments off the occurrence of that +argument in the same clause, or off the store when its Id was baked. A +partial pattern is NOT expanded into one clause per completion: a file loaded +later brings new shapes, which the expanded clauses would silently miss. So +the deeper a template, the fewer patterns determine it. + +ONE CONFIGURATION PER CONSTRUCTOR, PER PROCESS: a second declaration of a +constructor with another template raises while the file loads, because two +shapes of one term would not be `==` (agent design decision, 2026-09-20, not +objected to by the user; between files the library checks nothing else, by +the user's ruling of 2026-09-17: which files list which constructors is the +user's to arrange, for instance with one included file). + +THE STORE IS ONE TRIE, used through SWI-Prolog's trie API directly (user, +2026-09-17, after a benchmark of four candidate stores: "use the trie"). Its +key is the term itself, constructor included (a trie shares a functor node +among all its keys), and its value is the key's own handle, written back with +`trie_update/3` right after the insertion, because inserting an existing +key with a different value raises instead of failing. It lives outside +the table space and `trie_property(Trie, value_count(Count))` counts it. + +`externalized/2` AND `internalized/3` ARE THE BOUNDARY: the first replaces +every Id by its term, recursively, for printing, for writing a file and for a +content address; the second interns, bottom up, the instances of the +constructors whose templates it is given, for a term that did not come through the rewrite +(a toplevel query, `read_term/2`, a module that did not opt in, a term built +by `=..`). + +`:- hash_consing:rewritten(Templates).` OPTS A FILE IN (user ruling, +2026-09-17: opt-in per file, the constructors passed to the directive, no +setting). Every clause read after it in that file, included files counted, +has each occurrence of a listed constructor turned into an +Id pattern and a call of `intern/2`, the direction of each call decided at +run time, so the file is written as the program that does not intern and +needs no mode declaration. Several directives in one file add up. An empty +list rewrites nothing. The library checks no consistency between files: +files that pass one constructor to each other must both list it, which the +user arranges, for instance with one included file (user ruling, +2026-09-17). + +THE REWRITE OF A CLAUSE: + + head fast path when the Handle of every top-level head occurrence + is bound: look them up top down, then run the body, which + keeps the last call; otherwise look up the bound ones top + down, insert the ground ones bottom up, run the body, insert + the rest bottom up (an instantiation error when a term is + still not ground) + body goal when the variables of its terms are bound: insert bottom up + and call; otherwise insert the ground ones, call, and then + settle every occurrence top down (a lookup when the call + bound the Id, an insertion when it made the term ground, an + instantiation error when neither) + ground an occurrence that is ground in the source is interned while + the file loads and its Id is written into the clause + +Control constructs (`,`, `;`, `->`, `*->`, `\+`, `call/1`, `forall/2`, the +goal of `findall/3` and of `catch/3`, a module-qualified goal) are rewritten +inside. A listed constructor in the template or the result of `findall/3`, +in the catcher of `catch/3`, or in a DCG rule raises while the file loads. +Directives are not rewritten. + +TWO RULES FOR A FILE THAT OPTS IN. (1) An instance of a listed constructor is +settled, ground or its Id bound, by the end of the goal it is handed to; a +term handed over half built and filled in later raises an instantiation +error. (2) Reflection sees Ids: `=..`, `functor/3`, `arg/3`, `write/1`, +`variant_sha1/2`, `term_hash/2` and ordering whose result depends on the +order see `'__hash_consed_Name/Arity'(Handle)`. Code that reads structure calls +`externalized/2` first, and code that builds an instance with them calls +`internalized/3` after; an instance left uninterned fails to unify at every +rewritten position. Using an Id as an opaque key, whose result does not +depend on the order (an assoc key, a sort to remove duplicates), is fine. + +THIS MODULE REFLECTS ON SOURCE CLAUSES with `=..` while a file loads, a +mechanical boundary; nothing here chooses behaviour at run time by +reflection, and no closure is handed to another module. + +FIXME: `trie_term/2` on an integer that is no node of the store crashes the +process with a segmentation fault (measured 2026-09-14 on `trie_term(42, +_)`); a forged `'__hash_consed_apply/2'(42)` reaches it. Only a bug makes +such a value. Candidate fix: none in the trie API; the assertz backends of +the benchmark raise instead, at the costs recorded there. + +FIXME: on 2026-09-14, within tabled +compiles near a full stack, `trie_lookup/3` failed silently on a key of the +store and left the resource error pending. Here such a failure turns an +upsert into an insertion of an existing key, which raises, or a lookup into a +failure, which reads as no answer rather than `resource_error`. A direct probe +at 1m, 4m and 32m stacks on 2026-09-17 raised `resource_error(stack)` every +time and did not reproduce it. + +FIXME: the order of two Ids depends on the insertion +history. Nothing checks that no code in an opted-in file reads that order; +it is a rule of the file, stated above. + +FIXME: an Id written into a clause while the file loads +is a handle of this process. A file must be loaded from source, never +`qcompile`d nor saved in a state, and the store lives in one thread's global +variable. + +FIXME: a file that uses a constructor another file +interns, without listing it, passes its instances uninterned; the rewritten +positions of the other file then fail to unify, silently. The library cannot +see it. +*/ + +:- use_module(library(error), [must_be/2]). +:- use_module(library(lists), [reverse/2, append/3]). + +:- initialization(stores_created). + +%! stores_created the store and the spellings of the shapes, two tries in +% global variables of the loading thread. + +stores_created :- + trie_new(Store), + nb_setval(hash_consing_store, Store), + trie_new(Spellings), + nb_setval(hash_consing_spellings, Spellings). + +% ---- the relation ---- + +%! intern(?Term, ?Id) Id is the Id of the ground term Term. + +intern(Term, Id) :- + nonvar(Id), + !, + id_parts(Id, _, _, Handle), + ( nonvar(Handle) + -> trie_term(Handle, Stored), + Term = Stored + ; upserted(Term, Id) + ). +intern(Term, Id) :- + upserted(Term, Id). + +%! upserted(+Term, ?Id) insert Term unless it is stored, and answer its Id. + +upserted(Term, Id) :- + ( ground(Term) + -> true + ; throw(error(instantiation_error, context(hash_consing:intern/2, Term-Id))) + ), + nb_getval(hash_consing_store, Trie), + ( trie_lookup(Trie, Term, Handle) + -> true + ; trie_insert(Trie, Term, pending, Handle), + trie_update(Trie, Term, Handle) + ), + functor(Term, Name, Arity), + configuration_of(Name, Arity, Configuration), + id_of(Configuration, Term, Name, Arity, Handle, Id). + +id_of(root_only, _, Name, Arity, Handle, Id) :- + id_name(Name, Arity, IdName), + compound_name_arguments(Id, IdName, [Handle]). +id_of(shaped(Records), Term, Name, Arity, Handle, Id) :- + id_name(Name, Arity, IdName), + ( term_shape(Term, Records, [], Shape) + -> true + ; throw(error(instantiation_error, context(hash_consing:intern/2, Term))) + ), + compound_name_arguments(Id, IdName, [Shape, Handle]). + +%! id_parts(+Value, -IdName, -Shape, -Handle) Value is an Id or an Id +% pattern; Shape is `none` for a constructor without a shape. Fails on any +% other value. + +id_parts(Value, IdName, Shape, Handle) :- + compound(Value), + compound_name_arity(Value, IdName, Arity), + sub_atom(IdName, 0, _, _, '__hash_consed_'), + id_arguments(Arity, Value, Shape, Handle). + +id_arguments(1, Value, none, Handle) :- + arg(1, Value, Handle). +id_arguments(2, Value, Shape, Handle) :- + arg(1, Value, Shape), + arg(2, Value, Handle). + +%! id_pattern(+Name, +Arity, -Id, -Handle) an Id pattern of the constructor +% as it is configured, its Handle and, if it has one, its shape unbound. + +id_pattern(Name, Arity, Id, Handle) :- + id_name(Name, Arity, IdName), + configuration_of(Name, Arity, Configuration), + ( Configuration == root_only + -> compound_name_arguments(Id, IdName, [Handle]) + ; compound_name_arguments(Id, IdName, [_, Handle]) + ). + +%! id_name(+Name, +Arity, -IdName) the functor name of the Ids of the +% constructor Name/Arity, remembered once made, in both directions. + +:- dynamic known_id_name/3. % known_id_name(Name, Arity, IdName) +:- dynamic id_constructor/3. % id_constructor(IdName, Name, Arity) + +id_name(Name, Arity, IdName) :- + ( known_id_name(Name, Arity, Known) + -> IdName = Known + ; format(atom(Made), '__hash_consed_~w/~d', [Name, Arity]), + assertz(known_id_name(Name, Arity, Made)), + assertz(id_constructor(Made, Name, Arity)), + IdName = Made + ). + +% ---- the configuration of a constructor ---- + +:- dynamic constructor_configuration/3. % constructor_configuration(Name, Arity, Configuration) + +%! configuration_of(+Name, +Arity, -Configuration) `root_only`, or +% `shaped(Records)` with one record per argument, `ignored` or +% `root(Templates)`, Templates a list of `below(Name/Arity, Records)` for +% the nested templates; a constructor met without a declaration is +% registered as `root_only`. + +configuration_of(Name, Arity, Configuration) :- + ( constructor_configuration(Name, Arity, Known) + -> Configuration = Known + ; assertz(constructor_configuration(Name, Arity, root_only)), + Configuration = root_only + ). + +%! configuration_registered(+Name, +Arity, +Configuration) the one +% configuration of the constructor in this process; another raises. + +configuration_registered(Name, Arity, Configuration) :- + ( constructor_configuration(Name, Arity, Known) + -> ( Known == Configuration + -> true + ; throw(error(permission_error(reconfigure, interned_constructor, Name/Arity), + context(hash_consing:rewritten/1, + configured(Known)-declared(Configuration)))) + ) + ; assertz(constructor_configuration(Name, Arity, Configuration)) + ). + +%! specification(+Template, -Name, -Arity, -Configuration) an element of a +% constructor list, a template, in the form the library keeps: ground, so +% that two declarations of one constructor compare with `==`. + +specification(Template, _, _, _) :- + var(Template), + !, + throw(error(instantiation_error, context(hash_consing:rewritten/1, _))). +specification(Template, Name, Arity, Configuration) :- + callable(Template), + Template \== (*), + Template \= (_ ; _), + !, + compound_name_arguments_or_atom(Template, Name, Arguments), + length(Arguments, Arity), + arguments_records(Arguments, Records), + ( all_ignored(Records) + -> Configuration = root_only + ; Configuration = shaped(Records) + ). +specification(Template, _, _, _) :- + throw(error(type_error(constructor_template, Template), _)). + +compound_name_arguments_or_atom(Term, Name, Arguments) :- + ( atom(Term) + -> Name = Term, + Arguments = [] + ; compound_name_arguments(Term, Name, Arguments) + ). + +arguments_records([], []). +arguments_records([Argument | Arguments], [Record | Records]) :- + argument_record(Argument, Record), + arguments_records(Arguments, Records). + +argument_record(Argument, ignored) :- + var(Argument), + !. +argument_record(*, root([])) :- + !. +argument_record(Alternatives, root(Templates)) :- + alternatives_list(Alternatives, List), + templates_below(List, Templates). + +alternatives_list(Alternatives, List) :- + ( nonvar(Alternatives), + Alternatives = (Left ; Right) + -> alternatives_list(Left, LeftList), + alternatives_list(Right, RightList), + append(LeftList, RightList, List) + ; List = [Alternatives] + ). + +% A nested template whose own arguments are all ignored records nothing +% below the root, which the root already says, and is left out. +templates_below([], []). +templates_below([Template | Templates], Belows) :- + specification(Template, Name, Arity, Configuration), + ( Configuration = shaped(Records) + -> Belows = [below(Name/Arity, Records) | Rest] + ; Belows = Rest + ), + templates_below(Templates, Rest), + ( memberchk(below(Name/Arity, _), Rest) + -> throw(error(domain_error(one_template_per_constructor, Template), _)) + ; true + ). + +all_ignored([]). +all_ignored([ignored | Records]) :- + all_ignored(Records). + +% ---- shapes ---- + +% A STRUCTURE is what a shape atom spells: a list, one description per +% recorded argument, `other` for an argument that is no Id and +% `constructor(Name/Arity, Structure)` otherwise, the inner structure being +% `none` where no nested template goes on. + +%! term_shape(+Term, +Records, +Occurrences, -Atom) the shape atom of Term +% under its template. Fails when the term does not determine it: a +% recorded argument is an unbound variable, or a nested template needs the +% arguments of an Id pattern that is neither among Occurrences, the +% `occurrence(Term, Id, Handle)` of the clause being rewritten, nor stored. +% A ground Term always determines its shape. + +term_shape(Term, Records, Occurrences, Atom) :- + compound_name_arguments_or_atom(Term, _, Arguments), + arguments_descriptions(Records, Arguments, Occurrences, Structure), + nb_getval(hash_consing_spellings, Spellings), + ( trie_lookup(Spellings, Structure, Known) + -> Atom = Known + ; structure_atom(Structure, Atom), + trie_insert(Spellings, Structure, Atom) + ). + +arguments_descriptions([], [], _, []). +arguments_descriptions([ignored | Records], [_ | Arguments], Occurrences, Descriptions) :- + !, + arguments_descriptions(Records, Arguments, Occurrences, Descriptions). +arguments_descriptions([root(Templates) | Records], [Argument | Arguments], Occurrences, + [Description | Descriptions]) :- + argument_description(Argument, Templates, Occurrences, Description), + arguments_descriptions(Records, Arguments, Occurrences, Descriptions). + +argument_description(Argument, _, _, _) :- + var(Argument), + !, + fail. +argument_description(Argument, Templates, Occurrences, constructor(Name/Arity, Inner)) :- + id_parts(Argument, IdName, _, _), + !, + id_constructor(IdName, Name, Arity), + ( memberchk(below(Name/Arity, Records), Templates) + -> id_term(Argument, Occurrences, Below), + compound_name_arguments_or_atom(Below, _, BelowArguments), + arguments_descriptions(Records, BelowArguments, Occurrences, Inner) + ; Inner = none + ). +argument_description(_, _, _, other). + +%! id_term(+Id, +Occurrences, -Term) the term of an Id: stored, when its +% Handle is bound; the occurrence's, when it is a pattern of the clause +% being rewritten; fails otherwise. + +id_term(Id, Occurrences, Term) :- + id_parts(Id, _, _, Handle), + ( nonvar(Handle) + -> trie_term(Handle, Term) + ; occurrence_term(Occurrences, Id, Term) + ). + +occurrence_term([occurrence(Candidate, CandidateId, _) | Occurrences], Id, Term) :- + ( CandidateId == Id + -> Term = Candidate + ; occurrence_term(Occurrences, Id, Term) + ). + +%! structure_atom(+Structure, -Atom) the spelling: descriptions joined by +% commas, `-` for `other`, `Name/Arity` and, in parentheses, what is below. + +structure_atom(Structure, Atom) :- + descriptions_texts(Structure, Texts), + atomic_list_concat(Texts, ',', Atom). + +descriptions_texts([], []). +descriptions_texts([Description | Descriptions], [Text | Texts]) :- + description_text(Description, Text), + descriptions_texts(Descriptions, Texts). + +description_text(other, '-'). +description_text(constructor(Name/Arity, none), Text) :- + !, + format(atom(Text), '~w/~d', [Name, Arity]). +description_text(constructor(Name/Arity, Inner), Text) :- + structure_atom(Inner, InnerText), + format(atom(Text), '~w/~d(~w)', [Name, Arity, InnerText]). + +% ---- the boundary ---- + +%! externalized(+TermWithIds, -External) every Id replaced by its term, +% recursively. + +externalized(Term, External) :- + var(Term), + !, + External = Term. +externalized(Term, External) :- + id_parts(Term, _, _, Handle), + !, + ( nonvar(Handle) + -> trie_term(Handle, Stored), + externalized(Stored, External) + ; throw(error(instantiation_error, context(hash_consing:externalized/2, Term))) + ). +externalized(Term, External) :- + compound(Term), + !, + compound_name_arguments(Term, Name, Arguments), + arguments_externalized(Arguments, ExternalArguments), + compound_name_arguments(External, Name, ExternalArguments). +externalized(Term, Term). + +arguments_externalized([], []). +arguments_externalized([Argument | Arguments], [External | Externals]) :- + externalized(Argument, External), + arguments_externalized(Arguments, Externals). + +%! internalized(+Constructors, +External, -TermWithIds) every instance of a +% constructor in Constructors interned, bottom up; an Id is kept as it is. +% The list's elements are templates, as in the directive, and register the +% same configurations. + +internalized(Constructors, External, TermWithIds) :- + must_be(list, Constructors), + specifications_indicators(Constructors, Indicators), + term_internalized(External, Indicators, TermWithIds). + +specifications_indicators([], []). +specifications_indicators([Element | Elements], [Name/Arity | Indicators]) :- + specification(Element, Name, Arity, Configuration), + configuration_registered(Name, Arity, Configuration), + specifications_indicators(Elements, Indicators). + +term_internalized(Term, _, Internal) :- + var(Term), + !, + Internal = Term. +term_internalized(Term, _, Internal) :- + id_parts(Term, _, _, _), + !, + Internal = Term. +term_internalized(Term, Indicators, Internal) :- + compound(Term), + !, + compound_name_arguments(Term, Name, Arguments), + arguments_internalized(Arguments, Indicators, InternalArguments), + compound_name_arguments(Rebuilt, Name, InternalArguments), + compound_name_arity(Term, Name, Arity), + instance_internalized(Name/Arity, Indicators, Rebuilt, Internal). +term_internalized(Term, Indicators, Internal) :- + atom(Term), + !, + instance_internalized(Term/0, Indicators, Term, Internal). +term_internalized(Term, _, Term). + +arguments_internalized([], _, []). +arguments_internalized([Argument | Arguments], Indicators, [Internal | Internals]) :- + term_internalized(Argument, Indicators, Internal), + arguments_internalized(Arguments, Indicators, Internals). + +instance_internalized(Indicator, Indicators, Term, Internal) :- + ( memberchk(Indicator, Indicators) + -> intern(Term, Internal) + ; Internal = Term + ). + +% ---- the directive ---- + +%! rewritten(+Templates) the file being loaded opts in for the +% constructors whose templates are in the list; several calls add up. + +:- dynamic registered_constructor/3. % registered_constructor(SourceFile, Name, Arity) + +rewritten(Constructors) :- + must_be(list, Constructors), + ( prolog_load_context(source, File) + -> true + ; throw(error(context_error(nodirective, hash_consing:rewritten/1), _)) + ), + constructors_registered(Constructors, File). + +constructors_registered([], _). +constructors_registered([Element | Elements], File) :- + specification(Element, Name, Arity, Configuration), + configuration_registered(Name, Arity, Configuration), + id_name(Name, Arity, _), + ( registered_constructor(File, Name, Arity) + -> true + ; assertz(registered_constructor(File, Name, Arity)) + ), + constructors_registered(Elements, File). + +% ---- the rewrite ---- + +%! source_rewritten(+Source, -Rewritten) the rewrite of one term read from a +% file that opted in; fails, leaving the term to SWI-Prolog, otherwise. + +source_rewritten(Source, _) :- + var(Source), + !, + fail. +source_rewritten(end_of_file, _) :- + !, + prolog_load_context(source, File), + prolog_load_context(file, File), + retractall(registered_constructor(File, _, _)), + fail. +source_rewritten((:- _), _) :- + !, + fail. +source_rewritten((?- _), _) :- + !, + fail. +source_rewritten(Source, Rewritten) :- + prolog_load_context(source, File), + registered_constructor(File, _, _), + !, + clause_rewritten(Source, File, Candidate), + Candidate \=@= Source, + Rewritten = Candidate. + +clause_rewritten((Head --> Body), File, (Head --> Body)) :- + !, + listed_absent((Head --> Body), File, dcg_rule). +clause_rewritten((Head :- Body), File, Rewritten) :- + !, + rule_rewritten(Head, Body, File, Rewritten). +clause_rewritten(Head, File, Rewritten) :- + rule_rewritten(Head, true, File, Rewritten). + +%! rule_rewritten(+Head, +Body, +File, -Rewritten) the head's +% occurrences scheduled around the rewritten body. + +rule_rewritten(Qualifier:Head0, Body0, File, (Qualifier:Head :- Body)) :- + !, + plain_rule_rewritten(Head0, Body0, File, Head, Body). +rule_rewritten(Head0, Body0, File, (Head :- Body)) :- + plain_rule_rewritten(Head0, Body0, File, Head, Body). + +plain_rule_rewritten(Head0, Body0, File, Head, Body) :- + arguments_of_abstracted(Head0, File, Head, Occurrences), + body_rewritten(Body0, File, RewrittenBody), + head_scheduled(Occurrences, RewrittenBody, Body). + +%! arguments_of_abstracted(+Callable0, +File, -Callable, -Occurrences) the +% arguments of a head or a goal abstracted (its own functor is a predicate +% and is left alone), the ground occurrences interned now, and the others +% listed bottom up as `occurrence(Term, Id, Handle)`. + +arguments_of_abstracted(Callable0, File, Callable, Occurrences) :- + compound(Callable0), + !, + compound_name_arguments(Callable0, Name, Arguments0), + arguments_abstracted(Arguments0, File, Arguments, [], Reversed), + compound_name_arguments(Callable, Name, Arguments), + reverse(Reversed, BottomUp), + occurrences_baked(BottomUp, Occurrences), + shapes_determined(Occurrences). +arguments_of_abstracted(Callable, _, Callable, []). + +arguments_abstracted([], _, [], Reversed, Reversed). +arguments_abstracted([Argument0 | Arguments0], File, [Argument | Arguments], Reversed0, Reversed) :- + abstracted(Argument0, File, Argument, Reversed0, Reversed1), + arguments_abstracted(Arguments0, File, Arguments, Reversed1, Reversed). + +%! abstracted(+Term0, +File, -Term, +Reversed0, -Reversed) each occurrence +% of a listed constructor replaced by an Id pattern, its subterms first, +% the occurrences prepended as they are met. + +abstracted(Term, _, Term, Reversed, Reversed) :- + var(Term), + !. +abstracted(Term0, File, Term, Reversed0, Reversed) :- + compound(Term0), + !, + compound_name_arguments(Term0, Name, Arguments0), + arguments_abstracted(Arguments0, File, Arguments, Reversed0, Reversed1), + compound_name_arguments(Layer, Name, Arguments), + compound_name_arity(Term0, Name, Arity), + occurrence_abstracted(Name, Arity, Layer, File, Term, Reversed1, Reversed). +abstracted(Term0, File, Term, Reversed0, Reversed) :- + atom(Term0), + !, + occurrence_abstracted(Term0, 0, Term0, File, Term, Reversed0, Reversed). +abstracted(Term, _, Term, Reversed, Reversed). + +occurrence_abstracted(Name, Arity, Layer, File, Term, Reversed0, Reversed) :- + ( registered_constructor(File, Name, Arity) + -> id_pattern(Name, Arity, Term, Handle), + Reversed = [occurrence(Layer, Term, Handle) | Reversed0] + ; Term = Layer, + Reversed = Reversed0 + ). + +%! occurrences_baked(+BottomUp, -Remaining) an occurrence +% whose term is ground is interned while the file loads, which binds its +% Id in the clause; bottom up, so a parent of baked occurrences may become +% ground in turn. + +occurrences_baked([], []). +occurrences_baked([occurrence(Term, Id, Handle) | Occurrences], Remaining) :- + ( ground(Term) + -> intern(Term, Id), + occurrences_baked(Occurrences, Remaining) + ; Remaining = [occurrence(Term, Id, Handle) | Rest], + occurrences_baked(Occurrences, Rest) + ). + +%! shapes_determined(+BottomUp) AT COMPILE TIME (above): an +% occurrence of a shaped constructor whose pattern determines the whole +% configured shape gets the shape atom written into its Id pattern, bottom +% up so that a determined inner occurrence can determine an outer one; an +% occurrence that determines only part of it keeps an unbound shape, which +% matches every shape, and its constructors are still checked by the +% lookups of the body. + +shapes_determined(Occurrences) :- + shapes_determined(Occurrences, Occurrences). + +shapes_determined([], _). +shapes_determined([occurrence(Term, Id, _) | Rest], Occurrences) :- + ( id_parts(Id, _, Shape, _), + var(Shape), + compound_name_arguments_or_atom(Term, Name, Arguments), + length(Arguments, Arity), + constructor_configuration(Name, Arity, shaped(Records)), + term_shape(Term, Records, Occurrences, Atom) + -> Shape = Atom + ; true + ), + shapes_determined(Rest, Occurrences). + +%! head_scheduled(+BottomUp, +Body0, -Body) the head row of THE REWRITE +% OF A CLAUSE (above). + +head_scheduled([], Body, Body) :- + !. +head_scheduled(BottomUp, Body0, (Condition -> Fast ; General)) :- + reverse(BottomUp, TopDown), + top_level_occurrences(BottomUp, BottomUp, TopLevel), + handles_bound(TopLevel, Condition), + occurrences_goal(TopDown, intern, Lookups), + occurrences_goal(TopDown, intern_if_bound, Settled), + occurrences_goal(BottomUp, intern_if_unbound_and_ground, Inserted), + occurrences_goal(BottomUp, intern_if_unbound, Finished), + conjoined([Lookups, Body0], Fast), + conjoined([Settled, Inserted, Body0, Finished], General). + +%! conjoined(+Goals, -Conjunction) the goals in order, `true` left out. + +conjoined(Goals, Conjunction) :- + goals_kept(Goals, Kept), + kept_conjoined(Kept, Conjunction). + +goals_kept([], []). +goals_kept([Goal | Goals], Kept) :- + ( Goal == true + -> Kept = Rest + ; Kept = [Goal | Rest] + ), + goals_kept(Goals, Rest). + +kept_conjoined([], true). +kept_conjoined([Goal], Goal) :- + !. +kept_conjoined([Goal | Goals], (Goal, Conjunction)) :- + kept_conjoined(Goals, Conjunction). + +top_level_occurrences([], _, []). +top_level_occurrences([Occurrence | Occurrences], All, TopLevel) :- + Occurrence = occurrence(_, _, Handle), + ( nested_in_another(Handle, All) + -> TopLevel = Rest + ; TopLevel = [Occurrence | Rest] + ), + top_level_occurrences(Occurrences, All, Rest). + +nested_in_another(Handle, [occurrence(Term, _, _) | Occurrences]) :- + ( term_variables(Term, Variables), + variable_member(Handle, Variables) + -> true + ; nested_in_another(Handle, Occurrences) + ). + +variable_member(Variable, [Candidate | Candidates]) :- + ( Variable == Candidate + -> true + ; variable_member(Variable, Candidates) + ). + +handles_bound([occurrence(_, _, Handle)], nonvar(Handle)) :- + !. +handles_bound([occurrence(_, _, Handle) | Occurrences], (nonvar(Handle), Condition)) :- + handles_bound(Occurrences, Condition). + +%! occurrences_goal(+Occurrences, +Step, -Goal) the conjunction of one step +% over the occurrences, in the order given. + +occurrences_goal([], _, true). +occurrences_goal([Occurrence], Step, Goal) :- + !, + occurrence_goal(Step, Occurrence, Goal). +occurrences_goal([Occurrence | Occurrences], Step, (Goal, Goals)) :- + occurrence_goal(Step, Occurrence, Goal), + occurrences_goal(Occurrences, Step, Goals). + +occurrence_goal(intern, occurrence(Term, Id, _), + hash_consing:intern(Term, Id)). +occurrence_goal(intern_if_bound, occurrence(Term, Id, Handle), + (nonvar(Handle) -> hash_consing:intern(Term, Id) ; true)). +occurrence_goal(intern_if_unbound, occurrence(Term, Id, Handle), + (var(Handle) -> hash_consing:intern(Term, Id) ; true)). +occurrence_goal(intern_if_unbound_and_ground, occurrence(Term, Id, Handle), + ((var(Handle), ground(Term)) -> hash_consing:intern(Term, Id) ; true)). +occurrence_goal(intern_if_ground, occurrence(Term, Id, _), + (ground(Term) -> hash_consing:intern(Term, Id) ; true)). + +%! body_rewritten(+Body0, +File, -Body) the control constructs rewritten +% inside, every other goal by `goal_rewritten/3`. + +body_rewritten(Goal, _, Goal) :- + var(Goal), + !. +body_rewritten((Left0, Right0), File, (Left, Right)) :- + !, + body_rewritten(Left0, File, Left), + body_rewritten(Right0, File, Right). +body_rewritten((Left0 ; Right0), File, (Left ; Right)) :- + !, + body_rewritten(Left0, File, Left), + body_rewritten(Right0, File, Right). +body_rewritten((Condition0 -> Then0), File, (Condition -> Then)) :- + !, + body_rewritten(Condition0, File, Condition), + body_rewritten(Then0, File, Then). +body_rewritten((Condition0 *-> Then0), File, (Condition *-> Then)) :- + !, + body_rewritten(Condition0, File, Condition), + body_rewritten(Then0, File, Then). +body_rewritten(\+ Goal0, File, \+ Goal) :- + !, + body_rewritten(Goal0, File, Goal). +body_rewritten(call(Goal0), File, call(Goal)) :- + !, + body_rewritten(Goal0, File, Goal). +body_rewritten(forall(Condition0, Action0), File, forall(Condition, Action)) :- + !, + body_rewritten(Condition0, File, Condition), + body_rewritten(Action0, File, Action). +body_rewritten(findall(Template, Goal0, Result), File, findall(Template, Goal, Result)) :- + !, + listed_absent(Template-Result, File, findall_template_or_result), + body_rewritten(Goal0, File, Goal). +body_rewritten(catch(Goal0, Catcher, Recovery0), File, catch(Goal, Catcher, Recovery)) :- + !, + listed_absent(Catcher, File, catch_catcher), + body_rewritten(Goal0, File, Goal), + body_rewritten(Recovery0, File, Recovery). +body_rewritten(Qualifier:Goal0, File, Qualifier:Goal) :- + !, + body_rewritten(Goal0, File, Goal). +body_rewritten(Goal0, File, Goal) :- + goal_rewritten(Goal0, File, Goal). + +%! goal_rewritten(+Goal0, +File, -Goal) the body goal row of THE REWRITE +% OF A CLAUSE (above). + +goal_rewritten(Goal0, File, Goal) :- + arguments_of_abstracted(Goal0, File, Called, BottomUp), + goal_scheduled(BottomUp, Called, Goal). + +goal_scheduled([], Called, Called) :- + !. +goal_scheduled(BottomUp, Called, (ground(Variables) -> Fast ; General)) :- + reverse(BottomUp, TopDown), + terms_variables(BottomUp, Variables), + occurrences_goal(BottomUp, intern, Inserts), + occurrences_goal(BottomUp, intern_if_ground, Settled), + occurrences_goal(TopDown, intern, Finished), + conjoined([Inserts, Called], Fast), + conjoined([Settled, Called, Finished], General). + +%! terms_variables(+Occurrences, -Variables) the variables of the +% occurrences' terms other than their own Handles. + +terms_variables(Occurrences, Variables) :- + occurrences_terms(Occurrences, Terms), + term_variables(Terms, All), + occurrences_handles(Occurrences, Handles), + variables_without(All, Handles, Variables). + +occurrences_terms([], []). +occurrences_terms([occurrence(Term, _, _) | Occurrences], [Term | Terms]) :- + occurrences_terms(Occurrences, Terms). + +occurrences_handles([], []). +occurrences_handles([occurrence(_, _, Handle) | Occurrences], [Handle | Handles]) :- + occurrences_handles(Occurrences, Handles). + +variables_without([], _, []). +variables_without([Variable | Variables], Excluded, Kept) :- + ( variable_member(Variable, Excluded) + -> Kept = Rest + ; Kept = [Variable | Rest] + ), + variables_without(Variables, Excluded, Rest). + +%! listed_absent(+Term, +File, +Place) no listed constructor occurs in +% Term, a place the rewrite does not schedule; raises otherwise. + +listed_absent(Term, File, Place) :- + abstracted(Term, File, _, [], Occurrences), + ( Occurrences == [] + -> true + ; throw(error(domain_error(term_without_rewritten_constructor, Term), + context(hash_consing:rewritten/1, Place))) + ). + +% ---- the hook, last, so that this file's own clauses are read before it +% is active ---- + +:- multifile user:term_expansion/2. +:- dynamic user:term_expansion/2. + +user:term_expansion(Source, Rewritten) :- + hash_consing:source_rewritten(Source, Rewritten). diff --git a/test/hash_consing_fixtures/inner_dispatch.pl b/test/hash_consing_fixtures/inner_dispatch.pl new file mode 100644 index 0000000..17e2327 --- /dev/null +++ b/test/hash_consing_fixtures/inner_dispatch.pl @@ -0,0 +1,47 @@ +% Fixture of test/hash_consing_rewrite.pl: forty clauses told apart by +% the INNER constructor of an application, enough for SWI-Prolog to build a +% deep index on the shape, the first argument of the Id. +:- module(inner_dispatch, [kind/2]). +:- use_module('../../prolog/hash_consing', []). +:- hash_consing:rewritten([apply(*, _), closure_00(_), closure_01(_), closure_02(_), closure_03(_), closure_04(_), closure_05(_), closure_06(_), closure_07(_), closure_08(_), closure_09(_), closure_10(_), closure_11(_), closure_12(_), closure_13(_), closure_14(_), closure_15(_), closure_16(_), closure_17(_), closure_18(_), closure_19(_), closure_20(_), closure_21(_), closure_22(_), closure_23(_), closure_24(_), closure_25(_), closure_26(_), closure_27(_), closure_28(_), closure_29(_), closure_30(_), closure_31(_), closure_32(_), closure_33(_), closure_34(_), closure_35(_), closure_36(_), closure_37(_), closure_38(_), closure_39(_)]). + +kind(apply(closure_00(_), _), closure_00). +kind(apply(closure_01(_), _), closure_01). +kind(apply(closure_02(_), _), closure_02). +kind(apply(closure_03(_), _), closure_03). +kind(apply(closure_04(_), _), closure_04). +kind(apply(closure_05(_), _), closure_05). +kind(apply(closure_06(_), _), closure_06). +kind(apply(closure_07(_), _), closure_07). +kind(apply(closure_08(_), _), closure_08). +kind(apply(closure_09(_), _), closure_09). +kind(apply(closure_10(_), _), closure_10). +kind(apply(closure_11(_), _), closure_11). +kind(apply(closure_12(_), _), closure_12). +kind(apply(closure_13(_), _), closure_13). +kind(apply(closure_14(_), _), closure_14). +kind(apply(closure_15(_), _), closure_15). +kind(apply(closure_16(_), _), closure_16). +kind(apply(closure_17(_), _), closure_17). +kind(apply(closure_18(_), _), closure_18). +kind(apply(closure_19(_), _), closure_19). +kind(apply(closure_20(_), _), closure_20). +kind(apply(closure_21(_), _), closure_21). +kind(apply(closure_22(_), _), closure_22). +kind(apply(closure_23(_), _), closure_23). +kind(apply(closure_24(_), _), closure_24). +kind(apply(closure_25(_), _), closure_25). +kind(apply(closure_26(_), _), closure_26). +kind(apply(closure_27(_), _), closure_27). +kind(apply(closure_28(_), _), closure_28). +kind(apply(closure_29(_), _), closure_29). +kind(apply(closure_30(_), _), closure_30). +kind(apply(closure_31(_), _), closure_31). +kind(apply(closure_32(_), _), closure_32). +kind(apply(closure_33(_), _), closure_33). +kind(apply(closure_34(_), _), closure_34). +kind(apply(closure_35(_), _), closure_35). +kind(apply(closure_36(_), _), closure_36). +kind(apply(closure_37(_), _), closure_37). +kind(apply(closure_38(_), _), closure_38). +kind(apply(closure_39(_), _), closure_39). diff --git a/test/hash_consing_fixtures/plain.pl b/test/hash_consing_fixtures/plain.pl new file mode 100644 index 0000000..d63249d --- /dev/null +++ b/test/hash_consing_fixtures/plain.pl @@ -0,0 +1,9 @@ +% Fixture of test/hash_consing_rewrite.pl: no constructor has a shape, +% so every Id records its root constructor only. +:- module(plain, [doubled/2, swapped/2]). +:- use_module('../../prolog/hash_consing', []). +:- hash_consing:rewritten([pair(_, _)]). + +doubled(X, pair(X, X)). + +swapped(pair(A, B), pair(B, A)). diff --git a/test/hash_consing_fixtures/reconfigured.pl b/test/hash_consing_fixtures/reconfigured.pl new file mode 100644 index 0000000..e1eaa35 --- /dev/null +++ b/test/hash_consing_fixtures/reconfigured.pl @@ -0,0 +1,8 @@ +% Fixture of test/hash_consing_rewrite.pl: a constructor declared +% twice with different templates, which raises while the file loads. +:- module(reconfigured, [first/1]). +:- use_module('../../prolog/hash_consing', []). +:- hash_consing:rewritten([apply(*, _)]). +:- hash_consing:rewritten([apply(*, *)]). + +first(apply(_, _)). diff --git a/test/hash_consing_fixtures/spines.pl b/test/hash_consing_fixtures/spines.pl new file mode 100644 index 0000000..8b24acc --- /dev/null +++ b/test/hash_consing_fixtures/spines.pl @@ -0,0 +1,14 @@ +% Fixture of test/hash_consing_rewrite.pl: a nested template, so that +% the shape of an application spells two layers of its first argument when +% that argument is an application too. +:- module(spines, [head/2, inner/2]). +:- use_module('../../prolog/hash_consing', []). +:- hash_consing:rewritten([apply(apply(*, _), _), lambda(_), variable(_), closure_a(_)]). + +% Determined: two layers of the first argument are in the pattern. +head(apply(apply(lambda(_), _), _), redex_under_an_application). +head(apply(apply(closure_a(_), _), _), compiled_redex_under_an_application). +% Determined: the template goes on only below an application. +head(apply(lambda(_), _), redex). +% Not determined: the inner application's own callee is unknown. +inner(apply(apply(Function, _), _), Function). diff --git a/test/hash_consing_fixtures/steps.pl b/test/hash_consing_fixtures/steps.pl new file mode 100644 index 0000000..4e2641f --- /dev/null +++ b/test/hash_consing_fixtures/steps.pl @@ -0,0 +1,22 @@ +% Fixture of test/hash_consing_rewrite.pl: clauses told apart by an +% inner constructor; the template apply(*, _) records the root constructor +% of an application's first argument. +:- module(steps, [step/2, callee/2, built/2, constant/1]). +:- use_module('../../prolog/hash_consing', []). +:- hash_consing:rewritten([apply(*, _), lambda(_), variable(_), closure_a(_), closure_b]). + +% The shape is determined: the atom goes into the head. +step(apply(lambda(Body), Argument), beta(Body, Argument)). +step(apply(closure_a(Capture), Argument), compiled(Capture, Argument)). +step(apply(closure_b, Argument), constant(Argument)). +step(apply(apply(Function, First), Second), spine(Function, First, Second)). + +% The shape is not determined: the head keeps an unbound shape. +callee(apply(Function, _), Function). + +% A body goal that builds a shaped term. +built(Function, Applied) :- + Applied = apply(Function, variable(0)). + +% A ground occurrence is interned while the file loads. +constant(apply(lambda(variable(0)), closure_b)). diff --git a/test/hash_consing_rewrite.pl b/test/hash_consing_rewrite.pl new file mode 100644 index 0000000..829e707 --- /dev/null +++ b/test/hash_consing_rewrite.pl @@ -0,0 +1,298 @@ +#!/usr/bin/env swipl +% THE TEST OF THE HASH_CONSING LIBRARY: ONE PROCESS PER FIXTURE, launched +% by hash_consing_rewrite.sh as +% swipl -q --stack-limit=32m --table-space=32m \ +% hash_consing_rewrite.pl -- --fixture=Name +% It loads the fixture file of `hash_consing_fixtures/`, prints the +% clauses the load produced and the outcome of the fixture's +% queries, and hash_consing_rewrite.sh's output is compared with +% hash_consing_rewrite_baseline.txt. Failing it is a defect by definition: +% what a rewrite produces and how `intern/2` answers are fixed by the +% module comment of prolog/hash_consing.pl, not measured. +% +% A CLAUSE IS PRINTED WITH ITS BAKED IDS EXTERNALIZED, `baked(Term)` in +% place of the Id, because a handle is an address of this process and would +% make the baseline differ from run to run. An Id pattern whose handle is a +% variable is printed as it is, its shape atom included. +% +% AN ERROR WHILE LOADING IS PRINTED, not thrown: the fixtures that must be +% refused raise inside term expansion, which SWI-Prolog reports as a +% message and does not propagate, so a message hook records the formal +% term of each error, an absolute file name in it cut down to its base +% name, and the warning that a directive failed. +% +% This file does not opt in; it reaches Ids through the library's +% boundary predicates. The in-process budget is ONE SECOND. + +:- use_module('../prolog/hash_consing', [intern/2, externalized/2, internalized/3]). +:- use_module(library(main), [argv_options/3]). +:- use_module(library(time), [call_with_time_limit/2]). +:- use_module(library(aggregate), [aggregate_all/3]). +:- initialization(main, main). + +:- dynamic load_error/1. + +:- multifile user:message_hook/3. +user:message_hook(error(Formal, _), error, _) :- + loading_fixture, + assertz(load_error(Formal)). +user:message_hook(goal_failed(directive, _), warning, _) :- + loading_fixture, + assertz(load_error(directive_failed)). + +:- dynamic loading/0. + +loading_fixture :- + loading. + +gate_time_limit(1). + +main :- + current_prolog_flag(argv, Arguments), + argv_options(Arguments, _, Options), + ( memberchk(fixture(Name), Options) + -> true + ; throw(error(existence_error(option, fixture), _)) + ), + fixture(Name, File, Module, Predicates, Queries), + format('fixture(~q)~n', [Name]), + fixture_loaded(File), + forall(member(Predicate, Predicates), + predicate_printed(Module, Predicate)), + forall(member(query(QueryName, Goal), Queries), + query_printed(QueryName, Goal)). + +fixture_loaded(File) :- + assertz(loading), + catch(load_files(File, [if(true)]), Error, assertz(load_error(thrown(Error)))), + retractall(loading), + forall(load_error(Formal0), + \+ \+ ( paths_shortened(Formal0, Formal), + numbervars(Formal, 0, _), + format('load_error(~W)~n', [Formal, [quoted(true), numbervars(true)]]) + )). + +%! paths_shortened(+Term, -Shortened) every absolute file name in Term as +% its base name, so that the output does not depend on where the +% repository is checked out. + +paths_shortened(Term, Term) :- + var(Term), + !. +paths_shortened(Term, Shortened) :- + atom(Term), + is_absolute_file_name(Term), + !, + file_base_name(Term, Shortened). +paths_shortened(Term, Shortened) :- + compound(Term), + !, + compound_name_arguments(Term, Name, Arguments), + arguments_paths_shortened(Arguments, ShortenedArguments), + compound_name_arguments(Shortened, Name, ShortenedArguments). +paths_shortened(Term, Term). + +arguments_paths_shortened([], []). +arguments_paths_shortened([Argument | Arguments], [Shortened | Shorteneds]) :- + paths_shortened(Argument, Shortened), + arguments_paths_shortened(Arguments, Shorteneds). + +%! predicate_printed(+Module, +Name/Arity) the clauses as loaded. + +predicate_printed(Module, Name/Arity) :- + functor(Head, Name, Arity), + format('predicate(~q)~n', [Name/Arity]), + forall(clause(Module:Head, Body), + ( baked_externalized((Head :- Body), Printed), + portray_clause(Printed) + )). + +baked_externalized(Term, Printed) :- + var(Term), + !, + Printed = Term. +baked_externalized(Term, Printed) :- + compound(Term), + compound_name_arity(Term, Name, Arity), + sub_atom(Name, 0, _, _, '__hash_consed_'), + arg(Arity, Term, Handle), + nonvar(Handle), + !, + externalized(Term, External), + Printed = baked(External). +baked_externalized(Term, Printed) :- + compound(Term), + !, + compound_name_arguments(Term, Name, Arguments), + arguments_baked_externalized(Arguments, PrintedArguments), + compound_name_arguments(Printed, Name, PrintedArguments). +baked_externalized(Term, Term). + +arguments_baked_externalized([], []). +arguments_baked_externalized([Argument | Arguments], [Printed | Printeds]) :- + baked_externalized(Argument, Printed), + arguments_baked_externalized(Arguments, Printeds). + +%! query_printed(+Name, +Goal) `query(Name, true)`, `query(Name, false)`, +% or `query(Name, error(Formal))`. + +query_printed(Name, Goal) :- + gate_time_limit(Limit), + catch(( call_with_time_limit(Limit, Goal) + -> Outcome = true + ; Outcome = false + ), + Error, + error_outcome(Error, Outcome)), + format('query(~q, ~q)~n', [Name, Outcome]). + +error_outcome(error(Formal, _), error(Formal)) :- !. +error_outcome(Error, thrown(Error)). + +% ---- the queries' helpers ---- + +store_count(Count) :- + nb_getval(hash_consing_store, Trie), + trie_property(Trie, value_count(Count)). + +%! spelling_count(-Count) how many shape atoms the library has spelled. +spelling_count(Count) :- + nb_getval(hash_consing_spellings, Trie), + trie_property(Trie, value_count(Count)). + +%! check_inserts_nothing(+Term, +Id) `intern(Term, Id)` with both bound +% leaves the store's count as it was. +check_inserts_nothing(Term, Id) :- + store_count(Before), + ( intern(Term, Id) + -> Answered = true + ; Answered = false + ), + store_count(After), + Before =:= After, + Answered == false. + +%! shape_indexed(+Head) the just in time indexer built an index on the +% first argument of the first argument, which is the shape. +shape_indexed(Head) :- + predicate_property(Head, indexed(Indexes)), + member(Index, Indexes), + get_dict(arguments, Index, [1]), + get_dict(position, Index, [1]), + get_dict(realised, Index, true), + !. + +called_repeatedly(Goal) :- + forall(between(1, 20, _), ( call(Goal) -> true ; true )). + +% ---- the fixtures ---- + +calculus([apply(*, _), lambda(_), variable(_), closure_a(_), closure_b]). +deep_calculus([apply(apply(*, _), _), lambda(_), variable(_), closure_a(_)]). + +fixture(steps, 'hash_consing_fixtures/steps.pl', steps, + [step/2, callee/2, built/2, constant/1], + [ query(shape_of_an_id, + ( calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + T = '__hash_consed_apply/2'(Shape, _), Shape == 'lambda/1' )), + query(shape_of_a_zero_arity_callee, + ( calculus(L), internalized(L, apply(closure_b, variable(1)), T), + T = '__hash_consed_apply/2'(Shape, _), Shape == 'closure_b/0' )), + query(dispatch_lambda, + ( calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + steps:step(T, R), externalized(R, E), E == beta(variable(0), variable(1)) )), + query(dispatch_closure, + ( calculus(L), internalized(L, apply(closure_a(variable(7)), closure_b), T), + steps:step(T, R), externalized(R, E), E == compiled(variable(7), closure_b) )), + query(dispatch_zero_arity, + ( calculus(L), internalized(L, apply(closure_b, variable(3)), T), + steps:step(T, R), externalized(R, E), E == constant(variable(3)) )), + query(dispatch_spine, + ( calculus(L), internalized(L, apply(apply(closure_b, variable(1)), variable(2)), T), + steps:step(T, R), externalized(R, E), + E == spine(closure_b, variable(1), variable(2)) )), + query(one_answer_per_term, + ( calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + aggregate_all(count, steps:step(T, _), Count), Count == 1 )), + query(partial_pattern_matches_every_shape, + ( calculus(L), internalized(L, apply(closure_a(variable(7)), closure_b), T), + steps:callee(T, F), externalized(F, E), E == closure_a(variable(7)) )), + query(body_goal_builds_the_shape, + ( calculus(L), internalized(L, lambda(variable(0)), F), + steps:built(F, B), B = '__hash_consed_apply/2'(Shape, _), Shape == 'lambda/1', + internalized(L, apply(lambda(variable(0)), variable(0)), T), B == T )), + query(ground_occurrence_baked, + ( steps:constant(C), externalized(C, E), E == apply(lambda(variable(0)), closure_b), + calculus(L), internalized(L, E, T), C == T )), + query(same_content_same_id, + ( intern(variable(5), V), intern(lambda(V), F), + intern(apply(F, V), First), intern(apply(F, V), Second), First == Second )), + query(backward, + ( intern(variable(6), V), intern(lambda(V), F), intern(apply(F, V), Id), + intern(Term, Id), Term == apply(F, V) )), + query(wrong_shape_does_not_unify, + ( calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + \+ T = '__hash_consed_apply/2'('closure_a/1', _) )), + query(spelling_remembered_once, + ( intern(variable(8), V), intern(closure_a(V), F), + spelling_count(Before), + intern(apply(F, V), _), spelling_count(Middle), + intern(variable(9), W), intern(closure_a(W), G), intern(apply(G, W), _), + spelling_count(After), + Middle >= Before, After =:= Middle )), + query(argument_that_is_no_id, + ( intern(apply(3, 4), Id), Id = '__hash_consed_apply/2'(Shape, _), Shape == '-' )), + query(unground_term_raises, + intern(apply(_, _), _) ), + query(externalized_internalized_inverse, + ( calculus(L), External = f(apply(lambda(variable(0)), apply(closure_b, closure_b)), [variable(1)]), + internalized(L, External, Internal), externalized(Internal, Back), Back == External )) + ]). +fixture(spines, 'hash_consing_fixtures/spines.pl', spines, + [head/2, inner/2], + [ query(two_layers_in_the_shape, + ( deep_calculus(L), + internalized(L, apply(apply(lambda(variable(0)), variable(1)), variable(2)), T), + T = '__hash_consed_apply/2'(Shape, _), Shape == 'apply/2(lambda/1)' )), + query(template_ends_the_shape, + ( deep_calculus(L), + internalized(L, apply(apply(apply(lambda(variable(0)), variable(1)), variable(2)), variable(3)), T), + T = '__hash_consed_apply/2'(Shape, _), Shape == 'apply/2(apply/2)' )), + query(dispatch_two_layers, + ( deep_calculus(L), + internalized(L, apply(apply(closure_a(variable(0)), variable(1)), variable(2)), T), + findall(K, spines:head(T, K), Ks), Ks == [compiled_redex_under_an_application] )), + query(dispatch_one_layer, + ( deep_calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + findall(K, spines:head(T, K), Ks), Ks == [redex] )), + query(partial_pattern_still_right, + ( deep_calculus(L), + internalized(L, apply(apply(closure_a(variable(0)), variable(1)), variable(2)), T), + spines:inner(T, F), externalized(F, E), E == closure_a(variable(0)) )), + query(partial_pattern_rejects_a_redex, + ( deep_calculus(L), internalized(L, apply(lambda(variable(0)), variable(1)), T), + \+ spines:inner(T, _) )) + ]). +fixture(plain, 'hash_consing_fixtures/plain.pl', plain, + [doubled/2, swapped/2], + [ query(upsert_then_externalize, + ( plain:doubled(a, D), externalized(D, E), E == pair(a, a) )), + query(same_content_same_id, + ( plain:doubled(a, D), plain:swapped(D, S), D == S )), + query(value_that_is_no_id_fails, + plain:doubled(_, foo) ), + query(uninterned_instance_fails, + plain:doubled(_, pair(a, a)) ), + query(both_sides_unknown_raises, + plain:swapped(_, _) ) + ]). +fixture(inner_dispatch, 'hash_consing_fixtures/inner_dispatch.pl', inner_dispatch, [], + [ query(dispatch_by_inner_constructor, + ( internalized([apply(*, _), closure_39(_)], apply(closure_39(x), y), T), + findall(K, inner_dispatch:kind(T, K), Ks), Ks == [closure_39] )), + query(shape_indexed, + ( internalized([apply(*, _), closure_39(_)], apply(closure_39(x), y), T), + called_repeatedly(inner_dispatch:kind(T, _)), + shape_indexed(inner_dispatch:kind(_, _)) )) + ]). +fixture(reconfigured, 'hash_consing_fixtures/reconfigured.pl', reconfigured, [], []). diff --git a/test/hash_consing_rewrite.sh b/test/hash_consing_rewrite.sh new file mode 100755 index 0000000..2f9c241 --- /dev/null +++ b/test/hash_consing_rewrite.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# The test of the hash_consing library: every +# fixture in its own process at the day-to-day budget, +# --stack-limit=32m --table-space=32m outside, call_with_time_limit(1) +# around each query inside, `timeout 20` around process startup. +# +# Usage: ./hash_consing_rewrite.sh | diff - hash_consing_rewrite_baseline.txt +# must print nothing. +SELF_DIRECTORY="$(cd "$(dirname "$0")" && pwd)" +cd "$SELF_DIRECTORY" || exit 1 +for FIXTURE in steps spines plain inner_dispatch reconfigured; do + LANG=C.UTF-8 LC_ALL=C.UTF-8 timeout 20 \ + swipl -q --stack-limit=32m --table-space=32m hash_consing_rewrite.pl -- --fixture="$FIXTURE" 2>&1 \ + || echo "fixture($FIXTURE, process_exit($?))" +done diff --git a/test/hash_consing_rewrite_baseline.txt b/test/hash_consing_rewrite_baseline.txt new file mode 100644 index 0000000..95de4c8 --- /dev/null +++ b/test/hash_consing_rewrite_baseline.txt @@ -0,0 +1,385 @@ +fixture(steps) +predicate(step/2) +step('__hash_consed_apply/2'('lambda/1', A), beta(B, C)) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), C), '__hash_consed_apply/2'('lambda/1', A)), + hash_consing:intern(lambda(B), '__hash_consed_lambda/1'(D)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ), + ( nonvar(D) + -> hash_consing:intern(lambda(B), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(D), + ground(lambda(B)) + -> hash_consing:intern(lambda(B), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_lambda/1'(D), C)) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ), + ( var(D) + -> hash_consing:intern(lambda(B), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ) + ). +step('__hash_consed_apply/2'('closure_a/1', A), compiled(B, C)) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), C), '__hash_consed_apply/2'('closure_a/1', A)), + hash_consing:intern(closure_a(B), '__hash_consed_closure_a/1'(D)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), C), '__hash_consed_apply/2'('closure_a/1', A)) + ; true + ), + ( nonvar(D) + -> hash_consing:intern(closure_a(B), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(D), + ground(closure_a(B)) + -> hash_consing:intern(closure_a(B), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_closure_a/1'(D), C)) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), C), '__hash_consed_apply/2'('closure_a/1', A)) + ; true + ), + ( var(D) + -> hash_consing:intern(closure_a(B), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), C), '__hash_consed_apply/2'('closure_a/1', A)) + ; true + ) + ). +step('__hash_consed_apply/2'('closure_b/0', A), constant(B)) :- + ( nonvar(A) + -> hash_consing:intern(apply(baked(closure_b), B), '__hash_consed_apply/2'('closure_b/0', A)) + ; ( nonvar(A) + -> hash_consing:intern(apply(baked(closure_b), B), '__hash_consed_apply/2'('closure_b/0', A)) + ; true + ), + ( var(A), + ground(apply(baked(closure_b), B)) + -> hash_consing:intern(apply(baked(closure_b), B), '__hash_consed_apply/2'('closure_b/0', A)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply(baked(closure_b), B), '__hash_consed_apply/2'('closure_b/0', A)) + ; true + ) + ). +step('__hash_consed_apply/2'('apply/2', A), spine(B, C, D)) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'(E, F), D), '__hash_consed_apply/2'('apply/2', A)), + hash_consing:intern(apply(B, C), '__hash_consed_apply/2'(E, F)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'(E, F), D), '__hash_consed_apply/2'('apply/2', A)) + ; true + ), + ( nonvar(F) + -> hash_consing:intern(apply(B, C), '__hash_consed_apply/2'(E, F)) + ; true + ), + ( var(F), + ground(apply(B, C)) + -> hash_consing:intern(apply(B, C), '__hash_consed_apply/2'(E, F)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_apply/2'(E, F), D)) + -> hash_consing:intern(apply('__hash_consed_apply/2'(E, F), D), '__hash_consed_apply/2'('apply/2', A)) + ; true + ), + ( var(F) + -> hash_consing:intern(apply(B, C), '__hash_consed_apply/2'(E, F)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'(E, F), D), '__hash_consed_apply/2'('apply/2', A)) + ; true + ) + ). +predicate(callee/2) +callee('__hash_consed_apply/2'(A, B), C) :- + ( nonvar(B) + -> hash_consing:intern(apply(C, D), '__hash_consed_apply/2'(A, B)) + ; ( nonvar(B) + -> hash_consing:intern(apply(C, D), '__hash_consed_apply/2'(A, B)) + ; true + ), + ( var(B), + ground(apply(C, D)) + -> hash_consing:intern(apply(C, D), '__hash_consed_apply/2'(A, B)) + ; true + ), + ( var(B) + -> hash_consing:intern(apply(C, D), '__hash_consed_apply/2'(A, B)) + ; true + ) + ). +predicate(built/2) +built(A, B) :- + ( ground([A]) + -> hash_consing:intern(apply(A, baked(variable(0))), '__hash_consed_apply/2'(C, D)), + B='__hash_consed_apply/2'(C, D) + ; ( ground(apply(A, baked(variable(0)))) + -> hash_consing:intern(apply(A, baked(variable(0))), '__hash_consed_apply/2'(C, D)) + ; true + ), + B='__hash_consed_apply/2'(C, D), + hash_consing:intern(apply(A, baked(variable(0))), '__hash_consed_apply/2'(C, D)) + ). +predicate(constant/1) +constant(baked(apply(lambda(variable(0)), closure_b))). +query(shape_of_an_id, true) +query(shape_of_a_zero_arity_callee, true) +query(dispatch_lambda, true) +query(dispatch_closure, true) +query(dispatch_zero_arity, true) +query(dispatch_spine, true) +query(one_answer_per_term, true) +query(partial_pattern_matches_every_shape, true) +query(body_goal_builds_the_shape, true) +query(ground_occurrence_baked, true) +query(same_content_same_id, true) +query(backward, true) +query(wrong_shape_does_not_unify, true) +query(spelling_remembered_once, true) +query(argument_that_is_no_id, true) +query(unground_term_raises, error(instantiation_error)) +query(externalized_internalized_inverse, true) +fixture(spines) +predicate(head/2) +head('__hash_consed_apply/2'('apply/2(lambda/1)', A), redex_under_an_application) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('lambda/1', B), C), '__hash_consed_apply/2'('apply/2(lambda/1)', A)), + hash_consing:intern(apply('__hash_consed_lambda/1'(D), E), '__hash_consed_apply/2'('lambda/1', B)), + hash_consing:intern(lambda(F), '__hash_consed_lambda/1'(D)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('lambda/1', B), C), '__hash_consed_apply/2'('apply/2(lambda/1)', A)) + ; true + ), + ( nonvar(B) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), E), '__hash_consed_apply/2'('lambda/1', B)) + ; true + ), + ( nonvar(D) + -> hash_consing:intern(lambda(F), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(D), + ground(lambda(F)) + -> hash_consing:intern(lambda(F), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(B), + ground(apply('__hash_consed_lambda/1'(D), E)) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), E), '__hash_consed_apply/2'('lambda/1', B)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_apply/2'('lambda/1', B), C)) + -> hash_consing:intern(apply('__hash_consed_apply/2'('lambda/1', B), C), '__hash_consed_apply/2'('apply/2(lambda/1)', A)) + ; true + ), + ( var(D) + -> hash_consing:intern(lambda(F), '__hash_consed_lambda/1'(D)) + ; true + ), + ( var(B) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(D), E), '__hash_consed_apply/2'('lambda/1', B)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('lambda/1', B), C), '__hash_consed_apply/2'('apply/2(lambda/1)', A)) + ; true + ) + ). +head('__hash_consed_apply/2'('apply/2(closure_a/1)', A), compiled_redex_under_an_application) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('closure_a/1', B), C), '__hash_consed_apply/2'('apply/2(closure_a/1)', A)), + hash_consing:intern(apply('__hash_consed_closure_a/1'(D), E), '__hash_consed_apply/2'('closure_a/1', B)), + hash_consing:intern(closure_a(F), '__hash_consed_closure_a/1'(D)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('closure_a/1', B), C), '__hash_consed_apply/2'('apply/2(closure_a/1)', A)) + ; true + ), + ( nonvar(B) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), E), '__hash_consed_apply/2'('closure_a/1', B)) + ; true + ), + ( nonvar(D) + -> hash_consing:intern(closure_a(F), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(D), + ground(closure_a(F)) + -> hash_consing:intern(closure_a(F), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(B), + ground(apply('__hash_consed_closure_a/1'(D), E)) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), E), '__hash_consed_apply/2'('closure_a/1', B)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_apply/2'('closure_a/1', B), C)) + -> hash_consing:intern(apply('__hash_consed_apply/2'('closure_a/1', B), C), '__hash_consed_apply/2'('apply/2(closure_a/1)', A)) + ; true + ), + ( var(D) + -> hash_consing:intern(closure_a(F), '__hash_consed_closure_a/1'(D)) + ; true + ), + ( var(B) + -> hash_consing:intern(apply('__hash_consed_closure_a/1'(D), E), '__hash_consed_apply/2'('closure_a/1', B)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_apply/2'('closure_a/1', B), C), '__hash_consed_apply/2'('apply/2(closure_a/1)', A)) + ; true + ) + ). +head('__hash_consed_apply/2'('lambda/1', A), redex) :- + ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(B), C), '__hash_consed_apply/2'('lambda/1', A)), + hash_consing:intern(lambda(D), '__hash_consed_lambda/1'(B)) + ; ( nonvar(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(B), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ), + ( nonvar(B) + -> hash_consing:intern(lambda(D), '__hash_consed_lambda/1'(B)) + ; true + ), + ( var(B), + ground(lambda(D)) + -> hash_consing:intern(lambda(D), '__hash_consed_lambda/1'(B)) + ; true + ), + ( var(A), + ground(apply('__hash_consed_lambda/1'(B), C)) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(B), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ), + ( var(B) + -> hash_consing:intern(lambda(D), '__hash_consed_lambda/1'(B)) + ; true + ), + ( var(A) + -> hash_consing:intern(apply('__hash_consed_lambda/1'(B), C), '__hash_consed_apply/2'('lambda/1', A)) + ; true + ) + ). +predicate(inner/2) +inner('__hash_consed_apply/2'(A, B), C) :- + ( nonvar(B) + -> hash_consing:intern(apply('__hash_consed_apply/2'(D, E), F), '__hash_consed_apply/2'(A, B)), + hash_consing:intern(apply(C, G), '__hash_consed_apply/2'(D, E)) + ; ( nonvar(B) + -> hash_consing:intern(apply('__hash_consed_apply/2'(D, E), F), '__hash_consed_apply/2'(A, B)) + ; true + ), + ( nonvar(E) + -> hash_consing:intern(apply(C, G), '__hash_consed_apply/2'(D, E)) + ; true + ), + ( var(E), + ground(apply(C, G)) + -> hash_consing:intern(apply(C, G), '__hash_consed_apply/2'(D, E)) + ; true + ), + ( var(B), + ground(apply('__hash_consed_apply/2'(D, E), F)) + -> hash_consing:intern(apply('__hash_consed_apply/2'(D, E), F), '__hash_consed_apply/2'(A, B)) + ; true + ), + ( var(E) + -> hash_consing:intern(apply(C, G), '__hash_consed_apply/2'(D, E)) + ; true + ), + ( var(B) + -> hash_consing:intern(apply('__hash_consed_apply/2'(D, E), F), '__hash_consed_apply/2'(A, B)) + ; true + ) + ). +query(two_layers_in_the_shape, true) +query(template_ends_the_shape, true) +query(dispatch_two_layers, true) +query(dispatch_one_layer, true) +query(partial_pattern_still_right, true) +query(partial_pattern_rejects_a_redex, true) +fixture(plain) +predicate(doubled/2) +doubled(A, '__hash_consed_pair/2'(B)) :- + ( nonvar(B) + -> hash_consing:intern(pair(A, A), '__hash_consed_pair/2'(B)) + ; ( nonvar(B) + -> hash_consing:intern(pair(A, A), '__hash_consed_pair/2'(B)) + ; true + ), + ( var(B), + ground(pair(A, A)) + -> hash_consing:intern(pair(A, A), '__hash_consed_pair/2'(B)) + ; true + ), + ( var(B) + -> hash_consing:intern(pair(A, A), '__hash_consed_pair/2'(B)) + ; true + ) + ). +predicate(swapped/2) +swapped('__hash_consed_pair/2'(A), '__hash_consed_pair/2'(B)) :- + ( nonvar(A), + nonvar(B) + -> hash_consing:intern(pair(C, D), '__hash_consed_pair/2'(B)), + hash_consing:intern(pair(D, C), '__hash_consed_pair/2'(A)) + ; ( nonvar(B) + -> hash_consing:intern(pair(C, D), '__hash_consed_pair/2'(B)) + ; true + ), + ( nonvar(A) + -> hash_consing:intern(pair(D, C), '__hash_consed_pair/2'(A)) + ; true + ), + ( var(A), + ground(pair(D, C)) + -> hash_consing:intern(pair(D, C), '__hash_consed_pair/2'(A)) + ; true + ), + ( var(B), + ground(pair(C, D)) + -> hash_consing:intern(pair(C, D), '__hash_consed_pair/2'(B)) + ; true + ), + ( var(A) + -> hash_consing:intern(pair(D, C), '__hash_consed_pair/2'(A)) + ; true + ), + ( var(B) + -> hash_consing:intern(pair(C, D), '__hash_consed_pair/2'(B)) + ; true + ) + ). +query(upsert_then_externalize, true) +query(same_content_same_id, true) +query(value_that_is_no_id_fails, false) +query(uninterned_instance_fails, false) +query(both_sides_unknown_raises, error(instantiation_error)) +fixture(inner_dispatch) +query(dispatch_by_inner_constructor, true) +query(shape_indexed, true) +fixture(reconfigured) +load_error(permission_error(reconfigure,interned_constructor,apply/2)) +load_error(directive_failed)