\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#144: Argument Expansion Syntax}
\date{July 26, 2003}
\author{Peter Spjuth, Donal K. Fellows, }
\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 \#144}&\textbf{Argument Expansion Syntax}\\\hline
Author&

Peter Spjuth \tipmail{peter.spjuth}{space.se}
\par
Donal K. Fellows \tipmail{donal.k.fellows}{man.ac.uk}
\par
\tipmail{dgp}{users.sf.net}
\\
Created&Saturday, \(\text{26}^{\text{th}}\) July 2003\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Withdrawn\\
Vote&Pending\\
Version&\tipversion$Revision: 1.8 $\\
Post History&\\
Obsoleted By&157\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes to add syntax in Tcl to perform argument expansion in a safe and efficient manner.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Introduction}

Many commands take a variable number of arguments and often you find yourself with those arguments in a list. This list must then be expanded into individual arguments to the command. This is currently done with eval:
\begingroup\small\begin{verbatim}
eval destroy [winfo children .]
\end{verbatim}
\endgroup

This is a bit obscure and also very error prone when the command becomes more complex. It is also inefficient and not object safe, why something specialised in doing this would be better.

\section{Background}

See also \cite{tip103}. Please also see a summary of a poll of TCLCORE readers taken after \cite{tip103} was rejected. \url{http://wiki.tcl.tk/9462}

\section{Rationale}

For examples three statements are used. This is the eval version:
\begingroup\small\begin{verbatim}
eval destroy [winfo children .]
eval button .b $stdargs -text \$mytext -bd $border
eval exec \$prog $opts1 [getMoreopts] \$file1 \$file2
\end{verbatim}
\endgroup

The eval version would be even more complex if the lists that are to be expanded are not known to be pure. To be really safe the last would be:
\begingroup\small\begin{verbatim}
eval exec \$prog [lrange $opts1 0 end] [lrange [getMoreopts] 0 end] \$file1 \$file2
\end{verbatim}
\endgroup

With the proposed syntax they become:
\begingroup\small\begin{verbatim}
destroy {}[winfo children .]
button .b {}$stdargs -text $mytext -bd $border
exec $prog {}$opts1 {}[getMoreopts] $file1 $file2
\end{verbatim}
\endgroup

The advantage of using syntax for this is that the command do not get obscured. In the examples destroy/button/exec is the most important information on each line and it gets to be first on the line.

\section{Specification}

If a word starts with a pair of braces, ``\{\}'', and is followed by a non whitespace character it signifies argument expansion. The braces are removed and the rest of the word is parsed and substituted as any other word. The character after the removed ``\{\}'' counts as a first character in the rules about open braces and double quotes. After substitution, the word is then parsed as a list (as if with \textit{Tcl\_SplitList()} or \textit{Tcl\_GetListFromObj}) and each element of the list is added to the command being built as a separate word with no further parsing.

Before executing the command any word to be expanded is treated as a list where each element becomes one separate argument to the command.

\textit{Note 1:} A word should really start with \{\} to trigger expansion which means that words like these are not expanded:
\begingroup\small\begin{verbatim}
cmd "{}$temp" \{}[something]
\end{verbatim}
\endgroup

\textit{Note 2:} Expansion is typically most useful with words like:
\begingroup\small\begin{verbatim}
cmd {}$var {}[somecmd $arg] {}$arr([cmd $arg])
\end{verbatim}
\endgroup

But things like this are also legal:
\begingroup\small\begin{verbatim}
cmd {}word {}$x,$y {}[foo]xy[apa] {}{apa bepa}
\end{verbatim}
\endgroup

\section{Motivating Examples}

Many of the examples that make this TIP the way it is come from either advanced usage of commands like [exec] or from Tk.

Consider the case where you have lists of options for several external commands that are to be executed together in a pipeline. With expansion it becomes easy to execute such things:
\begingroup\small\begin{verbatim}
exec prog1 {}$optlist1 | prog2 {}$optlist2 | prog3 -staticOption
\end{verbatim}
\endgroup

As you can see, without expansion building this pipeline would be quite a complex task and would make what is going on much more obscure.

With Tk, there are many examples. Here's one from the creation of lines on a canvas:
\begingroup\small\begin{verbatim}
set id [$canv create polygon {}$coords -fill {} {}$opts -tags {foo bar}]
\end{verbatim}
\endgroup

In this case, there is a fair amount of material before the coordinate list, some static options (which act like defaults) between the coords list and the user-supplied options list, and some further options (which act like overrides for semantically-significant bits) after that which need careful space handling. This also demonstrates why having a command with a list of expanding indices is not a good idea, since it is plain to see that ongoing maintenance might place extra non-expanding arguments in various places through the command.

Another example demonstrates why having commands as well as variables expanded is a good idea:
\begingroup\small\begin{verbatim}
namespace eval my {
   variable defaults {
      -bg white
      -fg black
   }
   proc entry {path args} {
      variable defaults
      ::entry $path {}$defaults {}[platformOpts $::tcl_platform(platform)] {}$args
   }
}
\end{verbatim}
\endgroup

This illustrates why just plain [concat] doesn't work, demonstrates that having a way to do commands can be very useful, and also shows that having multiple expansion operations in a row is potentially useful.

A final example (deleting discontiguous ranges of characters with a particular tag) shows that this is not just useful in Tk for when creating widgets and canvas items:
\begingroup\small\begin{verbatim}
$text delete {}[$text tag ranges $tagToCleanUp]
\end{verbatim}
\endgroup

In this case, the obvious alternative:
\begingroup\small\begin{verbatim}
foreach {s e} [$text tag ranges $theTag] { $text delete $s $e }
\end{verbatim}
\endgroup

is wrong, because the positions of the tags move with each deletion (by contrast, the [\$text delete] operation is careful in this regard.)

\section{Reference Implementation}

Not done yet.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#103]{tip103}
Peter Spjuth,
Donal K. Fellows,
Andreas Leitgeb,
\emph{Argument Expansion Command},
on-line at \url{http://purl.org/tcl/tip/103.html}
\end{thebibliography}
\end{document}
