\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#407: The String Representation of Tcl Lists: the Gory Details}
\date{August 06, 2012}
\author{Donal K. Fellows, Kevin Kenny, Don Porter}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#407}&\textbf{The String Representation of Tcl Lists: the Gory Details}\\\hline
Author&

Donal K. Fellows \tipmail{dkf}{users.sf.net}
\par
Kevin Kenny \tipmail{kennykb}{acm.org}
\par
Don Porter \tipmail{dgp}{users.sf.net}
\\
Created&Monday, \(\text{6}^{\text{th}}\) August 2012\\
Type&Informative\\
State&Draft\\
Vote&No voting\\
Version&\tipversion$Revision: 1.7 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This document explains some of the details behind Tcl lists; it is there to expose documentation that was previously only present as comments in Tcl's source code.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{String Representation of Lists}

The routines [in tclUtil.c] implement the conversions of strings to and from Tcl lists. To understand their operation, the rules of parsing and generating the string representation of lists must be known. Here we describe them in one place.

A list is made up of zero or more elements. Any string is a list if it is made up of alternating substrings of element-separating ASCII whitespace and properly formatted elements.

The ASCII characters which can make up the whitespace between list elements are:
\begingroup\small\begin{verbatim}
    \u0009    \t    TAB
    \u000A    \n    NEWLINE
    \u000B    \v    VERTICAL TAB
    \u000C    \f    FORM FEED
    \u000D    \r    CARRIAGE RETURN
    \u0020          SPACE
\end{verbatim}
\endgroup

\textbf{NOTE:} differences between this and other places where Tcl defines a role for ``whitespace''.
\begin{itemize}
\item{}
Unlike command parsing, here NEWLINE is just another whitespace character; its role as a command terminator in a script has no importance here.
\item{}
Unlike command parsing, the BACKSLASH NEWLINE sequence is not considered to be a whitespace character.
\item{}
Other Unicode whitespace characters (recognized by \textbf{string is space} or \textit{Tcl\_UniCharIsSpace()}) do not play any role as element separators in Tcl lists.
\item{}
The NUL byte ought not appear, as it is not in strings properly encoded for Tcl, but if it is present, it is not treated as separating whitespace, or a string terminator. It is just another character in a list element.
\end{itemize}

The interpretaton of a formatted substring as a list element follows rules similar to the parsing of the words of a command in a Tcl script. Backslash substitution plays a key role, and is defined exactly as it is in command parsing. The same routine, \textit{TclParseBackslash()} is used in both command parsing and list parsing.

\textbf{NOTE:} This means that if and when backslash substitution rules ever change for command parsing, the interpretation of strings as lists also changes.

Backslash substitution replaces an ``escape sequence'' of one or more characters starting with
\begingroup\small\begin{verbatim}
    \u005c    \    BACKSLASH
\end{verbatim}
\endgroup

with a single character. The one character escape sequent case happens only when BACKSLASH is the last character in the string. In all other cases, the escape sequence is at least two characters long.

The formatted substrings are interpreted as element values according to the following cases:
\begin{itemize}
\item{}
If the first character of a formatted substring is
\begingroup\small\begin{verbatim}
    \u007b    {    OPEN BRACE
\end{verbatim}
\endgroup

then the end of the substring is the matching 
\begingroup\small\begin{verbatim}
    \u007d    }    CLOSE BRACE
\end{verbatim}
\endgroup

character, where matching is determined by counting nesting levels, and not including any brace characters that are contained within a backslash escape sequence in the nesting count. Having found the matching brace, all characters between the braces are the string value of the element. If no matching close brace is found before the end of the string, the string is not a Tcl list. If the character following the close brace is not an element separating whitespace character, or the end of the string, then the string is not a Tcl list.

\textbf{NOTE:} this differs from a brace-quoted word in the parsing of a Tcl command only in its treatment of the backslash-newline sequence. In a list element, the literal characters in the backslash-newline sequence become part of the element value. In a script word, conversion to a single SPACE character is done.

\textbf{NOTE:} Most list element values can be represented by a formatted substring using brace quoting. The exceptions are any element value that includes an unbalanced brace not in a backslash escape sequence, and any value that ends with a backslash not itself in a backslash escape sequence.
\item{}
If the first character of a formatted substring is
\begingroup\small\begin{verbatim}
    \u0022    "    QUOTE
\end{verbatim}
\endgroup

then the end of the substring is the next QUOTE character, not counting any QUOTE characters that are contained within a backslash escape sequence. If no next QUOTE is found before the end of the string, the string is not a Tcl list. If the character following the closing QUOTE is not an element separating whitespace character, or the end of the string, then the string is not a Tcl list. Having found the limits of the substring, the element value is produced by performing backslash substitution on the character sequence between the open and close QUOTEs.

\textbf{NOTE:} Any element value can be represented by this style of formatting, given suitable choice of backslash escape sequences.
\item{}
All other formatted substrings are terminated by the next element separating whitespace character in the string. Having found the limits of the substring, the element value is produced by performing backslash substitution on it.

\textbf{NOTE:} Any element value can be represented by this style of formatting, given suitable choice of backslash escape sequences, with one exception. The empty string cannot be represented as a list element without the use of either braces or quotes to delimit it.
\end{itemize}

This collection of parsing rules is implemented in the routine \textit{TclFindElement()}.

In order to produce lists that can be parsed by these rules, we need the ability to distinguish between characters that are part of a list element value from characters providing syntax that define the structure of the list. This means that our code that generates lists must at a minimum be able to produce escape sequences for the 10 characters identified above that have significance to a list parser.

\section{Canonical Lists}

In addition to the basic rules for parsing strings into Tcl lists, there are additional properties to be met by the set of list values that are generated by Tcl. Such list values are often said to be in ``canonical form'':
\begin{itemize}
\item{}
When any canonical list is evaluated as a Tcl script, it is a script of either zero commands (an empty list) or exactly one command. The command word is exactly the first element of the list, and each argument word is exactly one of the following elements of the list. This means that any characters that have special meaning during script evaluation need special treatment when canonical lists are produced:
\begin{itemize}
\item{}
Whitespace between elements may not include NEWLINE.
\item{}
The command terminating character,
\begingroup\small\begin{verbatim}
    \u003b    ;    SEMICOLON
\end{verbatim}
\endgroup

must be BRACEd, QUOTEd, or escaped so that it does not terminate the command prematurely.
\item{}
Any of the characters that begin substitutions in scripts,
\begingroup\small\begin{verbatim}
    \u0024    $    DOLLAR
    \u005b    [    OPEN BRACKET
    \u005c    \    BACKSLASH
\end{verbatim}
\endgroup

need to be BRACEd or escaped.
\item{}
In any list where the first character of the first element is
\begingroup\small\begin{verbatim}
    \u0023    #    HASH
\end{verbatim}
\endgroup

that HASH character must be BRACEd, QUOTEd, or escaped so that it does not convert the command into a comment.
\item{}
Any list element that contains the character sequence BACKSLASH NEWLINE cannot be formatted with BRACEs. The BACKSLASH character must be represented by an escape sequence, and unless QUOTEs are used, the NEWLINE must be as well.
\end{itemize}
\item{}
It is also guaranteed that one can use a canonical list as a building block of a larger script within command substitution, as in this example:
\begingroup\small\begin{verbatim}
        set script "puts \[[list $cmd $arg]]"; eval $script
\end{verbatim}
\endgroup

To support this usage, any appearance of the character
\begingroup\small\begin{verbatim}
    \u005d    ]    CLOSE BRACKET
\end{verbatim}
\endgroup

in a list element must be BRACEd, QUOTEd, or escaped.
\item{}
Finally it is guaranteed that enclosing a canonical list in braces produces a new value that is also a canonical list. This new list has length 1, and its only element is the original canonical list. This same guarantee also makes it possible to construct scripts where an argument word is given a list value by enclosing the canonical form of that list in braces:
\begingroup\small\begin{verbatim}
        set script "puts {[list $one $two $three]}"; eval $script
\end{verbatim}
\endgroup

This sort of coding was once fairly common, though it's become more idiomatic to see the following instead:
\begingroup\small\begin{verbatim}
        set script [list puts [list $one $two $three]]; eval $script
\end{verbatim}
\endgroup

In order to support this guarantee, every canonical list must have balance when counting those braces that are not in escape sequences.
\end{itemize}

Within these constraints, the canonical list generation routines \textit{TclScanElement()} and \textit{TclConvertElement()} attempt to generate the string for any list that is easiest to read. When an element value is itself acceptable as the formatted substring, it is usually used (CONVERT\_NONE). When some quoting or escaping is required, use of BRACEs (CONVERT\_BRACE) is usually preferred over the use of escape sequences (CONVERT\_ESCAPE). There are some exceptions to both of these preferences for reasons of code simplicity, efficiency, and continuation of historical habits. Canonical lists never use the QUOTE formatting to delimit their elements because that form of quoting does not nest, which makes construction of nested lists far too much trouble. Canonical lists always use only a single SPACE character for element-separating whitespace.

\section{Future Considerations}

When a list element requires quoting or escaping due to a CLOSE BRACKET character or an internal QUOTE character, a strange formatting mode is recommended. For example, if the value ``\textbf{a\{b]c\}d}'' is converted by the usual modes:
\begingroup\small\begin{verbatim}
    CONVERT_BRACE:    a{b]c}d    => {a{b]c}d}
    CONVERT_ESCAPE:   a{b]c}d    => a\{b\]c\}d
\end{verbatim}
\endgroup

we get perfectly usable formatted list elements. However, this is not what Tcl releases have been producing. Instead, we have:
\begingroup\small\begin{verbatim}
    CONVERT_MASK:     a{b]c}d    => a{b\]c}d
\end{verbatim}
\endgroup

where the CLOSE BRACKET is escaped, but the BRACEs are not. The same effect can be seen replacing \textbf{]} with \textbf{``} in this example. There does not appear to be any functional or aesthetic purpose for this strange additional mode. The sole purpose I can see for preserving it is to keep generating the same formatted lists programmers have become accustomed to, and perhaps written tests to expect. That is, compatibility only. The additional code complexity required to support this mode is significant. The lines of code supporting it are delimited in the routines marked with \textbf{\#if COMPAT} directives. This makes it easy to experiment with eliminating this formatting mode simply with ''\textbf{\#define COMPAT 0}" above. I believe this is worth considering.

Another consideration is the treatment of QUOTE characters in list elements. \textit{TclConvertElement()} must have the ability to produce the escape sequence \textbf{\(\backslash\)"} so that when a list element begins with a QUOTE we do not confuse that first character with a QUOTE used as list syntax to define list structure. However, that is the only place where QUOTE characters need quoting. In this way, handling QUOTE could really be much more like the way we handle HASH which also needs quoting and escaping only in particular situations. Following up this could increase the set of list elements that can use the CONVERT\_NONE formatting mode.

More speculative is that the demands of canonical list form require brace balance for the list as a whole, while the current implementation achieves this by establishing brace balance for every element.

Finally, a reminder that the rules for parsing and formatting lists are closely tied together with the rules for parsing and evaluating scripts, and will need to evolve in sync.

\section{Origin of Document and Copyright Notice}

This document is based ``near-verbatim'' on comments in \textit{generic/tclUtil.c} in the Tcl source code distribution. [\url{http://core.tcl.tk/tcl/doc/trunk/generic/tclUtil.c}]
\begingroup\small\begin{verbatim}
Copyright (c) 1987-1993 The Regents of the University of California.
Copyright (c) 1994-1998 Sun Microsystems, Inc.
Copyright (c) 2001 by Kevin B. Kenny. All rights reserved.
\end{verbatim}
\endgroup

This document is made available under the same license as Tcl.

[I, Kevin B. Kenny, dedicate any and all copyright interest in TIP \#407 to the public domain. I make this dedication for the benefit of the public at large and to the detriment of my heirs and successors. I intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to TIP \#407 under copyright law.]

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
