\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#284: New 'invoke' and 'namespace invoke' Commands}
\date{October 01, 2006}
\author{Miguel Sofer}
\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 \#284}&\textbf{New 'invoke' and 'namespace invoke' Commands}\\\hline
Author&

Miguel Sofer \tipmail{msofer}{users.sourceforge.net}
\\
Created&Sunday, \(\text{1}^{\text{st}}\) October 2006\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.23 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP exposes a Tcl script-level interface to the direct command invokation engine already present in the Tcl library for years.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Proposed New Commands}

This TIP proposes a new subcommand to \textbf{namespace}, \textbf{invoke}, with the following syntax:

\begin{quote}
\textbf{namespace invoke} \textit{namespace} \textit{cmd} ?\textit{arg} ...?
\end{quote}

This invokes the command called \textbf{cmd} in the caller's scope, as resolved from namespace \textit{namespace}, with the supplied arguments. If \textit{namespace} does not exist, the command returns an error.

This TIP also proposes a new command:

\begin{quote}
\textbf{invoke} \textit{level} \textit{cmd} ?\textit{arg} ...?
\end{quote}

This invokes the command \textit{cmd} in level \textit{level} with the supplied \textit{arg}uments. The syntax of \textit{level} is the same as that required by \textbf{uplevel}.

\section{Rationale}

There is currently no script-level equivalent to \textit{Tcl\_EvalObjv()}, though the functionality is provided by one of:
\begingroup\small\begin{verbatim}
   eval [list cmd ?arg ...?]
   {*}[list cmd ?arg ...?]
\end{verbatim}
\endgroup

Note that the core tries to optimise the first case, but has to be careful to only avoid reparsing when it is guaranteed safe to do so. The notation is rather clumsy too.

The proposed new commands try to improve this situation, with the added functionality of determining the namespace in which the command name is to be resolved (functionality which was very difficult to use previously using the script-level API). In this manner it is possible for the invocation to make good use of \textbf{namespace path} and \textbf{namespace unknown} features.

The new command \textbf{invoke} could be implemented as:
\begingroup\small\begin{verbatim}
   proc invoke {level args} {
       if {[llength $args] == 0} {
           return -code error SomeMessage
       }
       if {[string is integer $level] && ($level >= 0)} {
           incr level
       }
       uplevel $level $args
   }]
\end{verbatim}
\endgroup

\section{Reference Implementation and Documentation}

[RFE 1577324] (which depends on [Patch 1577278]) provides an implementation of \textbf{namespace invoke}. [\url{https://sourceforge.net/support/tracker.php?aid=1577324}] [\url{https://sourceforge.net/support/tracker.php?aid=1577278}]

\section{Differences to Other Commands}
\begin{enumerate}
\item{}
Both these commands perform command invocation, as opposed to the script evaluation done by \textbf{eval}, \textbf{uplevel}, \textbf{namespace eval} and \textbf{namespace inscope}
\item{}
\textbf{namespace inscope} does a magic expansion of the first argument, \textbf{namespace invoke} takes the first argument as a command name. In other words, \textbf{namespace inscope} can be used with a command prefix. \textit{Feedback on the semantics suggest that this is a worthy feature, very useful for packing up command prefixes. This tip may yet be revised or withdrawn to take that into consideration.}
\item{}
Both \textbf{namespace eval} and \textbf{namespace inscope} add a call frame,\textbf{namespace invoke} does not --- it invokes in the caller's frame.
\end{enumerate}

\section{Sample Usage}

In tcllib's \textbf{::math::calculus::romberg} we see (edited for brevity):
\begingroup\small\begin{verbatim}
    # Replace f with a context-independent version

    set fqname [uplevel 1 [list namespace which [lindex $f 0]]]
    set f [lreplace $f 0 0 $fqname]
    ...
    set cmd $f
    lappend cmd [expr {0.5 * ($a + $b)}]
    set v [eval $cmd]
\end{verbatim}
\endgroup

where the command name in the prefix \textit{f} is replaced with its fully qualified name. A further variable is lappended, and the result is sent to \textbf{eval}.

With \textbf{namespace invoke} and \textbf{invoke} this would be coded as:
\begingroup\small\begin{verbatim}
    set ns [invoke 1 namespace current]
    set f [list namespace invoke $ns {*}$f]
    ...
    set v [{*}$f [expr {0.5 * ($a + $b)}]]
\end{verbatim}
\endgroup

If both new commands took the \textit{cmd} argument as a prefix to be expanded (as suggested by some early commenters), it would be even nicer for this usage:
\begingroup\small\begin{verbatim}
    set ns [invoke 1 [list namespace current]]
    set f [list namespace invoke $ns $f]
    ...
    set v [invoke 0 $f [expr {0.5 * ($a + $b)}]]
\end{verbatim}
\endgroup

The same thing (with slightly different semantics and a performance cost due to script evaluation instead of command invocation) could be obtained today by doing:
\begingroup\small\begin{verbatim}
    set f [uplevel 1 [list namespace code [list uplevel 1 $f]]]
    ...
    set v [eval [lappend f [expr {0.5 * ($a + $b)}]]]
\end{verbatim}
\endgroup

In order to fully reproduce the semantics and performance it would have to be:
\begingroup\small\begin{verbatim}
    set f [uplevel 1 [list namespace code [list uplevel 1 $f]]]
    ...
    lset f end end [linsert [lindex $f end end] end [expr {0.5 * ($a + $b)}]]  
    set v [eval $f]
\end{verbatim}
\endgroup

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

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