Logtalk user manual
Writing, running, and debugging programs

Writing, running, and debugging programs

Writing programs

For a successful programming in Logtalk, you need a good working knowledge of Prolog and an understanding of the principles of object-oriented programming. All guidelines for writing good Prolog code apply as well to Logtalk programming. To those guidelines, you should add the basics of good object-oriented design.

One of the advantages of a system like Logtalk is that it enable us to use the currently available object-oriented methodologies, tools, and metrics [Champaux 92] in Prolog programming. That said, writing programs in Logtalk is similar to writing programs in Prolog: we define new predicates describing what is true about our domain objects, about our problem solution. We encapsulate our predicate directives and definitions inside new objects, categories and protocols that we create by hand with a text editor or by using the Logtalk built-in predicates. Some of the information collected during the analysis and design phases can be integrated in the objects, categories and protocols that we define by using the available entity and predicate documenting directives.

Source files

Logtalk source files may contain any number of objects, categories, protocols, and plain Prolog code. If you prefer to define each entity in its own source file, then it is recommended that the source file be named after the entity identifier. For parametric objects, the identifier arity can be appended to the identifier functor. By default, all Logtalk source files use the extension .lgt but this is optional and can be set in the configuration files. Intermediate Prolog source files (generated by the Logtalk compiler) have, by default, a .pl extension. Again, this can be set to match the needs of a particular Prolog compiler in the corresponding configuration file. For example, we may define an object named vehicle and save it in a vehicle.lgt source file that will be compiled to a vehicle.pl Prolog file. If we have a sort(_) parametric object we can save it on a sort_1.lgt source file that will be compiled to a sort_1.pl Prolog file. This name scheme helps avoid file name conflicts (remember that all Logtalk entities share the same name space).

Logtalk source files may contain arbitrary Prolog directives and clauses interleaved with Logtalk entity definitions. These directives and clauses are be copied unchanged to the corresponding Prolog output file. This feature is included to help the integration of Logtalk with Prolog extensions such as, for example, constraint programming extensions. The following Prolog directives are processed when read (thus affecting the compilation of the source code that follows): ensure_loaded/1, op/3, and set_prolog_flag/2. The initialization/1 directive may be used for defining an initialization goal to be executed when loading a source file.

The text encoding used in a source file may be declared using the encoding/1 directive when running Logtalk with some back-end Prolog compilers that support multiple encodings (check the encoding_directive flag in the configuration file of your Prolog compiler). The encoding used (and, in the case of a Unicode encoding, any BOM present) in a source file will be used for the generated Prolog and XML files. Logtalk uses the encoding names specified by IANA (in those cases where a preferred MIME name alias is specified, the alias is used instead).

Portable programs

Logtalk is compatible with almost all modern Prolog compilers. However, this does not necessarily imply that your Logtalk programs will have the same level of portability. If possible, you should only use in your programs Logtalk built-in predicates and ISO Prolog specified built-in predicates and arithmetic functions. If you need to use built-in predicates (or built-in arithmetic functions) that may not be available in other Prolog compilers, you should try to encapsulate the non-portable code in a small number of objects and provide a portable interface for that code through the use of Logtalk protocols. An example will be code that access operating-system specific features. The Logtalk compiler can warn you of the use of non-ISO specified built-in predicates and arithmetic functions by using the portability/1 compiler flag.

Conditional compilation

Logtalk supports conditional compilation within source files using the if/1, elif/1, else/0, and endif/0 directives. This support is similar to the support found in some Prolog compilers such as ECLiPSe, SWI-Prolog, or YAP.

Avoiding common errors

Try to write objects and protocol documentation before writing any other code; if you are having trouble documenting a predicate perhaps we need to go back to the design stage.

Try to avoid lengthy hierarchies. Besides performance penalties, composition is often a better choice over inheritance for defining new objects (Logtalk supports component-based programming through the use of categories). In addition, prototype-based hierarchies are conceptually simpler and more efficient than class-based hierarchies.

Dynamic predicates or dynamic entities are sometimes needed, but we should always try to minimize the use of non-logical features like destructive assignment (asserts and retracts).

Since each Logtalk entity is independently compiled, if an object inherits a dynamic or a meta-predicate predicate, then we must repeat the respective directives in order to ensure a correct compilation.

In general, Logtalk does not verify if a user predicate call/return arguments comply with the declared modes. On the other hand, Logtalk built-in predicates, built-in methods, and message sending control structures are carefully checked for calling mode errors.

Logtalk error handling strongly depends on the ISO compliance of the chosen Prolog compiler. For instance, the error terms that are generated by some Logtalk built-in predicates assume that the Prolog built-in predicates behave as defined in the ISO standard regarding error conditions. In particular, if your Prolog compiler does not support a read_term/3 built-in predicate compliant with the ISO Prolog Standard definition, then the current version of the Logtalk compiler may not be able to detect misspell variables in your source code.

Coding style guidelines

It is suggested that all code between an entity opening and closing directives be indented by one tab stop. When defining entity code, both directives and predicates, Prolog coding style guidelines may be applied. All Logtalk source files, examples, and standard library entities use four-space tabs for laying out code. Closed related entities should be defined in the same source file. Entities that might be useful in different contexts (such as library entities) are best defined in their own source files.

Running a Logtalk session

We run Logtalk inside a normal Prolog session, after loading the necessary files. Logtalk extends but does not modify your Prolog compiler. We can freely mix Prolog queries with the sending of messages and our programs can be made of both normal Prolog clauses and object definitions.

Starting Logtalk

Depending on your Logtalk installation, you may use a script or a shortcut to start Logtalk with your chosen Prolog compiler. On POSIX operating systems, the scripts should be available from the command-line; scripts are named upon the used Prolog compilers. On Windows, the shortcuts should be available from the Start Menu. If no scripts or shortcuts are available for your installation, operating-system, or Prolog compiler, you can always start a Logtalk session by performing the following steps:

  1. Start your Prolog compiler.
  2. Load the appropriate configuration file for your compiler. Configuration files for most common Prolog compilers can be found in the configs subdirectory.
  3. Load the Logtalk compiler/runtime files contained in the compiler subdirectory.
  4. Load the library paths configuration file corresponding to your Logtalk installation contained in the libpaths subdirectory.

Note that the configuration files, compiler/runtime files, and library paths file are Prolog source files. The predicate called to load (and compile) them depends on your Prolog compiler. In case of doubt, consult your Prolog compiler reference manual or take a look at the definition of the predicate '$lgt_load_prolog_code'/3 in the corresponding configuration file.

Most Prolog compilers support automatic loading of an initialization file, which can include the necessary directives to load both the Prolog configuration file and the Logtalk compiler. This feature, when available, allows automatic loading of Logtalk when you start your Prolog compiler.

Compiling and loading your programs

Your programs will be made of source files containing your objects, protocols, and categories. After changing the Prolog working directory to the one containing your files, you can compile them to disk by calling the Logtalk built-in predicate logtalk_compile/1:

| ?- logtalk_compile([source_file1, source_file2, ...]).

This predicate runs the compiler on each argument file and, if no fatal errors are found, outputs Prolog source files that can then be consulted or compiled in the usual way by your Prolog compiler.

To compile to disk and also load into memory the source files we can use the Logtalk built-in predicate logtalk_load/1:

| ?- logtalk_load([source_file1, source_file2, ...]).

This predicate works in the same way of the predicate logtalk_compile/1 but also loads the compiled files to memory.

Both predicates expect a source name name or a list of source name names as an argument. The Logtalk source file name extension, as defined in the configuration file, must be omitted.

If you have more than a few source files then you may want to use a loader helper file containing the calls to the logtalk_load/1-2 predicates. Consulting or compiling the loader file will then compile and load all your Logtalk entities into memory (see below for details).

With most Prolog back-end compilers, you can use the shorthand {File} for logtalk_load(File). The use this shorthand should be restricted to the Logtak/Prolog top-level; do not use it from within source files.

Loader utility files

Most examples directories contain a Logtalk utility file that can be used to load all included source files. These loader utility files are usually named loader.lgt or contain the word "loader" in their name. Loader files are compiled and loaded like any ordinary Logtalk source file. For an example loader file named loader.lgt we would type:

| ?- logtalk_load(loader).

Usually these files contain a call to the Logtalk built-in predicates set_logtalk_flag/2 (e.g. for setting project-specific flag values) and logtalk_load/1 or logtalk_load/2 (for loading project files), wrapped inside an initialization/1 directive. For instance, if your code is split in three Logtalk source files named source1.lgt, source2.lgt, and source3.lgt, then the contents of your loader file could be:

:- initialization((
    set_logtalk_flag(events, allow),           % set project-specific flags
    logtalk_load([source1, source2, source3])  % load the project source files
    )).

Another example of directives that are often used in a loader file would be op/3 directives declaring global operators needed by your application. Loader files are also often used for setting source file-specific compiler options (this is useful even when you only have a single source file if you always load it with using the same set of compiler options). For example:

:- initialization((
    set_logtalk_flag(underscore_variables, dont_care),
    set_logtalk_flag(xmlspec, xsd),
    logtalk_load(
        [source1, source2, source3],
        [portability(warning)]),               % source file-specific flags
    logtalk_load(
        [source4, source5],
        [portability(silent)])                 % source file-specific flags
    )).

To take the best advantage of loader files, assert a clause to the dynamic predicate logtalk_library_path/2 for the directory containing your source files, as explained in the next section.

A common mistake is to try to set compiler options using logtalk_load/2 with a loader file. For example, by writing:

| ?- logtalk_load(loader, [xmlspec(xsd), xslfile('lgtxhtml.xsl')]).

This will not work as you might expect as the compiler options will only be used in the compilation of the loader.lgt file itself and will not affect the compilation of files loaded through the initialization/1 directive contained on the loader file.

Libraries of source files

Logtalk defines a library simply as a directory containing source files. Library locations can be specified by defining or asserting clauses for the dynamic and multifile predicate logtalk_library_path/2. For example:

| ?- assertz(logtalk_library_path(shapes, '$LOGTALKUSER/examples/shapes/')). 

The first argument of the predicate is used as an alias for the path on the second argument. Library aliases may also be used on the second argument. For example:

| ?- assertz(logtalk_library_path(lgtuser, '$LOGTALKUSER/')),
     assertz(logtalk_library_path(examples, lgtuser('examples/'))),
     assertz(logtalk_library_path(viewpoints, examples('viewpoints/'))).

This allows us to load a library source file without the need to first change the current working directory to the library directory and then back to the original directory. For example, in order to load a loader.lgt file, contained in a library named shapes, we just need to type:

| ?- logtalk_load(viewpoints(loader)). 

The best way to take advantage of this feature is to load at startup a source file containing an initialization/1 directive which asserts all the logtalk_library_path/2 clauses needed for all available libraries. This allows us to load library source files or entire libraries without worrying about libraries paths, improving code portability. The directory paths on the second argument must always end with the path directory separator character. Most back-end Prolog compilers allows the use of environment variables in the second argument of the logtalk_library_path/2 predicate. Use of POSIX relative paths (e.g. '../' or './') for top-level library directories (e.g. lgtuser in the example above) is not advised as different back-end Prolog compilers may start with different initial working directories, which may result in portability problems of your loader files.

Unfortunately, a few Prolog compilers do not support the <library>(<source file>) notation. In this case, you will need to set the working directory to be the one that contains the source file in order to load it. The library notation provides functionality similar to the file_search_path/2 mechanism introduced by Quintus Prolog and later adopted by some other Prolog compilers.

Compiler flags

The logtalk_load/1 and logtalk_compile/1 always use the current set of default compiler flags as specified in your settings file and the Logtalk configuration files or changed for the current session using the built-in predicate set_logtalk_flag/2. Although the default flag values cover the usual cases, you may want to use a different set of flag values while compiling or loading some of your Logtalk source files. This can be accomplished by using the logtalk_load/2 or the logtalk_compile/2 built-in predicates. These two predicates accept a list of flag values affecting how a Logtalk source file is compiled and loaded:

| ?- logtalk_compile(Files, Flags).

or:

| ?- logtalk_load(Files, Flags).

In fact, the logtalk_load/1 and logtalk_compile/1 predicates are just shortcuts to the extended versions called with the default compiler flag values.

We may also change the default flag values from the ones loaded from the config file by using the set_logtalk_flag/2 built-in predicate. For example:

| ?- set_logtalk_flag(xmldocs, off).

The current default flags values can be enumerated using the current_logtalk_flag/2 built-in predicate:

| ?- current_logtalk_flag(xmldocs, Value).

Value = off
yes

Logtalk also implements a set_logtalk_flag/2 directive, which can be used to set flags within a source file or within an entity. For example:

:- set_logtalk_flag(events, allow).                      % compile all objects in the source file with event support

:- object(foo).

    :- set_logtalk_flag(dynamic_declarations, allow).    % compile this object with support for dynamic predicate declarations
    ...

:- end_object.

...

Note that the scope of the set_logtalk_flag/2 directive is local to the entity or to the source file containing it.

Lint flags

unknown(Option)
Controls the unknown entity warnings, resulting from loading an entity that references some other entity that is not currently loaded. Possible option values are warning (the usual default) and silent. Note that these warnings are not always avoidable, specially when using reflective designs of class-based hierarchies.
misspelt(Option)
Controls the misspelt predicate call warnings. A misspelt call is a call to a predicate which is not defined in the object or category containing the call, is not declared as dynamic, and is not a Logtalk/Prolog built-in predicate. Possible option values are error, warning (the usual default), and silent (not recommended).
lgtredef(Option)
Controls the Logtalk built-in predicate redefinition warnings. Possible option values are warning (the usual default) and silent. These warnings are almost always programming errors.
plredef(Option)
Controls the Prolog built-in predicate redefinition warnings. Possible option values are warning (can be very verbose if your code redefines a lot of Prolog built-in predicates) and silent (the usual default). When running a Logtalk application on several Prolog compilers, is possible to get different sets of warnings due to different sets of built-in predicates implemented by each Prolog compiler.
portability(Option)
Controls the non-ISO specified built-in predicate and non-ISO specified built-in arithmetic function calls warnings. Possible option values are warning and silent (the usual default).
singletons(Option)
Controls the singleton variable warnings. Possible option values are warning (the usual default) and silent (not recommended).
underscore_variables(Option)
Controls the interpretation of variables that start with an underscore (excluding the anonymous variable) that occur once in a term as either don't care variables or singleton variables. Possible option values are dont_care and singletons (the usual default). Note that, depending on your Prolog compiler, the read_term/3 built-in predicate may report variables that start with an underscore as singleton variables. There is no standard behavior, hence this option.

Documenting flags

xmldocs(Option)
Controls the automatic generation of documenting files in XML format. Possible option values are on (the usual default) and off.
xmlspec(Option)
Defines the XML documenting files specification format. Possible option values are dtd (for the DTD specification; the usual default) and xsd (for the XML Schema specification). Most XSL processors support DTDs but only some of them support XML Schemas.
xmlsref(Option)
Sets the reference to the XML specification file in the automatically generated XML documenting files. The default value is local, that is, the reference points to a local DTD or XSD file (respectively, logtalk.dtd or logtalk.xsd), residing in the same directory as the XML file. Other possible values are web (the reference points to an web location, either http://logtalk.org/xml/1.3/logtalk.dtd or http://logtalk.org/xml/1.3/logtalk.xsd), and standalone (no reference to specification files in the XML documenting files). The most appropriated option value depends on the XSL processor you intend to use. Some of them are buggy an may not work with the default option value.
xslfile(File)
Sets the XSLT file to be used with the automatically generated XML documenting files. The default value is lgtxml.xsl, which allows the XML files to be viewed by simply opening them with recent versions of web navigators which support XSLT transformations (after copying the lgtxml.xsl and of the logtalk.css files to the directory containing the XML files).

Directories compilation flags

altdirs
Allows the use of alternative directories for storing the Prolog files and the XML documenting files resulting from entity compilation. This flag can only be set for Prolog compilers providing the necessary operating-system access predicates for implementing this feature (specifically, a built-in predicate for creating new directories). Possible option values are off and on (the usual default). The names of the alternative directories are specified using the compiler flags tmpdir and xmldir. The default values for these flags are defined in the configuration files. Make sure the directory names are valid for your operating system before setting this flag on.
tmpdir(Directory)
Sets the directory to be used to store the temporary files generated when compiling Logtalk source files. The default value is a sub-directory of the source files directory, either lgt_tmp or .lgt_tmp (depending on the back-end Prolog compiler and operating-system). Use of this flag requires that the flag altdirs be set to on (not supported in some back-end Prolog compilers).
xmldir(Directory)
Sets the directory to be used to store the automatically generated XML documenting files. The default value is xml_docs, a sub-directory of the source files directory. Use of this flag requires that the read-only flag altdirs be set to on (not supported in some back-end Prolog compilers).

Optional features compilation flags

complements(Option)
Allows objects to be compiled with support for complementing categories turned off in order to improve performance and security. Possible option values are allow and deny (the usual default). This option can be used on a per-object basis. Note that changing this option is of no consequence for objects already compiled and loaded.
dynamic_declarations(Option)
Allows objects to be compiled with support for dynamic declaration of new predicates turned off in order to improve performance and security. Possible option values are allow and deny (the usual default). This option can be used on a per-object basis. Note that changing this option is of no consequence for objects already compiled and loaded.
events(Option)
Allows message sending calls to be compiled with event-driven programming support disable in order to improve performance. Possible option values are allow and deny (the usual default). Objects (and categories) compiled with this option set to deny use optimized code for message-sending calls that does not trigger events. As such, this option can be used on a per-object (or per-category) basis. Note that changing this option is of no consequence for objects already compiled and loaded.
context_switching_calls(Option)
Allows context switching calls (<</2) to be either allowed or denied. Possible option values are allow and deny. The default flag vale is allow. Note that changing this option is of no consequence for objects already compiled and loaded.

Other flags

report(Option)
Controls reporting of each compiled or loaded object, category, or protocol (including compilation and loading warnings). Possible option values are on (verbose, the usual default), warnings (only print warnings), and off (silent compilation and loading, useful for batch processing).
code_prefix(Option)
Enables the definition of prefix for all functors of Prolog code generated by the Logtalk compiler. The option value must be an atom; the default value is the empty atom (''). Specifying a code prefix provides a way to solve possible conflicts between Logtalk compiled code and other Prolog code. In addition, some Prolog compilers automatically hide predicates whose functor start with a specific prefix such as the character $.
debug(Option)
Controls the compilation of source files in debug mode (the Logtalk built-in debugger can only be used with files compiled in this mode). Possible option values are on and off (the usual default).
startup_message
Controls the messages printed by Logtalk at startup. Possible flag values are flags(verbose) (prints the Logtalk banner and a verbose listing of the default compiler flags), flags(compact) (the usual default; prints the Logtalk banner and a compact listing of the default compiler flags), banner (prints only the Logtalk banner), and none (suppress all startup messages; useful for batch processing).
reload(Option)
Defines the reloading behavior for source files. Possible option values are skip (skip loading of already loaded files; this value can be used to get similar functionality to the Prolog directive ensure_loaded/1) and always (always reload files; the usual default when developing). This option must not be used when recompiling source files in debug mode (see debug/1 option above).
smart_compilation(Option)
Controls the use of smart compilation of source files to avoid recompiling files that are unchanged since the last time they are compiled. Possible option values are on and off (the usual default). This option is only supported in some Prolog compilers. It must not be used when recompiling source files in debug mode (see debug/1 option above).
hook(Object)
Allows the definition of compiler hooks that are called for each term read form a source file and for each compiled goal. This option specifies an object (which can be the pseudo-object user) implementing the expanding built-in protocol. The object is expected to define clauses for the term_expansion/2 and goal_expansion/2 predicates. In the case of the term_expansion/2 predicate, the first argument is the term read form the source file while the second argument returns a list of terms corresponding to the expansion of the first argument. In the case of the goal_expansion/2 predicate, the second argument should be a goal resulting from the expansion of the goal in the first argument. The predicate goal_expansion/2 is called on the expanded goals so care must be taken to avoid compilation loops.
clean(Option)
Controls cleaning of the intermediate Prolog files generated when compiling Logtalk source files. Possible option values are off and on (the usual default).

Reloading and smart compilation of source files

As a general rule, reloading source files should never occur in production code and should be handled with care in development code. Reloading a Logtalk source file usually requires reloading the intermediate Prolog file that is generated by the Logtalk compiler. The problem is that there is no standard behavior for reloading Prolog files. For static predicates, almost all Prolog compilers replace the old definitions with the new ones. However, for dynamic predicates, the behavior depends on the Prolog compiler. Most compilers replace the old definitions but some of them simply append the new ones, which usually leads to trouble. See the compatibility notes for the back-end Prolog compiler you intend to use for more information. There is an additional potential problem when using multi-threading programming. Reloading a threaded object does not recreate from scratch its old message queue, which may still be in use (e.g. threads may be waiting on it).

When using library entities and stable code, you can avoid reloading the corresponding source files (and, therefore, recompiling them) by setting the compiler option reload to skip. For code under development, you can turn on smart compilation of source files to avoid recompiling files that have not been modified since last compilation (assuming that back-end Prolog compiler that you are using supports retrieving of file modification dates). Smart compilation of source files is usually off by default. You can enable it by changing the default flag value in your settings file, by using the corresponding compiler flag with the compiling and loading built-in predicates, or, for the remaining of a working session, by using the call:

| ?- set_logtalk_flag(smart_compilation, on).

Some caveats that you should be aware. First, some warnings that might be produced when compiling a source file will not show up if the corresponding object file is up-to-date because the source file is not being (re)compiled. Second, if you are using several Prolog compilers with Logtalk, be sure to perform the first compilation of your source files with smart compilation turned off: the intermediate Prolog files generated by the Logtalk compiler may be not compatible across Prolog compilers or even for the same Prolog compiler across operating systems (e.g. due to the use of different character encodings or end-of-line characters).

Using Logtalk for batch processing

If you use Logtalk for batch processing, you probably want to suppress most, if not all, banners, messages, and warnings that are normally printed by the system. To suppress printing of the Logtalk startup banner and default flags, set the option startup_message in the config file that you are using to none. To suppress printing of compiling and loading messages (including compiling warnings but not compiling error messages), turn off the option report.

Debugging Logtalk programs

Logtalk defines a built-in pseudo-object named debugger, which implements debugging features similar to those found on most Prolog compilers. However, there are some differences between the usual implementation of Prolog debuggers and the current implementation of the Logtalk debugger that you should be aware. First, unlike some Prolog debuggers, the Logtalk debugger is not implemented as a meta-interpreter. This translates to a different, although similar, set of debugging features with some limitations when compared with some Prolog debuggers. Second, debugging is only possible for objects compiled in debug mode. When compiling an object in debug mode, Logtalk keeps each clause goal in both source form and compiled form in order to allow tracing of the goal execution. Third, implementation of spy points allows the user to specify the execution context for entering the debugger. This feature is a consequence of the encapsulation of predicates inside objects.

Compiling entities in debug mode

Compilation of source files in debug mode is controlled by the compiler flag debug. The default value for this flag, usually off, is defined in the config files. Its value may be changed at runtime by writing:

| ?- set_logtalk_flag(debug, on).

yes

In alternative, if we want to compile only some entities in debug mode, we may instead write:

| ?- logtalk_load([file1, file2, ...], [debug(on)]).

The compiler flag smart_compilation is automatically turned off whenever the debug flag is turned on at runtime. This is necessary because debug code would not be generated for files previously compiled in normal mode if there are no changes to the source files. Note, however, that you should be careful to not turn both flags on at the same time in a config or settings file.

We may check or enumerate, by backtracking, all loaded entities compiled in debug mode as follows:

| ?- debugger::debugging(Entity).

Logtalk Procedure Box model

Logtalk uses a Procedure Box model similar to those found on most Prolog compilers. The traditional Prolog procedure box model uses four ports (call, exit, redo, and fail) for describing control flow when a predicate clause is used during program execution:

call
predicate call
exit
success of a predicate call
redo
backtracking into a predicate
fail
failure of a predicate call

Logtalk, as found on some recent Prolog compilers, adds a port for dealing with exceptions thrown when calling a predicate:

exception
predicate call throws an exception

In addition to the ports described above, Logtalk adds two more ports, fact and rule, which show the result of the unification of a goal with, respectively, a fact and a rule head:

fact
unification success between a goal and a fact
rule
unification success between a goal and a rule head

For static predicates, the debugger prints the clause number at the unification ports: Fact #N or Rule #N indicates that clause N is being used for proving a goal.

The user may define for which ports the debugger should pause for user interaction by specifying a list of leashed ports. For example:

| ?- debugger::leash([call, exit, fail]).

Alternatively, the user may use an atom abbreviation for a pre-defined set of ports. For example:

| ?- debugger::leash(loose).

The abbreviations defined in Logtalk are similar to those defined on some Prolog compilers:

none
[]
loose
[fact, rule, call]
half
[fact, rule, call, redo]
tight
[fact, rule, call, redo, fail, exception]
full
[fact, rule, call, exit, redo, fail, exception]

Defining spy points

Logtalk spy points can be defined by simply stating which predicates should be spied, as in most Prolog debuggers, or by fully specifying the context for activating a spy point.

Defining predicate spy points

Predicate spy points are specified using the method spy/1. The argument can be either a predicate indicator (Functor/Arity) or a list of predicate indicators. For example:

| ?- debugger::spy(foo/2).

Spy points set.
yes

| ?- debugger::spy([foo/4, bar/1]).

Spy points set.
yes

Predicate spy points can be removed by using the method nospy/1. The argument can be a predicate indicator, a list of predicate indicators, or a non-instantiated variable in which case all predicate spy points will be removed. For example:

| ?- debugger::nospy(_).

All matching predicate spy points removed.
yes

Defining context spy points

A context spy point is a term describing a message execution context and a goal:

(Sender, This, Self, Goal)

The debugger is evoked whenever the execution context is true and when the spy point goal unifies with the goal currently being executed. Variable bindings resulting from the unification between the current goal and the goal argument are discarded. The user may establish any number of context spy points as necessary. For example, in order to call the debugger whenever a predicate defined on an object named foo is called we may define the following spy point:

| ?- debugger::spy(_, foo, _, _).

Spy point set.
yes

For example, we can spy all calls to a foo/2 predicate by setting the condition:

| ?- debugger::spy(_, _, _, foo(_, _)).

Spy point set.
yes

The method nospy/4 may be used to remove all matching spy points. For example, the call:

| ?- debugger::nospy(_, _, foo, _).

All matching context spy points removed.
yes

will remove all context spy points where the value of Self matches the name foo.

Removing all spy points

We may remove all predicate spy points and all context spy points by using the method nospyall/0:

| ?- debugger::nospyall.

All predicate spy points removed.
All context spy points removed.
yes

Tracing program execution

Logtalk allows tracing of execution for all objects compiled in debug mode. To start the debugger in trace mode, write:

| ?- debugger::trace.

yes

Note that, when tracing, spy points will be ignored. While tracing, the debugger will pause for user input at each leashed port, printing an informative message with the port name and the current goal. After the port name, the debugger prints the goal invocation number (except for the unification ports). This invocation number is unique and can be used to correlate the port trace messages.

To stop tracing and turning off the debugger, write:

| ?- debugger::notrace.

yes

Debugging using spy points

Tracing a program execution may generate large amounts of debugging data. Debugging using spy points allows the user to concentrate its attention in specific points of its code. To start a debugging session using spy points, write:

| ?- debugger::debug.

yes

At the beginning of a port description, the debugger will print a + or a * before the current goal if there is, respectively, a predicate spy point or a context spy point defined.

To stop the debugger, write:

| ?- debugger::nodebug.

yes

Note that stopping the debugger does not remove any defined spy points.

Debugging commands

The debugger pauses at leashed posts when tracing or when finding a spy point for user interaction. The commands available are as follows:

c — creep
go on; you may use the spacebar, return, or enter keys in alternative
l — leap
continues execution until the next spy point is found
s — skip
skips debugging for the current goal; only meaningful at call and redo ports
i — ignore
ignores goal, assumes that it succeeded; only valid at call and redo ports
f — fail
forces backtracking; may also be used to convert an exception into a failure
n — nodebug
turns off debugging
@ — command; ! can be used in alternative
reads and executes a query
b — break
suspends execution and starts new interpreter; type end_of_file to terminate
a — abort
returns to top level interpreter
q — quit
quits Logtalk
d — display
writes current goal without using operator notation
w — display
writes current goal quoting atoms if necessary
x — context
prints execution context
e — exception
prints exception term thrown by the current goal
= — debugging
prints debugging information
* — add
adds a context spy point for the current goal
/ — remove
removes a context spy point for the current goal
+ — add
adds a predicate spy point for the current goal
- — remove
removes a predicate spy point for the current goal
h — help
prints list of command options; ? can be used in alternative

Context-switching calls

Logtalk provides a control construct, <</2, which allows the execution of a query within the context of an object. Common debugging uses include checking an object local predicates (e.g. predicates representing internal dynamic state) and sending a message from within an object. This control construct may also be used to write unit tests.

Consider the following toy example:

:- object(broken).

    :- public(a/1).
    :- private([b/2, c/1]).
    :- dynamic(c/1).

    a(A) :- b(A, B), c(B).
    b(1, 2). b(2, 4). b(3, 6).
    c(3).    % in a real-life example, this would be a clause asserted at runtime

:- end_object.

Something is wrong when we try the object public predicate, a/1:

| ?- broken::a(A).

no

For helping diagnosing the problem, instead of compiling the object in debug mode and doing a trace of the query to check the clauses for the non-public predicates, we can instead simply type:

| ?- broken << c(C).

C = 3
yes

The <</2 control construct works by switching the execution context to the object in the first argument and then compiling and executing the second argument within that context:

| ?- broken << (self(Self), sender(Sender), this(This)).

Self = broken
Sender = broken
This = broken

yes

As exemplified above, the <</2 control construct allows you to call an object local and private predicates. However, it is important to stress that we are not bypassing or defeating an object predicate scope directives. The calls take place within the context of the specified object, not within the context of the object making the <</2 call. Thus, the <</2 control construct implements a form of execution-context switching.

The availability of the <</2 control construct is controlled by the compiler flag context_switching_calls, which default value is defined in the config files of the back-end Prolog compilers.

Using compilation hooks and term expansion for debugging

It is possible to use compilation hooks and the term expansion mechanism for conditional compilation of debugging goals. Assume that we chose the predicate debug/1 to represent debug goals. For example:

append([], List, List) :-
    debug((write('Base case: '), writeq(append([], List, List)), nl)).
append([Head| Tail], List, [Head| Tail2]) :-
    debug((write('Recursive case: '), writeq(append(Tail, List, Tail2)), nl)),
    append(Tail, List, Tail2).

When debugging, we want to call the argument of the predicate debug/1. This can be easily accomplished by defining a hook object containing the following definition for goal_expansion/2:

goal_expansion(debug(Goal), Goal).

When not debugging, we can use a second hook object to discard the debug/1 calls by defining the predicate goal_expansion/2 as follows:

goal_expansion(debug(_), true).

The Logtalk compiler automatically removes any redundant calls to the built-in predicate true/0 when compiling object predicates.

Debugging grammar rules

When objects or categories containing grammar rules are compiled in debug mode, calls to non-terminals in grammar rules are printed by the debugger as call to the predicate phrase/3. This makes it possible to distinguish between calls to predicates resulting from the compilation of grammar rules from calls to other predicates. In addition, in debug mode, Logtalk tries to print any exception, in particular, existence errors, in terms of non-terminals instead of in terms of the predicates that would resulted from the compilation of grammar rules.