View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2006-2023, University of Amsterdam
    7                              VU University Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(error,
   38          [ instantiation_error/1,      % +FormalSubTerm
   39            uninstantiation_error/1,    % +Culprit
   40            type_error/2,               % +ValidType, +Culprit
   41            domain_error/2,             % +ValidDomain, +Culprit
   42            existence_error/2,          % +ObjectType, +Culprit
   43            existence_error/3,          % +ObjectType, +Culprit, +Set
   44            permission_error/3,         % +Operation, +PermissionType, +Culprit
   45            representation_error/1,     % +Flag
   46            resource_error/1,           % +Resource
   47            syntax_error/1,             % +ImplDepAtom
   48
   49            must_be/2,                  % +Type, +Term
   50            is_of_type/2,               % +Type, +Term
   51            current_type/3              % ?Type, @Var, -Body
   52          ]).   53:- set_prolog_flag(generate_debug_info, false).   54:- use_module(library(debug), [assertion/1]).

Error generating support

This module provides predicates to simplify error generation and checking. It's implementation is based on a discussion on the SWI-Prolog mailinglist on best practices in error handling. The utility predicate must_be/2 provides simple run-time type validation. The *_error predicates are simple wrappers around throw/1 to simplify throwing the most common ISO error terms.

author
- Jan Wielemaker
- Richard O'Keefe
- Ulrich Neumerkel
See also
- library(debug) and library(prolog_stack).
- print_message/2 is used to print (uncaught) error terms. */
   72:- multifile
   73    has_type/2.   74
   75                 /*******************************
   76                 *           ISO ERRORS         *
   77                 *******************************/
 type_error(+ValidType, +Culprit)
Tell the user that Culprit is not of the expected ValidType. This error is closely related to domain_error/2 because the notion of types is not really set in stone in Prolog. We introduce the difference using a simple example.

Suppose an argument must be a non-negative integer. If the actual argument is not an integer, this is a type_error. If it is a negative integer, it is a domain_error.

Typical borderline cases are predicates accepting a compound term, e.g., point(X,Y). One could argue that the basic type is a compound-term and any other compound term is a domain error. Most Prolog programmers consider each compound as a type and would consider a compound that is not point(_,_) a type_error.

   96type_error(ValidType, Culprit) :-
   97    throw(error(type_error(ValidType, Culprit), _)).
 domain_error(+ValidDomain, +Culprit)
The argument is of the proper type, but has a value that is outside the supported values. See type_error/2 for a more elaborate discussion of the distinction between type- and domain-errors.
  105domain_error(ValidDomain, Culprit) :-
  106    throw(error(domain_error(ValidDomain, Culprit), _)).
 existence_error(+ObjectType, +Culprit)
Culprit is of the correct type and correct domain, but there is no existing (external) resource of type ObjectType that is represented by it.
  114existence_error(ObjectType, Culprit) :-
  115    throw(error(existence_error(ObjectType, Culprit), _)).
 existence_error(+ObjectType, +Culprit, +Set)
Culprit is of the correct type and correct domain, but there is no existing (external) resource of type ObjectType that is represented by it in the provided set. The thrown exception term carries a formal term structured as follows: existence_error(ObjectType, Culprit, Set)
Compatibility
- This error is outside the ISO Standard.
  127existence_error(ObjectType, Culprit, Set) :-
  128    throw(error(existence_error(ObjectType, Culprit, Set), _)).
 permission_error(+Operation, +PermissionType, +Culprit)
It is not allowed to perform Operation on (whatever is represented by) Culprit that is of the given PermissionType (in fact, the ISO Standard is confusing and vague about these terms' meaning).
  136permission_error(Operation, PermissionType, Culprit) :-
  137    throw(error(permission_error(Operation, PermissionType, Culprit), _)).
 instantiation_error(+FormalSubTerm)
An argument is under-instantiated. I.e. it is not acceptable as it is, but if some variables are bound to appropriate values it would be acceptable.
Arguments:
FormalSubTerm- is the term that needs (further) instantiation. Unfortunately, the ISO error does not allow for passing this term along with the error, but we pass it to this predicate for documentation purposes and to allow for future enhancement.
  151instantiation_error(_FormalSubTerm) :-
  152    throw(error(instantiation_error, _)).
 uninstantiation_error(+Culprit)
An argument is over-instantiated. This error is used for output arguments whose value cannot be known upfront. For example, the goal open(File, read, input) cannot succeed because the system will allocate a new unique stream handle that will never unify with input.
  162uninstantiation_error(Culprit) :-
  163    throw(error(uninstantiation_error(Culprit), _)).
 representation_error(+Flag)
A representation error indicates a limitation of the implementation. SWI-Prolog has no such limits that are not covered by other errors, but an example of a representation error in another Prolog implementation could be an attempt to create a term with an arity higher than supported by the system.
  173representation_error(Flag) :-
  174    throw(error(representation_error(Flag), _)).
 syntax_error(+Culprit)
A text has invalid syntax. The error is described by Culprit. According to the ISO Standard, Culprit should be an implementation-dependent atom.
To be done
- Deal with proper description of the location of the error. For short texts, we allow for Type(Text), meaning Text is not a valid Type. E.g. syntax_error(number('1a')) means that 1a is not a valid number.
  187syntax_error(Culprit) :-
  188    throw(error(syntax_error(Culprit), _)).
 resource_error(+Resource)
A goal cannot be completed due to lack of resources. According to the ISO Standard, Resource should be an implementation-dependent atom.
  196resource_error(Resource) :-
  197    throw(error(resource_error(Resource), _)).
  198
  199
  200                 /*******************************
  201                 *            MUST-BE           *
  202                 *******************************/
 must_be(+Type, @Term) is det
True if Term satisfies the type constraints for Type. Defined types are atom, atomic, between, boolean, callable, chars, codes, text, compound, constant, float, integer, nonneg, positive_integer, negative_integer, nonvar, number, oneof, list, list_or_partial_list, symbol, var, rational, encoding, dict and string.

Most of these types are defined by an arity-1 built-in predicate of the same name. Below is a brief definition of the other types.

acyclicAcyclic term (tree); see acyclic_term/1
anyany term
between(FloatL,FloatU)Number [FloatL..FloatU]
between(IntL,IntU)Integer [IntL..IntU]
booleanOne of true or false
callableAtom or compound term
charAtom of length 1
charsProper list of 1-character atoms
codeRepresentation Unicode code point (0..0x10ffff)
codesProper list of Unicode character codes
compoundcompound term
compound(Term)Compound with same name/arity as term; checks arguments
constantSame as atomic
cyclicCyclic term (rational tree); see cyclic_term/1
dictA dictionary term; see is_dict/1
encodingValid name for a character encoding; see current_encoding/1
listA (non-open) list; see is_list/1
list(Type)Proper list with elements of Type
list_or_partial_listA list or an open list (ending in a variable); see is_list_or_partial_list/1
negative_integerInteger < 0
nonnegInteger >= 0
oneof(L)Ground term that is member of L
pairKey-Value pair. Same as compound(any-any)
positive_integerInteger > 0
proper_listSame as list
streamA stream name or valid stream handle; see is_stream/1
symbolSame as atom
textOne of atom, string, chars or codes
typeTerm is a valid type specification

In addition, types may be composed using TypeA,TypeB, TypeA;TypeB and negated using \Type.

throws
- instantiation_error if Term is insufficiently instantiated and type_error(Type, Term) if Term is not of Type.
  253must_be(Type, X) :-
  254    (   nonvar(Type),
  255        has_type(Type, X)
  256    ->  true
  257    ;   nonvar(Type)
  258    ->  is_not(Type, X)
  259    ;   instantiation_error(Type)
  260    ).
 is_not(+Type, @Term)
Throws appropriate error. It is known that Term is not of type Type.
throws
- type_error(Type, Term)
- instantiation_error
  270is_not(list, X) :-
  271    !,
  272    not_a_list(list, X).
  273is_not(list(Of), X) :-
  274    !,
  275    not_a_list(list(Of), X).
  276is_not(list_or_partial_list, X) :-
  277    !,
  278    type_error(list, X).
  279is_not(chars, X) :-
  280    !,
  281    not_a_list(list(char), X).
  282is_not(codes, X) :-
  283    !,
  284    not_a_list(list(code), X).
  285is_not(var,X) :-
  286    !,
  287    uninstantiation_error(X).
  288is_not(cyclic, X) :-
  289    domain_error(cyclic_term, X).
  290is_not(acyclic, X) :-
  291    domain_error(acyclic_term, X).
  292is_not(Type, X) :-
  293    current_type(Type, _Var, _Body),
  294    !,
  295    (   var(X)
  296    ->  instantiation_error(X)
  297    ;   ground_type(Type), \+ ground(X)
  298    ->  instantiation_error(X)
  299    ;   type_error(Type, X)
  300    ).
  301is_not(Type, _) :-
  302    existence_error(type, Type).
  303
  304ground_type(ground).
  305ground_type(oneof(_)).
  306ground_type(stream).
  307ground_type(text).
  308ground_type(string).
  309ground_type(rational).
  310
  311not_a_list(Type, X) :-
  312    '$skip_list'(_, X, Rest),
  313    (   var(Rest)
  314    ->  instantiation_error(X)
  315    ;   Rest == []
  316    ->  Type = list(Of),
  317        (   nonvar(Of)
  318        ->  element_is_not(X, Of)
  319        ;   instantiation_error(Of)
  320        )
  321    ;   type_error(Type, X)
  322    ).
  323
  324
  325element_is_not([H|T], Of) :-
  326    has_type(Of, H),
  327    !,
  328    element_is_not(T, Of).
  329element_is_not([H|_], Of) :-
  330    !,
  331    is_not(Of, H).
  332element_is_not(_List, _Of) :-
  333    assertion(fail).
 is_of_type(+Type, @Term) is semidet
True if Term satisfies Type.
  339is_of_type(Type, Term) :-
  340    nonvar(Type),
  341    !,
  342    has_type(Type, Term),
  343    !.
  344is_of_type(Type, _) :-
  345    instantiation_error(Type).
 has_type(+Type, @Term) is semidet
True if Term satisfies Type.
  351:- '$clausable'(has_type/2).            % always allow clause/2
  352:- public                               % May be called through current_type/3
  353    is_list_or_partial_list/1,
  354    current_encoding/1,
  355    element_types/2.  356
  357has_type(any, _).
  358has_type(atom, X)         :- atom(X).
  359has_type(atomic, X)       :- atomic(X).
  360has_type(between(L,U), X) :- (   integer(L)
  361    ->  integer(X), between(L,U,X)
  362    ;   number(X), X >= L, X =< U
  363    ).
  364has_type(boolean, X)      :- (X==true;X==false), !.
  365has_type(callable, X)     :- callable(X).
  366has_type(char,  X)        :- '$is_char'(X).
  367has_type(code,  X)        :- '$is_char_code'(X).
  368has_type(chars, X)        :- '$is_char_list'(X, _Len).
  369has_type(codes, X)        :- '$is_code_list'(X, _Len).
  370has_type(text, X)         :- text(X).
  371has_type(compound, X)     :- compound(X).
  372has_type(compound(Term),X):- compound(X), is_term_of_type(Term,X).
  373has_type(constant, X)     :- atomic(X).
  374has_type(float, X)        :- float(X).
  375has_type(ground, X)       :- ground(X).
  376has_type(cyclic, X)       :- cyclic_term(X).
  377has_type(acyclic, X)      :- acyclic_term(X).
  378has_type(integer, X)      :- integer(X).
  379has_type(nonneg, X)       :- integer(X), X >= 0.
  380has_type(positive_integer, X)     :- integer(X), X > 0.
  381has_type(negative_integer, X)     :- integer(X), X < 0.
  382has_type(nonvar, X)       :- nonvar(X).
  383has_type(number, X)       :- number(X).
  384has_type(oneof(L), X)     :- ground(X), \+ \+ memberchk(X, L).
  385has_type(pair, X)         :- nonvar(X), X = _-_.
  386has_type(proper_list, X)  :- is_list(X).
  387has_type(list, X)         :- is_list(X).
  388has_type(list_or_partial_list, X)  :- is_list_or_partial_list(X).
  389has_type(symbol, X)       :- atom(X).
  390has_type(var, X)          :- var(X).
  391has_type(rational, X)     :- rational(X).
  392has_type(string, X)       :- string(X).
  393has_type(stream, X)       :- is_stream(X).
  394has_type(encoding, X)     :- current_encoding(X).
  395has_type(dict, X)         :- is_dict(X).
  396has_type(list(Type), X)   :- is_list(X), element_types(X, Type).
  397has_type(list_or_partial_list(Type), X)   :- is_list_or_partial_list(X), element_types(X, Type).
  398has_type(type, Type)      :- ground(Type), current_type(Type,_,_).
  399has_type((A,B), X)	  :- (is_of_type(A,X)->is_of_type(B,X)).
  400has_type((A;B), X)	  :- (is_of_type(A,X)->true;is_of_type(B,X)).
  401has_type(\A, X)	          :- \+ is_of_type(A,X).
  402
  403text(X) :-
  404    (   atom(X)
  405    ;   string(X)
  406    ;   '$is_char_list'(X, _)
  407    ;   '$is_code_list'(X, _)
  408    ),
  409    !.
  410
  411element_types(List, Type) :-
  412    nonvar(Type),
  413    !,
  414    element_types_(List, Type).
  415element_types(_List, Type) :-
  416    instantiation_error(Type).
  417
  418element_types_(Var, _) :-
  419    var(Var),
  420    !.
  421element_types_([], _).
  422element_types_([H|T], Type) :-
  423    has_type(Type, H),
  424    !,
  425    element_types_(T, Type).
  426
  427is_list_or_partial_list(L0) :-
  428    '$skip_list'(_, L0,L),
  429    ( var(L) -> true ; L == [] ).
 current_encoding(?Name) is nondet
True if Name is the name of a supported encoding. See encoding option of e.g., open/4.
  436current_encoding(octet).
  437current_encoding(ascii).
  438current_encoding(iso_latin_1).
  439current_encoding(text).
  440current_encoding(utf8).
  441current_encoding(unicode_be).
  442current_encoding(unicode_le).
  443current_encoding(wchar_t).
 current_type(?Type, @Var, -Body) is nondet
True when Type is a currently defined type and Var satisfies Type of the body term Body succeeds.
  451current_type(Type, Var, Body) :-
  452    clause(has_type(Type, Var), Body0),
  453    qualify(Body0, Body).
  454
  455qualify(Var, VarQ) :-
  456    var(Var),
  457    !,
  458    VarQ = Var.
  459qualify((A0,B0), (A,B)) :-
  460    qualify(A0, A),
  461    qualify(B0, B).
  462qualify(G0, G) :-
  463    predicate_property(system:G0, built_in),
  464    !,
  465    G = G0.
  466qualify(G, error:G).
 is_term_of_type(Term, X)
Supports types as e.g. compound(oneof(list(atom))).
  472is_term_of_type(Term, X) :-
  473    compound_name_arity(Term, N, A),
  474    compound_name_arity(X, N, A),
  475    term_arg_types(1, A, Term, X).
  476
  477term_arg_types(I, A, Type, X) :-
  478    I =< A,
  479    !,
  480    arg(I, Type, AType),
  481    arg(I, X, XArg),
  482    has_type(AType, XArg),
  483    I2 is I+1,
  484    term_arg_types(I2, A, Type, X).
  485term_arg_types(_, _, _, _).
  486
  487
  488		 /*******************************
  489		 *           SANDBOX		*
  490		 *******************************/
  491
  492:- multifile sandbox:safe_primitive/1.  493
  494sandbox:safe_primitive(error:current_type(_,_,_))