..
   This file is part of Logtalk <https://logtalk.org/>
   SPDX-FileCopyrightText: 1998-2025 Paulo Moura <pmoura@logtalk.org>
   SPDX-License-Identifier: Apache-2.0

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


.. _protocols_protocols:

Protocols
=========

Protocols enable the separation between interface and implementation:
several objects can implement the same protocol, and an object can
implement several protocols. Protocols may contain only predicate
declarations. In some languages the term *interface* is used with
a similar meaning. Logtalk allows predicate declarations of any scope
within protocols, contrary to some languages that only allow public
declarations.

Logtalk defines three built-in protocols,
:ref:`monitoring <apis:monitoring/0>`,
:ref:`expanding <apis:expanding/0>`, and
:ref:`forwarding <apis:forwarding/0>`, which are described at the
end of this section.

.. _protocols_defining:

Defining a new protocol
-----------------------

We can define a new protocol in the same way we write Prolog code: by
using a text editor. Logtalk source files may contain one or more
objects, categories, or protocols. If you prefer to define each entity
in its own source file, it is recommended that the file be named after
the protocol. By default, all Logtalk source files use the extension
``.lgt`` but this is optional and can be set in the adapter files.
Intermediate Prolog source files (generated by the Logtalk compiler)
have, by default, a ``_lgt`` suffix and a ``.pl`` extension. Again, this
can be set to match the needs of a particular Prolog compiler in the
corresponding adapter file. For example, we may define a protocol named
``listp`` and save it in a ``listp.lgt`` source file that will be
compiled to a ``listp_lgt.pl`` Prolog file (depending on the backend
compiler, the names of the intermediate Prolog files may include a
directory hash and a process identifier to prevent file name clashes
when embedding Logtalk applications or running parallel Logtalk processes).

Protocol names must be atoms. Objects, categories, and protocols share
the same namespace: we cannot have a protocol with the same name as an
object or a category.

Protocol directives are textually encapsulated by using two Logtalk
directives: :ref:`directives_protocol_1_2` and
:ref:`directives_end_protocol_0`. The
most simple protocol will be one that is self-contained, not depending
on any other Logtalk entity:

::

   :- protocol(Protocol).
       ...
   :- end_protocol.

If a protocol extends one or more protocols, then the opening directive
will be:

::

   :- protocol(Protocol,
       extends([Protocol1, Protocol2, ...])).
       ...
   :- end_protocol.

In order to maximize protocol reuse, all predicates specified in a
protocol should relate to the same functionality. Therefore, the only
recommended use of protocol extension is when you need both a minimal
protocol and an extended version of the same protocol with additional,
convenient predicates.

.. _protocols_finding:

Finding defined protocols
-------------------------

We can find, by backtracking, all defined protocols by using the
:ref:`predicates_current_protocol_1` built-in predicate with a
unbound argument:

.. code-block:: text

   | ?- current_protocol(Protocol).

This predicate can also be used to test if a protocol is defined by
calling it with a valid protocol identifier (an atom).

.. _protocols_creating:

Creating a new protocol at runtime
----------------------------------

We can create a new (dynamic) protocol at runtime by calling the Logtalk
built-in predicate :ref:`predicates_create_protocol_3`:

.. code-block:: text

   | ?- create_protocol(Protocol, Relations, Directives).

The first argument should be either a variable or the name of the new
protocol (a Prolog atom, which must not match an existing entity name).
The remaining two arguments correspond to the relations described in the
opening protocol directive and to the protocol directives.

For instance, the call:

.. code-block:: text

   | ?- create_protocol(ppp, [extends(qqq)], [public([foo/1, bar/1])]).

is equivalent to compiling and loading the protocol:

::

   :- protocol(ppp,
       extends(qqq)).

       :- dynamic.

       :- public([foo/1, bar/1]).

   :- end_protocol.

If we need to create a lot of (dynamic) protocols at runtime, then it
is best to define a metaclass or a prototype with a predicate that will
call this built-in predicate in order to provide more sophisticated
behavior.

.. _protocols_abolishing:

Abolishing an existing protocol
-------------------------------

Dynamic protocols can be abolished using the
:ref:`predicates_abolish_protocol_1` built-in predicate:

.. code-block:: text

   | ?- abolish_protocol(Protocol).

The argument must be an identifier of a defined dynamic protocol;
otherwise an error will be thrown.

Protocol directives
-------------------

Protocol directives are used to define protocol properties and
documentation.

.. _protocols_dynamic:

Dynamic protocols
~~~~~~~~~~~~~~~~~

As usually happens with Prolog code, a protocol can be either static or
dynamic. A protocol created during the execution of a program is always
dynamic. A protocol defined in a file can be either dynamic or static.
Dynamic protocols are declared by using the
:ref:`directives_dynamic_0` directive in the protocol source code:

::

   :- dynamic.

The directive must precede any predicate directives. Please be aware
that using dynamic code results in a performance hit when compared to
static code. We should only use dynamic protocols when these need to be
abolished during program execution.

.. _protocols_documentation:

Protocol documentation
~~~~~~~~~~~~~~~~~~~~~~

A protocol can be documented with arbitrary user-defined information
by using the :ref:`directives_info_1` entity directive. See the
:ref:`documenting_documenting` section for details.

.. _protocols_include:

Loading files into a protocol
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The :ref:`directives_include_1` directive
can be used to load the contents of a file into a protocol. See the
:ref:`objects_objects` section for an example of using this
directive.

.. _protocols_relationships:

Protocol relationships
----------------------

Logtalk provides two sets of built-in predicates that enable us to query
the system about the relationships that a protocol has with other entities.

The :ref:`predicates_extends_protocol_2_3` built-in predicates return all
pairs of protocols so that the first one extends the second:

.. code-block:: text

   | ?- extends_protocol(Protocol1, Protocol2).

or, if we also want to know the extension scope:

.. code-block:: text

   | ?- extends_protocol(Protocol1, Protocol2, Scope).

To find which objects or categories implement which protocols, we can
call the :ref:`predicates_implements_protocol_2_3` built-in predicates:

.. code-block:: text

   | ?- implements_protocol(ObjectOrCategory, Protocol).

or, if we also want to know the implementation scope:

.. code-block:: text

   | ?- implements_protocol(ObjectOrCategory, Protocol, Scope).

Note that, if we use a non-instantiated variable for the first argument,
we will need to use the :ref:`predicates_current_object_1` or
:ref:`predicates_current_category_1`
built-in predicates to identify the kind of entity returned.

.. _protocols_properties:

Protocol properties
-------------------

We can find the properties of defined protocols by calling the
:ref:`predicates_protocol_property_2` built-in predicate:

.. code-block:: text

   | ?- protocol_property(Protocol, Property).

A protocol may have the property ``static``, ``dynamic``, or
``built_in``. Dynamic protocols can be abolished in runtime by calling
the :ref:`predicates_abolish_protocol_1`
built-in predicate. Depending on the :term:`backend Prolog compiler`, a
protocol may have additional properties related to the source file where
it is defined.

The following protocol properties are supported:

``static``
   The protocol is static
``dynamic``
   The protocol is dynamic (and thus can be abolished in runtime by
   calling the :ref:`predicates_abolish_category_1` built-in predicate)
``built_in``
   The protocol is a built-in protocol (and thus always available)
``source_data``
   Source data available for the protocol
``file(Path)``
   Absolute path of the source file defining the protocol (if
   applicable)
``file(Basename, Directory)``
   Basename and directory of the source file defining the protocol (if
   applicable); ``Directory`` always ends with a ``/``
``lines(BeginLine, EndLine)``
   Source file begin and end lines of the protocol definition (if
   applicable)
``directive(BeginLine, EndLine)``
   Source file begin and end lines of the protocol opening directive (if
   applicable)
``public(Resources)``
   List of public predicates and operators declared by the protocol
``protected(Resources)``
   List of protected predicates and operators declared by the protocol
``private(Resources)``
   List of private predicates and operators declared by the protocol
``declares(Predicate, Properties)``
   List of :ref:`properties <grammar_entity_properties>` for a predicate declared by the protocol
``alias(Predicate, Properties)``
   List of :ref:`properties <grammar_entity_properties>` for a :term:`predicate alias` declared by the protocol
   (the properties include ``for(Original)``, ``from(Entity)``,
   ``non_terminal(NonTerminal)``, and ``line_count(Line)`` with ``Line``
   being the begin line of the alias directive)

Some of the properties, such as line numbers, are only available when the
protocol is defined in a source file compiled with the
:ref:`source_data <flag_source_data>` flag turned on.

.. _protocols_implementing:

Implementing protocols
----------------------

Any number of objects or categories can implement a protocol. The syntax
is very simple:

::

   :- object(Object,
       implements(Protocol)).
       ...
   :- end_object.

or, in the case of a category:

::

   :- category(Object,
       implements(Protocol)).
       ...
   :- end_category.

To make all public predicates declared via an implemented protocol
protected or to make all public and protected predicates private we
prefix the protocol's name with the corresponding keyword. For instance:

::

   :- object(Object,
       implements(private::Protocol)).
       ...
   :- end_object.

or:

::

   :- object(Object,
       implements(protected::Protocol)).
       ...
   :- end_object.

Omitting the scope keyword is equivalent to writing:

::

   :- object(Object,
       implements(public::Protocol)).
       ...
   :- end_object.

The same rules apply to protocols implemented by categories.

.. _protocols_built_in:

Built-in protocols
------------------

Logtalk defines a set of built-in protocols that are always available
for any application.

.. _protocols_expanding:

The built-in protocol ``expanding``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The built-in :ref:`expanding <apis:expanding/0>` protocol declares
the :ref:`methods_term_expansion_2` and :ref:`methods_goal_expansion_2`
predicates. See the description of the :ref:`hook <flag_hook>`
compiler flag for more details.

.. _protocols_monitoring:

The built-in protocol ``monitoring``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The built-in :ref:`monitoring <apis:monitoring/0>` protocol declares the
:ref:`methods_before_3` and :ref:`methods_after_3` public event handler
predicates. See the :ref:`events_events` section for more details.

.. _protocols_forwarding:

The built-in protocol ``forwarding``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The built-in :ref:`forwarding <apis:forwarding/0>` protocol declares the
:ref:`methods_forward_1` user-defined message forwarding handler, which
is automatically called (if defined) by the runtime for any message that
the receiving object does not understand. See also the
:ref:`control_delegate_message_1` control construct.

Multi-threading applications
----------------------------

When writing multi-threading applications, user-defined predicates calling
built-in predicates such as ``create_protocol/3`` and ``abolish_protocol/1``
may need to be declared synchronized in order to avoid race conditions.
