Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

PATCH: zmathfuncdef and zsh/mathfunc



This patch extends zmathfuncdef (the front end to user-defined
mathematical functions) to load zsh/mathfunc if it looks like the
function will need it.

It does it by looking for the names of known functions and if it finds
them generating an autoload call to zsh/mathfunc for the function in
question.  This is as economical as possible in terms of library
loading.

For example, my definition

        zmathfuncdef ppm 'float(abs($1 - $2)) * 1e6 / $1 '

generates the autoloads (from zmodload -af)

        abs (zsh/mathfunc)
        float (zsh/mathfunc)

so that

        print $(( ppm(1, 1.00001) ))

will load zsh/mathfunc if it isn't already loaded and print 10 and a bit.


Index: Functions/Misc/zmathfuncdef
===================================================================
RCS file: /cvsroot/zsh/zsh/Functions/Misc/zmathfuncdef,v
retrieving revision 1.2
diff -u -r1.2 zmathfuncdef
--- Functions/Misc/zmathfuncdef	23 Apr 2006 22:47:04 -0000	1.2
+++ Functions/Misc/zmathfuncdef	2 Jun 2006 13:16:50 -0000
@@ -35,6 +35,32 @@
 
 functions -M $mname $iarg $ioptarg $fname || return 1
 
+# See if we need to autoload a math function from the standard
+# library.
+if ! zmodload -e zsh/mathfunc; then
+  local -a mathfuncs match mbegin mend loads
+  local mathfuncpat bodysearch
+
+  # generate pattern to match all known math functions
+  mathfuncs=(abs acos acosh asin asinh atan atanh cbrt ceil cos cosh erf erfc
+    exp expm1 fabs float floor gamma int j0 j1 lgamma log log10 log1p logb
+    sin sinh sqrt tan tanh y0 y1 signgam copysign fmod hypot nextafter jn yn
+    ldexp scalb rand48)
+  mathfuncpat="(${(j.|.)mathfuncs})"
+  bodysearch=$body
+  while [[ $bodysearch = (#b)(*[^[:alnum]]|)([[:alnum:]]##)\((*) ]]; do
+    # save worrying about search order...
+    bodysearch=$match[1]$match[3]
+    if [[ $match[2] = ${~mathfuncpat} ]]; then
+      # Uses function from math library.
+      loads+=($match[2])
+    fi
+  done
+  if (( ${#loads} )); then
+    zmodload -af zsh/mathfunc $loads
+  fi
+fi
+
 {
   eval "$fname() { (( $body )) }"
 } always {

-- 
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070


To access the latest news from CSR copy this link into a web browser:  http://www.csr.com/email_sig.php



Messages sorted by: Reverse Date, Date, Thread, Author