\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#460: An Alternative to Upvar}
\date{December 08, 2016}
\author{Don Hathway}
\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 \#460}&\textbf{An Alternative to Upvar}\\\hline
Author&

Don Hathway \tipmail{dunnie}{gmail.com}
\\
Created&Thursday, \(\text{8}^{\text{th}}\) December 2016\\
Type&Project\\
Tcl Version&\(9.0\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.5 $\\
Keywords&Tcl, variable, link, upvar\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

Variable linking with the \textit{upvar} command is not as intuitive or effecient as it should be. This TIP proposes an alternative through automatic variable linking.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

The current strategy used to link a variable in a called procedure to the caller, is to pass the name of the variable to the procedure, and use the \textit{upvar} command to create a new variable, which is then linked to the original. Thus linking to a variable requires two components; the variable name and a newly created variable.

It is possible to instruct Tcl to do this linking automatically in an idiomatic way and dispense with the \textit{upvar} command call.

Also, the requirement (by \textit{upvar}) that the name of the new link variable be a different name from the original is arguably considered counter-intuitive.

Benefits to this TIP as proposed:
\begin{enumerate}
\item{}
\textbf{No code to perform explicit linking within the procedure's body.} Unlike \textit{upvar}, this method requires no additional code to be entered in the body of the procedure. Less code, less bugs, easier to use! It has been said that Tcl'ers should make more use of variable linking in their code. Making it easier for them should have an encouraging effect, similar to how most Tcl'ers prefer \textit{\$var} over \textit{set var}.
\setcounter{enumi}{1}
\item{}
\textbf{Clearly defines links in the procedure's parameter list.} Readers should instantly know what the links are. Clarity is important, especially for people that read code all day. There are no special project naming conventions to follow. A reader doesn't have to rely on docs or assume that a parameter name of ``varName'', ``\_var'', or ``varLnk'' is to be linked by an upvar call, of which may be pushed down in the procedure's body by comments or other code.
\setcounter{enumi}{2}
\item{}
\textit{'Alleviates arguably messy }upvar\textit{ chain linking.}'
\end{enumerate}

\subsection{Upvar Chaining Example}

Below are three \textit{upvar}s with the same arguments. As you can see, there is quite a bit of arguably unnecessary code duplication, and that is bug prone.
\begingroup\small\begin{verbatim}
 proc foo {a} {
    upvar 1 $a la
    maybe do something with la
    bar la
 }
 proc bar {a} {
    upvar 1 $a la
    maybe do something with la
    baz la
 }
 proc baz {a} {
    upvar 1 $a la
    maybe do something with la
 }
 foo begin
\end{verbatim}
\endgroup

This could be written more succinctly:
\begingroup\small\begin{verbatim}
 proc foo {*a} {
    maybe do something with a
    bar a
 }
 proc bar {*a} {
    maybe do something with a
    baz a
 }
 proc baz {*a} {
    maybe do something with a
 }
 foo begin
\end{verbatim}
\endgroup

\section{Specification}

Add support to procedure handling to allow for a parametric hint to procedure definitions with respect to the intent to link variables accordingly. We use the asterisk character ``\textbf{*}'' as the symbol to declare this intent; which shall prefix the parameter's name. Consequently, the ``\textbf{*}'' character becomes special, but only inside the procedure parameter list. A procedure definition using this facility would then have the signature:
\begingroup\small\begin{verbatim}
 proc foo {*a *b} {...}
\end{verbatim}
\endgroup

Where \textbf{*a} and \textbf{*b} are the procedure's parameters to be linked to the caller's arguments. New variables are then created for the future linking. In this example \textbf{*a} creates a new link variable named \textbf{a}, and likewise done for \textbf{*b}. \textbf{*a} and \textbf{*b} holds the values passed in by the caller.

The formal parameter's shall retain the same values provided by the caller.

The link variable's name shall always have one \textbf{*} symbol less than its counterpart parameter, for the sake of consistency. In example, a parameter named \textbf{***a} shall have a counterpart link variable named \textbf{**a}. Similarily \textbf{**a} shall have a counterpart link named \textbf{*a}.

Where there are duplicate link parameter names (i.e. proc P \{*a *a\}) the behavior shall be the same as if there were duplicate \textbf{upvar} statements.

It is legal to have empty link variable names. It shall be possible with a single \textbf{*} in the procedure's parameter list (i.e. proc P \{*\} \{incr ""\}). The same duplicate name rule applies.

If the variable to be linked does not exist, it shall be created, if necessary. It shall have the same behavior as \textbf{upvar 1} in such instances.

When a link's construction fails, the behavior shall be the same as if \textbf{upvar} had failed, the procedure will return with an error before any other commands (with exception to any commands involved in the link's construction) in its body are executed.

It is illegal for a link parameter to have a default value. It shall invoke an error during procedure creation time and result in failed procedure creation with the error code:
\begingroup\small\begin{verbatim}
 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PROC","FORMALARGUMENTFORMAT", NULL);
\end{verbatim}
\endgroup

An example of such an error for: \tipbar{} proc P \{\{*a foo\}\} \{...\} Would be: ``procedure ''P``: formal parameter ''*a`` is to be linked and must not have a default value''

In that example, proc \textbf{P} is never created, the attempt failed due to the error.

It is the caller's responsibility to provide the names of variables to be linked. This constraint exists in the spirit of promoting good coding practices and to help avoid obscure and subtle bugs. For the same reasons, this TIP only searches one level up. Therefore, It shall have the same behavior as \textbf{upvar 1}.

\textbf{*args} is a valid parameter name. For example, \textbf{args} is simply a link in:
\begingroup\small\begin{verbatim}
 proc foo {a *args} {
     incr args
 }
\end{verbatim}
\endgroup

Note that as of this TIP \textit{proc foo \{args args\} \{...\}} is legal Tcl. In this instance only the first \textit{scalar} \textbf{args} is usable by the procedure. The rest of the arguments are inaccessible by the script. They're not internally lost, but Tcl's variable lookup mechanics will choose whichever is found first when a script references it. This behavior is inherited for \textit{proc foo \{*args args\} \{...\}}. Where \textbf{args} will be a link.

To further illustrate this proposal with an example:
\begingroup\small\begin{verbatim}
 proc foo {*a *b} {
   bar a b
 }
\end{verbatim}
\endgroup
\begingroup\small\begin{verbatim}
 proc bar {*a *b} {
   incr a
   incr b
 }
\end{verbatim}
\endgroup
\begingroup\small\begin{verbatim}
 set v1 0
 set v2 1
 foo v1 v2
 puts $v1
 # prints 1
 puts $v2
 # prints 2
\end{verbatim}
\endgroup
\begingroup\small\begin{verbatim}
 # Version of foo using upvar:
 proc foo {a b} {
    # Note, upvar $a a would be an error.
    upvar 1 $a la $b lb
    bar la lb
 }
 proc bar {a b} {
    upvar 1 $a la $b lb
    incr la
    incr lb
 }
\end{verbatim}
\endgroup

The ``\textbf{*}'' character was chosen primarily because it resembles a star or a snowflake and has a pleasantry to it. It is one of the few ascii characters that \textbf{sticks out} from its surrounding text. 

It is also familiar to users of other languages where the same symbol exhibits similar semantics (to wit: a link in Tcl acts as a reference to another variable and doesn't perform a copy when the reference is written to, as it would if it weren't a link). However, unlike other languages, the Tcl core does not expose operations to user scripts that work directly on memory, so the ``\textbf{*}'' character should not be mistaken to behave the same or suffer from the same pitfalls as it does in C, C++, Golang, etc. The \textbf{*} symbol simply instructs Tcl to create a link if it is able to do so.

\subsection{Consequences}
\begin{enumerate}
\item{}
Breaks scripts using the special ``\textbf{*}'' as the first character in their procedure's parameters (i.e. \textbf{*var}).

The impact of this should be minimal because these variable names require the user to wrap it in curly braces (i.e. \textbf{\$\{*var\}}) to fetch their values, unless they're using the less common form of \textbf{set varname}.
\end{enumerate}

\section{Reference Implementation}

See branch \textit{dah-proc-arg-upvar}

\subsection{Implementation Notes}
\begin{description}
\item[tclInt.h]
Add a new field named \textit{numArgsCompiledLocals} to the Proc struct. The new field holds the number of parameters along with any other relevant local variables which follow immediately after the parameters. For this TIP, these additional locals are variables with the VAR\_LINK flag and to be resolved as links to the values of arguments they've been configured to link with.
\end{description}

 The additional field was a hard choice, but is necessary because \textit{TclProcCompileProc} enforces \textit{procPtr-\tiprangle{}numCompiledLocals} to be the same value as \textit{procPtr-\tiprangle{}numArgs}. The local variable table is evidently not growable until later.
\begin{description}
\item[tclProc.c]
Modify \textit{InitArgsAndLocals} to do the automatic linking. Note that this is a \textit{very hot} function and that was kept in mind while making the necessary adjustments. There are two additional branches in the function (the second only visited when an error happens). The first to check if the command has any parameters that need linking and if so, process them with link support handling code. The second branch is to simply check if the link handling code set an error when an error occurs, so this branch should not be a concern as to performance impact. Due to branch prediction and this function being so hot, there should be virtually nil of a performance impact on any code which doesn't make use of the new automatic linking facility.
\item[tclProc.c]
Modify \textit{TclCreateProc} to add additional locals after the list of parameter locals (if any) when there are parameters flagged for auto linking.
\end{description}

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

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