.\" t
.\" Note that this file *must* be preprocessed with tbl before being
.\" passed to *roff. Fail to do this and things will break...
.de Hl
.br
\l'\\n(.lu-\\n(.iu'
.sp
..
.TL
TIP #232: Creating New Math Functions for the 'expr' Command
.AU
Arjen Markus ,
Kevin Kenny
.DA "26 Nov 2004"
.AI
Tcl Core Team
.AB
This TIP proposes to replace Tcl's math functions, ordinarily created using the \fBTcl_CreateMathFunc()\fR function, with ordinary Tcl commands created in a known namespace, \fB::tcl::mathfunc\fR. This change has two chief motivations: it allows programmers to define new math functions at the Tcl level, and it encapsulates the \fBTcl_Value\fR API so that new math functions can work on data types that are not described adequately as \fBTcl_Value\fR objects.
.AE
.TS
box;
lb | lb.
TIP #232: Creating New Math Functions for the 'expr' Command
_
.T&
l | l.
Type: Project
State: Final
Vote: Done
Version: $Revision: 1.11 $
Tcl-Version: 8.5
Post-History:
Keywords: math expr Tcl
.TE
.1C
.NH 1
\fBRationale\fR
.LP
The two authors of this TIP, Kevin Kenny and Arjen Markus, have come at wanting the same change to Tcl from two distinct directions.
.LP
Arjen Markus has been the maintainer of several modules in Tcllib that implement "special functions" such as the exponential integral, the incomplete gamma function and the Bessel functions. He has wanted to have "scripted" math functions available to simplify his notation. In place of a complex expression like
.LD
\ \ set\ f\ [expr\ {\ $x*[J0\ $x]\ +\ [J1\ [expr\ {2.0*$x}]]\ }]
.DE
.LP
which is pretty unreadable (and prone to error because of the need to brace the subexpressions), he would like a mechanism for defining new mathematical functions so that he can write:
.LD
\ \ set\ f\ [expr\ {\ $x*J0($x)\ +\ J1(2.0*$x)\ }]
.DE
.LP
Donal Fellows has felt the need for such a construct, too, enough to implement a "funcproc" extension that provides it. [http://wiki.tcl.tk/541]
.LP
Kevin Kenny has come at the desire for rework of the math function mechanism from a different direction. He has been investigating Tcl Core support for arbitrary-precision integers [TIP #237], and discovered that implementing math functions that accept them as arguments or return them as results would require an incompatible change to the \fBTcl_Value\fR data type that is used to communicate with the math functions. When the last such change was made (in implementing 64-bit integers [TIP #72]), it required a source code change to several popular extensions that created new math functions \fImin\fR and \fImax\fR. Wishing the incompatibility introduced by [TIP #237] to be the last of the type, he decided to eliminate \fBTcl_Value\fR and use the open-ended \fBTcl_Obj\fR data type in its place. When he derived the type signature that a math function would have if it accepted its parameters in an array of \fBTcl_Obj\fR pointers, he discovered that it was identical to the \fBTcl_ObjCmdProc\fR -- making him ask, "what if math functions really \fIwere\fR commands?"
.LP
This TIP is the result of those two investigations, and proposes a unification of math functions with Tcl commands.
.NH 1
\fBProposed Changes\fR
.LP
This TIP proposes that:
.IP " 1: "
The [expr] command shall be modified so that an expression of the form:
.LD
\ \ \ f(arg1,arg2,...)
.DE
.QP
shall generate code equivalent to that generated by
.LD
\ \ \ [tcl::mathfunc::f\ [expr\ {\ arg1\ }]\ [expr\ {\ arg2\ }]\ ...]
.DE
.QP
so that math functions are interpreted as Tcl commands whose arguments are parsed as subexpressions. The existing code in [expr] that checks for correct argument counts to the math functions at compile time shall be removed (the general consensus among Core maintainers is that compile-time checks of this sort are a bad idea anyway).
.QP
Note that the call to \fItcl::mathfunc::f\fR has no leading namespace delimiter. A search for the function will try to resolve it first relative to the current namespace.
.IP " 2: "
The current math functions in Tcl shall be reimplemented as ordinary Tcl commands in the \fB::tcl::mathfunc\fR namespace; a Tcl interpreter will contain commands \fB::tcl::mathfunc::abs\fR, \fB::tcl::mathfunc::acos\fR, etc.
.IP " 3: "
The Tcl command [info functions] shall be deprecated in favor of searching for math functions using [info commands] in the appropriate namespace.
.IP " 4: "
The C functions \fBTcl_CreateMathFunc\fR, \fBTcl_GetMathFuncInfo\fR, and \fBTcl_ListMathFuncs\fR shall be deprecated in favor of \fBTcl_CreateObjCommand\fR, \fBTcl_GetCommandInfo\fR and [info commands]. (The last is provided only in Tcl at the present time; we do not export a C-level interface to enumerate commands in a namespace.) The functions will continue to work for extensions that use them. The \fBTcl_CreateMathFunc\fR command will create a Tcl command in the \fB::tcl::mathfunc\fR namespace whose command procedure checks argument count and types and dispatches to the math function handler. The \fBTcl_GetMathFuncInfo\fR procedure will return \fITCL_OK\fR or \fITCL_ERROR\fR according to whether the given math function exists in \fB::tcl::mathfunc\fR and will return parameter information for (only) those functions defined using \fBTcl_CreateMathFunc\fR. Functions defined as ordinary Tcl commands shall return \fITCL_OK\fR but have a parameter count of -1. The \fBTcl_ListMathFuncs\fR procedure will simply enumerate all the commands in the \fB::tcl::mathfunc\fR namespace.
.IP " 5: "
Several error messages change as a side effect of changing the math function implementation. All of the new messages are more informative than the old ones (for instance, identifying which math function encountered a parameter error rather than a generic "too few/too many arguments to math function"), with the exception of the error message for an unknown function, which is replaced with "unknown command ::tcl::mathfunc::" where is the name of the missing function.
.NH 1
\fBDiscussion\fR
.LP
The proposed change lifts several other restrictions in the way math functions operate:
.IP " 1: "
There is no longer any restriction that new math functions must accept a fixed number of arguments, or, indeed, that their arguments and results must be numeric. It will be possible to create variadic functions like:
.LD
\ \ \ proc\ ::tcl::mathfunc::min\ args\ {
\ \ \ \ \ \ \ set\ m\ Inf
\ \ \ \ \ \ \ foreach\ a\ $args\ {
\ \ \ \ \ \ \ \ \ \ \ if\ {\ $a\ <\ $m\ }\ {
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ set\ m\ $a
\ \ \ \ \ \ \ \ \ \ \ }
\ \ \ \ \ \ \ }
\ \ \ \ \ \ \ return\ $m
\ \ \ }
.DE
.IP " 2: "
It will be possible to compile Tcl code that refers to a math function that has not yet been defined. That is:
.LD
\ \ \ proc\ foo\ {\ x\ }\ {
\ \ \ \ \ \ \ set\ have_f\ [llength\ [info\ commands\ ::tcl::mathfunc::f]]
\ \ \ \ \ \ \ if\ {\ $have_f\ }\ {
\ \ \ \ \ \ \ \ \ \ \ return\ [expr\ {\ f($x)\ }]
\ \ \ \ \ \ \ }\ else\ {
\ \ \ \ \ \ \ \ \ \ \ ...\ fallback\ ...
\ \ \ \ \ \ \ }
\ \ \ }
.DE
.QP
will be a valid procedure. (In Tcl 8.4, the procedure will fail to compile if \fIf\fR is not known at compile time, something that runs contrary to the dynamic nature of Tcl.)
.IP " 3: "
Namespaces will be able to define their own math functions that are not visible outside those namespaces. If a namespace defines a function \fB[namespace current]::tcl::mathfunc::f\fR, then calls to \fBf\fR in expressions evaluated in that namespace will resolve to it in preference to \fB::tcl::mathfunc::f\fR. Not only does this rule allow two extensions both to define functions \fBf\fR without collision, but it also allows an extension to override a builtin function such as \fBsin\fR.
.LP
Alas, all these improvements come at some cost of performance. On Kevin Kenny's machine, the command
.LD
\ expr\ {sin(0.325)}
.DE
.LP
executes in roughly 520 nanoseconds before the change, and 870 nanoseconds afterward. Since the resolution of the function name is cached, name lookup is not the problem; rather, the issue is that invoking the function as a command needs to look for command traces; this whole mechanism costs about 300-350 ns (and has been observed to do so in other contexts). For real-life expressions, the additional cost tends to vanish quickly into statistical noise; variable access (with corresponding checks for traces) and bytecode overhead quickly comes to dominate the performance for all but the simplest expressions.
.NH 1
\fBSafe Interpreters\fR
.LP
It is not anticipated that exposing this functionality in a safe interpreter will present any new problems for safety. Any functionality that the interpreter can access by defining or overriding math functions is functionality that would have been available to it by calling the functions as commands.
.NH 1
\fBImpact on C-coded Extensions\fR
.LP
Extensions coded in C that wish to create math functions accepting parameters of type \fBTCL_EITHER\fR may find that they do not get type coercion from parameters of new numeric types, such as extended-precision integers. The coding change to replace them with Tcl commands is fairly easy and mechanical, at a level of effort comparable to that needed for [TIP #72]. Moreover, once it is completed, a math function will be using the known \fBTcl_CreateObjCmd\fR API, which has been stable since Tcl 8.0 and is unlikely to change substantially in future releases.
.LP
The \fItbcload\fR extension will need to implement a small amount of bytecode translation to preserve compatibility with bytecode compiled modules built against earlier versions of Tcl. The reason is that two bytecodes, \fBINST_INVOKE_BUILTIN1\fR and \fBINST_INVOKE_FUNC1\fR have been eliminated from \fBTcl_ExecuteByteCode\fR since the compiler no longer emits them. If this change for some reason should prove infeasible, we can always put the bytecodes back into \fBTcl_ExecuteByteCode\fR, but the authors of this TIP would prefer to avoid the code bloat.
.NH 1
\fBReference Implementation\fR
.LP
A reference implementation is committed on the 'tcl-numerics-branch' at SourceForge and may be retrieved with
.LD
\ cvs\ -d:ext:USERID@cvs.sourceforge.net:/cvsroot/tcl\ checkout\ -rTIP232\ tcl_numerics
.DE
.NH 1
\fBCopyright\fR
.LP
Copyright (c) 2005 by Kevin B. Kenny and Adriaan Markus. All rights reserved.
.LP
This document may be distributed subject to the terms and conditions set forth in the Open Publication License, version 1.0 [http://www.opencontent.org/openpub/].
.SH
Colophon
.LP
TIP AutoGenerator - written by Donal K. Fellows