Syntax Errors

A syntax error occurs when data are read from some external source but have an improper format or cannot be processed for some other reason. This category mainly applies to read/1 and its variants.

The exception code associated with a syntax error is

     syntax_error(Goal, Position, Message, Left, Right)
     

where Goal is the goal in question, Position identifies the position in the stream where reading started, and Message describes the error. Left and right are lists of tokens before and after the error, respectively.

Note that the Position is where reading started, not where the error is.

read/1 does two things. First, it reads a sequence of characters from the current input stream up to and including a clause terminator, or the end of file marker, whichever comes first. Then it attempts to parse the sequence of characters as a Prolog term. If the parse is unsuccessful, a syntax error occurs. Thus, in the case of syntax errors, read/1 disobeys the normal rule that predicates should detect and report errors before they perform any side-effects, because the side-effect of reading the characters has been done.

A syntax error does not necessarily cause an exception to be raised. The behavior can be controlled via a Prolog flag as follows:


prolog_flag(syntax_errors, quiet)
When a syntax error is detected, nothing is printed, and read/1 just quietly fails.
prolog_flag(syntax_errors, dec10)
This provides compatibility with DEC-10 Prolog and earlier versions of Quintus Prolog: when a syntax error is detected, a syntax error message is printed on user_error, and the read is repeated. This is the default for the sake of compatibility with earlier releases.
prolog_flag(syntax_errors, fail)
This provides compatibility with C Prolog. When a syntax error is detected, a syntax error message is printed on user_error, and the read then fails.
prolog_flag(syntax_errors, error)
When a syntax error is detected, an exception is raised.