- moved is_of_type and friend macros into utils.h so they can be phased
[ginac.git] / ginac / function.pl
1 $maxargs=13;
2
3 sub generate_seq {
4         my ($seq_template,$n)=@_;
5         my ($res,$N);
6         
7         $res='';
8         for ($N=1; $N<=$n; $N++) {
9                 $res .= eval('"' . $seq_template . '"');
10                 if ($N!=$n) {
11                         $res .= ', ';
12                 }
13         }
14         return $res;
15 }
16
17 sub generate_from_to {
18         my ($template,$seq_template1,$seq_template2,$seq_template3,$from,$to)=@_;
19         my ($res,$N,$SEQ);
20
21         $res='';
22         for ($N=$from; $N<=$to; $N++) {
23                 $SEQ1=generate_seq($seq_template1,$N);
24                 $SEQ2=generate_seq($seq_template2,$N);
25                 $SEQ3=generate_seq($seq_template3,$N);
26                 $res .= eval('"' . $template . '"');
27                 $SEQ1=''; # to avoid main::SEQ1 used only once warning
28                 $SEQ2=''; # same as above
29                 $SEQ3=''; # same as above
30         }
31         return $res;
32 }
33
34 sub generate {
35         my ($template,$seq_template1,$seq_template2,$seq_template3)=@_;
36         return generate_from_to($template,$seq_template1,$seq_template2,$seq_template3,1,$maxargs);
37 }
38
39 $declare_function_macro = generate(
40         <<'END_OF_DECLARE_FUNCTION_MACRO','typename T${N}','const T${N} & p${N}','GiNaC::ex(p${N})');
41 #define DECLARE_FUNCTION_${N}P(NAME) \\
42 extern const unsigned function_index_##NAME; \\
43 template<${SEQ1}> \\
44 inline const GiNaC::function NAME(${SEQ2}) { \\
45         return GiNaC::function(function_index_##NAME, ${SEQ3}); \\
46 }
47
48 END_OF_DECLARE_FUNCTION_MACRO
49
50 $typedef_eval_funcp=generate(
51 'typedef ex (* eval_funcp_${N})(${SEQ1});'."\n",
52 'const ex &','','');
53
54 $typedef_evalf_funcp=generate(
55 'typedef ex (* evalf_funcp_${N})(${SEQ1});'."\n",
56 'const ex &','','');
57
58 $typedef_derivative_funcp=generate(
59 'typedef ex (* derivative_funcp_${N})(${SEQ1}, unsigned);'."\n",
60 'const ex &','','');
61
62 $typedef_series_funcp=generate(
63 'typedef ex (* series_funcp_${N})(${SEQ1}, const relational &, int, unsigned);'."\n",
64 'const ex &','','');
65
66 $eval_func_interface=generate('    function_options & eval_func(eval_funcp_${N} e);'."\n",'','','');
67
68 $evalf_func_interface=generate('    function_options & evalf_func(evalf_funcp_${N} ef);'."\n",'','','');
69
70 $derivative_func_interface=generate('    function_options & derivative_func(derivative_funcp_${N} d);'."\n",'','','');
71
72 $series_func_interface=generate('    function_options & series_func(series_funcp_${N} s);'."\n",'','','');
73
74 $constructors_interface=generate(
75 '    function(unsigned ser, ${SEQ1});'."\n",
76 'const ex & param${N}','','');
77
78 $constructors_implementation=generate(
79         <<'END_OF_CONSTRUCTORS_IMPLEMENTATION','const ex & param${N}','param${N}','');
80 function::function(unsigned ser, ${SEQ1})
81         : exprseq(${SEQ2}), serial(ser)
82 {
83         debugmsg(\"function ctor from unsigned,${N}*ex\",LOGLEVEL_CONSTRUCT);
84         tinfo_key = TINFO_function;
85 }
86 END_OF_CONSTRUCTORS_IMPLEMENTATION
87
88 $eval_switch_statement=generate(
89         <<'END_OF_EVAL_SWITCH_STATEMENT','seq[${N}-1]','','');
90         case ${N}:
91                 eval_result = ((eval_funcp_${N})(registered_functions()[serial].eval_f))(${SEQ1});
92                 break;
93 END_OF_EVAL_SWITCH_STATEMENT
94
95 $evalf_switch_statement=generate(
96         <<'END_OF_EVALF_SWITCH_STATEMENT','eseq[${N}-1]','','');
97         case ${N}:
98                 return ((evalf_funcp_${N})(registered_functions()[serial].evalf_f))(${SEQ1});
99 END_OF_EVALF_SWITCH_STATEMENT
100
101 $diff_switch_statement=generate(
102         <<'END_OF_DIFF_SWITCH_STATEMENT','seq[${N}-1]','','');
103         case ${N}:
104                 return ((derivative_funcp_${N})(registered_functions()[serial].derivative_f))(${SEQ1},diff_param);
105 END_OF_DIFF_SWITCH_STATEMENT
106
107 $series_switch_statement=generate(
108         <<'END_OF_SERIES_SWITCH_STATEMENT','seq[${N}-1]','','');
109         case ${N}:
110                 try {
111                         res = ((series_funcp_${N})(registered_functions()[serial].series_f))(${SEQ1},r,order,options);
112                 } catch (do_taylor) {
113                         res = basic::series(r, order, options);
114                 }
115                 return res;
116 END_OF_SERIES_SWITCH_STATEMENT
117
118 $eval_func_implementation=generate(
119         <<'END_OF_EVAL_FUNC_IMPLEMENTATION','','','');
120 function_options & function_options::eval_func(eval_funcp_${N} e)
121 {
122         test_and_set_nparams(${N});
123         eval_f = eval_funcp(e);
124         return *this;
125 }
126 END_OF_EVAL_FUNC_IMPLEMENTATION
127
128 $evalf_func_implementation=generate(
129         <<'END_OF_EVALF_FUNC_IMPLEMENTATION','','','');
130 function_options & function_options::evalf_func(evalf_funcp_${N} ef)
131 {
132         test_and_set_nparams(${N});
133         evalf_f = evalf_funcp(ef);
134         return *this;
135 }
136 END_OF_EVALF_FUNC_IMPLEMENTATION
137
138 $derivative_func_implementation=generate(
139         <<'END_OF_DERIVATIVE_FUNC_IMPLEMENTATION','','','');
140 function_options & function_options::derivative_func(derivative_funcp_${N} d)
141 {
142         test_and_set_nparams(${N});
143         derivative_f = derivative_funcp(d);
144         return *this;
145 }
146 END_OF_DERIVATIVE_FUNC_IMPLEMENTATION
147
148 $series_func_implementation=generate(
149         <<'END_OF_SERIES_FUNC_IMPLEMENTATION','','','');
150 function_options & function_options::series_func(series_funcp_${N} s)
151 {
152         test_and_set_nparams(${N});
153         series_f = series_funcp(s);
154         return *this;
155 }
156 END_OF_SERIES_FUNC_IMPLEMENTATION
157
158 $interface=<<END_OF_INTERFACE;
159 /** \@file function.h
160  *
161  *  Interface to class of symbolic functions. */
162
163 /*
164  *  This file was generated automatically by function.pl.
165  *  Please do not modify it directly, edit the perl script instead!
166  *  function.pl options: \$maxargs=${maxargs}
167  *
168  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
169  *
170  *  This program is free software; you can redistribute it and/or modify
171  *  it under the terms of the GNU General Public License as published by
172  *  the Free Software Foundation; either version 2 of the License, or
173  *  (at your option) any later version.
174  *
175  *  This program is distributed in the hope that it will be useful,
176  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
177  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
178  *  GNU General Public License for more details.
179  *
180  *  You should have received a copy of the GNU General Public License
181  *  along with this program; if not, write to the Free Software
182  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
183  */
184
185 #ifndef __GINAC_FUNCTION_H__
186 #define __GINAC_FUNCTION_H__
187
188 #include <string>
189 #include <vector>
190
191 // CINT needs <algorithm> to work properly with <vector>
192 #include <algorithm>
193
194 #include "exprseq.h"
195
196 // the following lines have been generated for max. ${maxargs} parameters
197 $declare_function_macro
198 // end of generated lines
199
200 #define REGISTER_FUNCTION(NAME,OPT) \\
201 const unsigned function_index_##NAME= \\
202         GiNaC::function::register_new(GiNaC::function_options(#NAME).OPT);
203
204 // The TYPECHECK-macros were used inside the _evalf() functions.  They are
205 // considered obsolete now:  (FIXME: remove them)
206
207 #define BEGIN_TYPECHECK \\
208 bool automatic_typecheck=true;
209
210 #define TYPECHECK(VAR,TYPE) \\
211 if (!is_exactly_a<TYPE>(VAR)) { \\
212         automatic_typecheck=false; \\
213 } else
214
215 #define TYPECHECK_INTEGER(VAR) \\
216 if (!(VAR).info(GiNaC::info_flags::integer)) { \\
217         automatic_typecheck=false; \\
218 } else
219
220 #define END_TYPECHECK(RV) \\
221 {} \\
222 if (!automatic_typecheck) { \\
223         return RV.hold(); \\
224 }
225
226 namespace GiNaC {
227
228 class function;
229 class symmetry;
230
231 typedef ex (* eval_funcp)();
232 typedef ex (* evalf_funcp)();
233 typedef ex (* derivative_funcp)();
234 typedef ex (* series_funcp)();
235
236 // the following lines have been generated for max. ${maxargs} parameters
237 $typedef_eval_funcp
238 $typedef_evalf_funcp
239 $typedef_derivative_funcp
240 $typedef_series_funcp
241 // end of generated lines
242
243 class function_options
244 {
245         friend class function;
246         friend class fderivative;
247 public:
248         function_options();
249         function_options(std::string const & n, std::string const & tn=std::string());
250         ~function_options();
251         void initialize(void);
252         function_options & set_name(std::string const & n, std::string const & tn=std::string());
253         function_options & latex_name(std::string const & tn);
254 // the following lines have been generated for max. ${maxargs} parameters
255 $eval_func_interface
256 $evalf_func_interface
257 $derivative_func_interface
258 $series_func_interface
259 // end of generated lines
260         function_options & set_return_type(unsigned rt, unsigned rtt=0);
261         function_options & do_not_evalf_params(void);
262         function_options & remember(unsigned size, unsigned assoc_size=0,
263                                     unsigned strategy=remember_strategies::delete_never);
264         function_options & overloaded(unsigned o);
265         function_options & set_symmetry(const symmetry & s);
266         void test_and_set_nparams(unsigned n);
267         std::string get_name(void) const { return name; }
268         unsigned get_nparams(void) const { return nparams; }
269         bool has_derivative(void) const { return derivative_f != NULL; }
270
271 protected:
272         std::string name;
273         std::string TeX_name;
274
275         unsigned nparams;
276
277         eval_funcp eval_f;
278         evalf_funcp evalf_f;
279         derivative_funcp derivative_f;
280         series_funcp series_f;
281
282         bool evalf_params_first;
283
284         bool use_return_type;
285         unsigned return_type;
286         unsigned return_type_tinfo;
287
288         bool use_remember;
289         unsigned remember_size;
290         unsigned remember_assoc_size;
291         unsigned remember_strategy;
292
293         unsigned functions_with_same_name;
294
295         ex symtree;
296 };
297
298 /** The class function is used to implement builtin functions like sin, cos...
299         and user defined functions */
300 class function : public exprseq
301 {
302         GINAC_DECLARE_REGISTERED_CLASS(function, exprseq)
303
304         // CINT has a linking problem
305 #ifndef __MAKECINT__
306         friend void ginsh_get_ginac_functions(void);
307 #endif // def __MAKECINT__
308
309         friend class remember_table_entry;
310         // friend class remember_table_list;
311         // friend class remember_table;
312
313 // member functions
314
315         // other ctors
316 public:
317         function(unsigned ser);
318         // the following lines have been generated for max. ${maxargs} parameters
319 $constructors_interface
320         // end of generated lines
321         function(unsigned ser, const exprseq & es);
322         function(unsigned ser, const exvector & v, bool discardable = false);
323         function(unsigned ser, exvector * vp); // vp will be deleted
324
325         // functions overriding virtual functions from base classes
326 public:
327         void print(const print_context & c, unsigned level = 0) const;
328         unsigned precedence(void) const {return 70;}
329         int degree(const ex & s) const;
330         int ldegree(const ex & s) const;
331         ex coeff(const ex & s, int n = 1) const;
332         ex expand(unsigned options=0) const;
333         ex eval(int level=0) const;
334         ex evalf(int level=0) const;
335         unsigned calchash(void) const;
336         ex series(const relational & r, int order, unsigned options = 0) const;
337         ex thisexprseq(const exvector & v) const;
338         ex thisexprseq(exvector * vp) const;
339 protected:
340         ex derivative(const symbol & s) const;
341         bool is_equal_same_type(const basic & other) const;
342         bool match_same_type(const basic & other) const;
343         unsigned return_type(void) const;
344         unsigned return_type_tinfo(void) const;
345         
346         // new virtual functions which can be overridden by derived classes
347         // none
348         
349         // non-virtual functions in this class
350 protected:
351         ex pderivative(unsigned diff_param) const; // partial differentiation
352         static std::vector<function_options> & registered_functions(void);
353         bool lookup_remember_table(ex & result) const;
354         void store_remember_table(ex const & result) const;
355 public:
356         static unsigned register_new(function_options const & opt);
357         static unsigned find_function(const std::string &name, unsigned nparams);
358         unsigned get_serial(void) const {return serial;}
359         std::string get_name(void) const;
360         
361 // member variables
362
363 protected:
364         unsigned serial;
365 };
366
367 // utility functions/macros
368 /** Return the object of type function handled by an ex.
369  *  This is unsafe: you need to check the type first. */
370 inline const function &ex_to_function(const ex &e)
371 {
372         return static_cast<const function &>(*e.bp);
373 }
374
375 /** Specialization of is_exactly_a<function>(obj) for objects of type function. */
376 template<> inline bool is_exactly_a<function>(const basic & obj)
377 {
378         return obj.tinfo()==TINFO_function;
379 }
380
381 #define is_ex_the_function(OBJ, FUNCNAME) \\
382         (is_exactly_a<function>(OBJ) && static_cast<GiNaC::function *>(OBJ.bp)->get_serial() == function_index_##FUNCNAME)
383
384 } // namespace GiNaC
385
386 #endif // ndef __GINAC_FUNCTION_H__
387
388 END_OF_INTERFACE
389
390 $implementation=<<END_OF_IMPLEMENTATION;
391 /** \@file function.cpp
392  *
393  *  Implementation of class of symbolic functions. */
394
395 /*
396  *  This file was generated automatically by function.pl.
397  *  Please do not modify it directly, edit the perl script instead!
398  *  function.pl options: \$maxargs=${maxargs}
399  *
400  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
401  *
402  *  This program is free software; you can redistribute it and/or modify
403  *  it under the terms of the GNU General Public License as published by
404  *  the Free Software Foundation; either version 2 of the License, or
405  *  (at your option) any later version.
406  *
407  *  This program is distributed in the hope that it will be useful,
408  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
409  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
410  *  GNU General Public License for more details.
411  *
412  *  You should have received a copy of the GNU General Public License
413  *  along with this program; if not, write to the Free Software
414  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
415  */
416
417 #include <string>
418 #include <stdexcept>
419 #include <list>
420
421 #include "function.h"
422 #include "fderivative.h"
423 #include "ex.h"
424 #include "lst.h"
425 #include "symmetry.h"
426 #include "print.h"
427 #include "archive.h"
428 #include "inifcns.h"
429 #include "tostring.h"
430 #include "utils.h"
431 #include "debugmsg.h"
432 #include "remember.h"
433
434 namespace GiNaC {
435
436 //////////
437 // helper class function_options
438 //////////
439
440 function_options::function_options()
441 {
442         initialize();
443 }
444
445 function_options::function_options(std::string const & n, std::string const & tn)
446 {
447         initialize();
448         set_name(n,tn);
449 }
450
451 function_options::~function_options()
452 {
453         // nothing to clean up at the moment
454 }
455
456 void function_options::initialize(void)
457 {
458         set_name("unnamed_function","\\\\mbox{unnamed}");
459         nparams = 0;
460         eval_f = evalf_f = derivative_f = series_f = 0;
461         evalf_params_first = true;
462         use_return_type = false;
463         use_remember = false;
464         functions_with_same_name = 1;
465         symtree = 0;
466 }
467
468 function_options & function_options::set_name(std::string const & n,
469                                               std::string const & tn)
470 {
471         name=n;
472         if (tn==std::string())
473                 TeX_name = "\\\\mbox{"+name+"}";
474         else
475                 TeX_name = tn;
476         return *this;
477 }
478
479 function_options & function_options::latex_name(std::string const & tn)
480 {
481         TeX_name=tn;
482         return *this;
483 }
484
485 // the following lines have been generated for max. ${maxargs} parameters
486 $eval_func_implementation
487 $evalf_func_implementation
488 $derivative_func_implementation
489 $series_func_implementation
490 // end of generated lines
491
492 function_options & function_options::set_return_type(unsigned rt, unsigned rtt)
493 {
494         use_return_type = true;
495         return_type = rt;
496         return_type_tinfo = rtt;
497         return *this;
498 }
499
500 function_options & function_options::do_not_evalf_params(void)
501 {
502         evalf_params_first = false;
503         return *this;
504 }
505
506 function_options & function_options::remember(unsigned size,
507                                               unsigned assoc_size,
508                                               unsigned strategy)
509 {
510         use_remember = true;
511         remember_size = size;
512         remember_assoc_size = assoc_size;
513         remember_strategy = strategy;
514         return *this;
515 }
516
517 function_options & function_options::overloaded(unsigned o)
518 {
519         functions_with_same_name = o;
520         return *this;
521 }
522
523 function_options & function_options::set_symmetry(const symmetry & s)
524 {
525         symtree = s;
526         return *this;
527 }
528         
529 void function_options::test_and_set_nparams(unsigned n)
530 {
531         if (nparams==0) {
532                 nparams = n;
533         } else if (nparams!=n) {
534                 // we do not throw an exception here because this code is
535                 // usually executed before main(), so the exception could not
536                 // caught anyhow
537                 std::cerr << "WARNING: number of parameters ("
538                           << n << ") differs from number set before (" 
539                           << nparams << ")" << std::endl;
540         }
541 }
542
543 GINAC_IMPLEMENT_REGISTERED_CLASS(function, exprseq)
544
545 //////////
546 // default ctor, dtor, copy ctor assignment operator and helpers
547 //////////
548
549 // public
550
551 function::function() : serial(0)
552 {
553         debugmsg("function default ctor",LOGLEVEL_CONSTRUCT);
554         tinfo_key = TINFO_function;
555 }
556
557 // protected
558
559 void function::copy(const function & other)
560 {
561         inherited::copy(other);
562         serial = other.serial;
563 }
564
565 void function::destroy(bool call_parent)
566 {
567         if (call_parent)
568                 inherited::destroy(call_parent);
569 }
570
571 //////////
572 // other ctors
573 //////////
574
575 // public
576
577 function::function(unsigned ser) : serial(ser)
578 {
579         debugmsg("function ctor from unsigned",LOGLEVEL_CONSTRUCT);
580         tinfo_key = TINFO_function;
581 }
582
583 // the following lines have been generated for max. ${maxargs} parameters
584 $constructors_implementation
585 // end of generated lines
586
587 function::function(unsigned ser, const exprseq & es) : exprseq(es), serial(ser)
588 {
589         debugmsg("function ctor from unsigned,exprseq",LOGLEVEL_CONSTRUCT);
590         tinfo_key = TINFO_function;
591 }
592
593 function::function(unsigned ser, const exvector & v, bool discardable) 
594   : exprseq(v,discardable), serial(ser)
595 {
596         debugmsg("function ctor from string,exvector,bool",LOGLEVEL_CONSTRUCT);
597         tinfo_key = TINFO_function;
598 }
599
600 function::function(unsigned ser, exvector * vp) 
601   : exprseq(vp), serial(ser)
602 {
603         debugmsg("function ctor from unsigned,exvector *",LOGLEVEL_CONSTRUCT);
604         tinfo_key = TINFO_function;
605 }
606
607 //////////
608 // archiving
609 //////////
610
611 /** Construct object from archive_node. */
612 function::function(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
613 {
614         debugmsg("function ctor from archive_node", LOGLEVEL_CONSTRUCT);
615
616         // Find serial number by function name
617         std::string s;
618         if (n.find_string("name", s)) {
619                 unsigned int ser = 0;
620                 std::vector<function_options>::const_iterator i = registered_functions().begin(), iend = registered_functions().end();
621                 while (i != iend) {
622                         if (s == i->name) {
623                                 serial = ser;
624                                 return;
625                         }
626                         ++i; ++ser;
627                 }
628                 throw (std::runtime_error("unknown function '" + s + "' in archive"));
629         } else
630                 throw (std::runtime_error("unnamed function in archive"));
631 }
632
633 /** Unarchive the object. */
634 ex function::unarchive(const archive_node &n, const lst &sym_lst)
635 {
636         return (new function(n, sym_lst))->setflag(status_flags::dynallocated);
637 }
638
639 /** Archive the object. */
640 void function::archive(archive_node &n) const
641 {
642         inherited::archive(n);
643         GINAC_ASSERT(serial < registered_functions().size());
644         n.add_string("name", registered_functions()[serial].name);
645 }
646
647 //////////
648 // functions overriding virtual functions from base classes
649 //////////
650
651 // public
652
653 void function::print(const print_context & c, unsigned level) const
654 {
655         debugmsg("function print", LOGLEVEL_PRINT);
656
657         GINAC_ASSERT(serial<registered_functions().size());
658
659         if (is_of_type(c, print_tree)) {
660
661                 c.s << std::string(level, ' ') << class_name() << " "
662                     << registered_functions()[serial].name
663                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
664                     << ", nops=" << nops()
665                     << std::endl;
666                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
667                 for (unsigned i=0; i<seq.size(); ++i)
668                         seq[i].print(c, level + delta_indent);
669                 c.s << std::string(level + delta_indent, ' ') << "=====" << std::endl;
670
671         } else if (is_of_type(c, print_csrc)) {
672
673                 // Print function name in lowercase
674                 std::string lname = registered_functions()[serial].name;
675                 unsigned num = lname.size();
676                 for (unsigned i=0; i<num; i++)
677                         lname[i] = tolower(lname[i]);
678                 c.s << lname << "(";
679
680                 // Print arguments, separated by commas
681                 exvector::const_iterator it = seq.begin(), itend = seq.end();
682                 while (it != itend) {
683                         it->print(c);
684                         ++it;
685                         if (it != itend)
686                                 c.s << ",";
687                 }
688                 c.s << ")";
689
690         } else if (is_of_type(c, print_latex)) {
691                 c.s << registered_functions()[serial].TeX_name;
692                 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
693         } else {
694                 c.s << registered_functions()[serial].name;
695                 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
696         }
697 }
698
699 ex function::expand(unsigned options) const
700 {
701         // Only expand arguments when asked to do so
702         if (options & expand_options::expand_function_args)
703                 return inherited::expand(options);
704         else
705                 return (options == 0) ? setflag(status_flags::expanded) : *this;
706 }
707
708 int function::degree(const ex & s) const
709 {
710         return is_equal(*s.bp) ? 1 : 0;
711 }
712
713 int function::ldegree(const ex & s) const
714 {
715         return is_equal(*s.bp) ? 1 : 0;
716 }
717
718 ex function::coeff(const ex & s, int n) const
719 {
720         if (is_equal(*s.bp))
721                 return n==1 ? _ex1() : _ex0();
722         else
723                 return n==0 ? ex(*this) : _ex0();
724 }
725
726 ex function::eval(int level) const
727 {
728         GINAC_ASSERT(serial<registered_functions().size());
729
730         if (level>1) {
731                 // first evaluate children, then we will end up here again
732                 return function(serial,evalchildren(level));
733         }
734
735         const function_options &opt = registered_functions()[serial];
736
737         // Canonicalize argument order according to the symmetry properties
738         if (seq.size() > 1 && !(opt.symtree.is_zero())) {
739                 exvector v = seq;
740                 GINAC_ASSERT(is_a<symmetry>(opt.symtree));
741                 int sig = canonicalize(v.begin(), ex_to<symmetry>(opt.symtree));
742                 if (sig != INT_MAX) {
743                         // Something has changed while sorting arguments, more evaluations later
744                         if (sig == 0)
745                                 return _ex0();
746                         return ex(sig) * thisexprseq(v);
747                 }
748         }
749
750         if (opt.eval_f==0) {
751                 return this->hold();
752         }
753
754         bool use_remember = opt.use_remember;
755         ex eval_result;
756         if (use_remember && lookup_remember_table(eval_result)) {
757                 return eval_result;
758         }
759
760         switch (opt.nparams) {
761                 // the following lines have been generated for max. ${maxargs} parameters
762 ${eval_switch_statement}
763                 // end of generated lines
764         default:
765                 throw(std::logic_error("function::eval(): invalid nparams"));
766         }
767         if (use_remember) {
768                 store_remember_table(eval_result);
769         }
770         return eval_result;
771 }
772
773 ex function::evalf(int level) const
774 {
775         GINAC_ASSERT(serial<registered_functions().size());
776
777         // Evaluate children first
778         exvector eseq;
779         if (level == 1)
780                 eseq = seq;
781         else if (level == -max_recursion_level)
782                 throw(std::runtime_error("max recursion level reached"));
783         else
784                 eseq.reserve(seq.size());
785         --level;
786         exvector::const_iterator it = seq.begin(), itend = seq.end();
787         while (it != itend) {
788                 eseq.push_back(it->evalf(level));
789                 ++it;
790         }
791         
792         if (registered_functions()[serial].evalf_f==0) {
793                 return function(serial,eseq).hold();
794         }
795         switch (registered_functions()[serial].nparams) {
796                 // the following lines have been generated for max. ${maxargs} parameters
797 ${evalf_switch_statement}
798                 // end of generated lines
799         }
800         throw(std::logic_error("function::evalf(): invalid nparams"));
801 }
802
803 unsigned function::calchash(void) const
804 {
805         unsigned v = golden_ratio_hash(golden_ratio_hash(tinfo()) ^ serial);
806         for (unsigned i=0; i<nops(); i++) {
807                 v = rotate_left_31(v);
808                 v ^= this->op(i).gethash();
809         }
810         v &= 0x7FFFFFFFU;
811         if (flags & status_flags::evaluated) {
812                 setflag(status_flags::hash_calculated);
813                 hashvalue = v;
814         }
815         return v;
816 }
817
818 ex function::thisexprseq(const exvector & v) const
819 {
820         return function(serial,v);
821 }
822
823 ex function::thisexprseq(exvector * vp) const
824 {
825         return function(serial,vp);
826 }
827
828 /** Implementation of ex::series for functions.
829  *  \@see ex::series */
830 ex function::series(const relational & r, int order, unsigned options) const
831 {
832         GINAC_ASSERT(serial<registered_functions().size());
833
834         if (registered_functions()[serial].series_f==0) {
835                 return basic::series(r, order);
836         }
837         ex res;
838         switch (registered_functions()[serial].nparams) {
839                 // the following lines have been generated for max. ${maxargs} parameters
840 ${series_switch_statement}
841                 // end of generated lines
842         }
843         throw(std::logic_error("function::series(): invalid nparams"));
844 }
845
846 // protected
847
848 /** Implementation of ex::diff() for functions. It applies the chain rule,
849  *  except for the Order term function.
850  *  \@see ex::diff */
851 ex function::derivative(const symbol & s) const
852 {
853         ex result;
854
855         if (serial == function_index_Order) {
856                 // Order Term function only differentiates the argument
857                 return Order(seq[0].diff(s));
858         } else {
859                 // Chain rule
860                 ex arg_diff;
861                 unsigned num = seq.size();
862                 for (unsigned i=0; i<num; i++) {
863                         arg_diff = seq[i].diff(s);
864                         // We apply the chain rule only when it makes sense.  This is not
865                         // just for performance reasons but also to allow functions to
866                         // throw when differentiated with respect to one of its arguments
867                         // without running into trouble with our automatic full
868                         // differentiation:
869                         if (!arg_diff.is_zero())
870                                 result += pderivative(i)*arg_diff;
871                 }
872         }
873         return result;
874 }
875
876 int function::compare_same_type(const basic & other) const
877 {
878         GINAC_ASSERT(is_of_type(other, function));
879         const function & o = static_cast<const function &>(other);
880
881         if (serial != o.serial)
882                 return serial < o.serial ? -1 : 1;
883         else
884                 return exprseq::compare_same_type(o);
885 }
886
887 bool function::is_equal_same_type(const basic & other) const
888 {
889         GINAC_ASSERT(is_of_type(other, function));
890         const function & o = static_cast<const function &>(other);
891
892         if (serial != o.serial)
893                 return false;
894         else
895                 return exprseq::is_equal_same_type(o);
896 }
897
898 bool function::match_same_type(const basic & other) const
899 {
900         GINAC_ASSERT(is_of_type(other, function));
901         const function & o = static_cast<const function &>(other);
902
903         return serial == o.serial;
904 }
905
906 unsigned function::return_type(void) const
907 {
908         if (seq.empty())
909                 return return_types::commutative;
910         else
911                 return seq.begin()->return_type();
912 }
913
914 unsigned function::return_type_tinfo(void) const
915 {
916         if (seq.empty())
917                 return tinfo_key;
918         else
919                 return seq.begin()->return_type_tinfo();
920 }
921
922 //////////
923 // new virtual functions which can be overridden by derived classes
924 //////////
925
926 // none
927
928 //////////
929 // non-virtual functions in this class
930 //////////
931
932 // protected
933
934 ex function::pderivative(unsigned diff_param) const // partial differentiation
935 {
936         GINAC_ASSERT(serial<registered_functions().size());
937         
938         // No derivative defined? Then return abstract derivative object
939         if (registered_functions()[serial].derivative_f == NULL)
940                 return fderivative(serial, diff_param, seq);
941
942         switch (registered_functions()[serial].nparams) {
943                 // the following lines have been generated for max. ${maxargs} parameters
944 ${diff_switch_statement}
945                 // end of generated lines
946         }
947         throw(std::logic_error("function::pderivative(): no diff function defined"));
948 }
949
950 std::vector<function_options> & function::registered_functions(void)
951 {
952         static std::vector<function_options> * rf = new std::vector<function_options>;
953         return *rf;
954 }
955
956 bool function::lookup_remember_table(ex & result) const
957 {
958         return remember_table::remember_tables()[serial].lookup_entry(*this,result);
959 }
960
961 void function::store_remember_table(ex const & result) const
962 {
963         remember_table::remember_tables()[serial].add_entry(*this,result);
964 }
965
966 // public
967
968 unsigned function::register_new(function_options const & opt)
969 {
970         unsigned same_name = 0;
971         for (unsigned i=0; i<registered_functions().size(); ++i) {
972                 if (registered_functions()[i].name==opt.name) {
973                         ++same_name;
974                 }
975         }
976         if (same_name>=opt.functions_with_same_name) {
977                 // we do not throw an exception here because this code is
978                 // usually executed before main(), so the exception could not
979                 // caught anyhow
980                 std::cerr << "WARNING: function name " << opt.name
981                           << " already in use!" << std::endl;
982         }
983         registered_functions().push_back(opt);
984         if (opt.use_remember) {
985                 remember_table::remember_tables().
986                         push_back(remember_table(opt.remember_size,
987                                                  opt.remember_assoc_size,
988                                                  opt.remember_strategy));
989         } else {
990                 remember_table::remember_tables().push_back(remember_table());
991         }
992         return registered_functions().size()-1;
993 }
994
995 /** Find serial number of function by name and number of parameters.
996  *  Throws exception if function was not found. */
997 unsigned function::find_function(const std::string &name, unsigned nparams)
998 {
999         std::vector<function_options>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
1000         unsigned serial = 0;
1001         while (i != end) {
1002                 if (i->get_name() == name && i->get_nparams() == nparams)
1003                         return serial;
1004                 ++i;
1005                 ++serial;
1006         }
1007         throw (std::runtime_error("no function '" + name + "' with " + ToString(nparams) + " parameters defined"));
1008 }
1009
1010 /** Return the print name of the function. */
1011 std::string function::get_name(void) const
1012 {
1013         GINAC_ASSERT(serial<registered_functions().size());
1014         return registered_functions()[serial].name;
1015 }
1016
1017 } // namespace GiNaC
1018
1019 END_OF_IMPLEMENTATION
1020
1021 print "Creating interface file function.h...";
1022 open OUT,">function.h" or die "cannot open function.h";
1023 print OUT $interface;
1024 close OUT;
1025 print "ok.\n";
1026
1027 print "Creating implementation file function.cpp...";
1028 open OUT,">function.cpp" or die "cannot open function.cpp";
1029 print OUT $implementation;
1030 close OUT;
1031 print "ok.\n";
1032
1033 print "done.\n";