e3c10f1e362797f1ff97189daaf658404de8d2f5
[ginac.git] / ginac / function.pl
1 #  This perl script automatically generates function.h and function.cpp
2
3 #  function.pl options: \$maxargs=${maxargs}
4
5 #  GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany
6
7 #  This program is free software; you can redistribute it and/or modify
8 #  it under the terms of the GNU General Public License as published by
9 #  the Free Software Foundation; either version 2 of the License, or
10 #  (at your option) any later version.
11
12 #  This program is distributed in the hope that it will be useful,
13 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #  GNU General Public License for more details.
16
17 #  You should have received a copy of the GNU General Public License
18 #  along with this program; if not, write to the Free Software
19 #  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20
21 $maxargs=14;
22
23 sub generate_seq {
24         my ($seq_template,$n)=@_;
25         my ($res,$N);
26         
27         $res='';
28         for ($N=1; $N<=$n; $N++) {
29                 $res .= eval('"' . $seq_template . '"');
30                 if ($N!=$n) {
31                         $res .= ', ';
32                 }
33         }
34         return $res;
35 }
36
37 sub generate_from_to {
38         my ($template,$seq_template1,$seq_template2,$seq_template3,$from,$to)=@_;
39         my ($res,$N,$SEQ);
40
41         $res='';
42         for ($N=$from; $N<=$to; $N++) {
43                 $SEQ1=generate_seq($seq_template1,$N);
44                 $SEQ2=generate_seq($seq_template2,$N);
45                 $SEQ3=generate_seq($seq_template3,$N);
46                 $res .= eval('"' . $template . '"');
47                 $SEQ1=''; # to avoid main::SEQ1 used only once warning
48                 $SEQ2=''; # same as above
49                 $SEQ3=''; # same as above
50         }
51         return $res;
52 }
53
54 sub generate {
55         my ($template,$seq_template1,$seq_template2,$seq_template3)=@_;
56         return generate_from_to($template,$seq_template1,$seq_template2,$seq_template3,1,$maxargs);
57 }
58
59 $declare_function_macro = generate(
60         <<'END_OF_DECLARE_FUNCTION_MACRO','typename T${N}','const T${N} & p${N}','GiNaC::ex(p${N})');
61 #define DECLARE_FUNCTION_${N}P(NAME) \\
62 class NAME##_SERIAL { public: static unsigned serial; }; \\
63 const unsigned NAME##_NPARAMS = ${N}; \\
64 template<${SEQ1}> const GiNaC::function NAME(${SEQ2}) { \\
65         return GiNaC::function(NAME##_SERIAL::serial, ${SEQ3}); \\
66 }
67
68 END_OF_DECLARE_FUNCTION_MACRO
69
70 $typedef_eval_funcp=generate(
71 'typedef ex (* eval_funcp_${N})(${SEQ1});'."\n",
72 'const ex &','','');
73
74 $typedef_evalf_funcp=generate(
75 'typedef ex (* evalf_funcp_${N})(${SEQ1});'."\n",
76 'const ex &','','');
77
78 $typedef_conjugate_funcp=generate(
79 'typedef ex (* conjugate_funcp_${N})(${SEQ1});'."\n",
80 'const ex &','','');
81
82 $typedef_derivative_funcp=generate(
83 'typedef ex (* derivative_funcp_${N})(${SEQ1}, unsigned);'."\n",
84 'const ex &','','');
85
86 $typedef_power_funcp=generate(
87 'typedef ex (* power_funcp_${N})(${SEQ1}, const ex &);'."\n",
88 'const ex &','','');
89
90 $typedef_series_funcp=generate(
91 'typedef ex (* series_funcp_${N})(${SEQ1}, const relational &, int, unsigned);'."\n",
92 'const ex &','','');
93
94 $typedef_print_funcp=generate(
95 'typedef void (* print_funcp_${N})(${SEQ1}, const print_context &);'."\n",
96 'const ex &','','');
97
98 $eval_func_interface=generate('    function_options & eval_func(eval_funcp_${N} e);'."\n",'','','');
99
100 $evalf_func_interface=generate('    function_options & evalf_func(evalf_funcp_${N} ef);'."\n",'','','');
101
102 $conjugate_func_interface=generate('    function_options & conjugate_func(conjugate_funcp_${N} d);'."\n",'','','');
103
104 $derivative_func_interface=generate('    function_options & derivative_func(derivative_funcp_${N} d);'."\n",'','','');
105
106 $power_func_interface=generate('    function_options & power_func(power_funcp_${N} d);'."\n",'','','');
107
108 $series_func_interface=generate('    function_options & series_func(series_funcp_${N} s);'."\n",'','','');
109
110 $print_func_interface=generate(
111         <<'END_OF_PRINT_FUNC_INTERFACE','','','');
112     template <class Ctx> function_options & print_func(print_funcp_${N} p)
113     {
114         test_and_set_nparams(${N});
115         set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p));
116         return *this;
117     }
118 END_OF_PRINT_FUNC_INTERFACE
119
120 $constructors_interface=generate(
121 '    function(unsigned ser, ${SEQ1});'."\n",
122 'const ex & param${N}','','');
123
124 $constructors_implementation=generate(
125         <<'END_OF_CONSTRUCTORS_IMPLEMENTATION','const ex & param${N}','param${N}','');
126 function::function(unsigned ser, ${SEQ1})
127         : exprseq(${SEQ2}), serial(ser)
128 {
129         tinfo_key = &function::tinfo_static;
130 }
131 END_OF_CONSTRUCTORS_IMPLEMENTATION
132
133 $eval_switch_statement=generate(
134         <<'END_OF_EVAL_SWITCH_STATEMENT','seq[${N}-1]','','');
135         case ${N}:
136                 eval_result = ((eval_funcp_${N})(opt.eval_f))(${SEQ1});
137                 break;
138 END_OF_EVAL_SWITCH_STATEMENT
139
140 $evalf_switch_statement=generate(
141         <<'END_OF_EVALF_SWITCH_STATEMENT','eseq[${N}-1]','','');
142         case ${N}:
143                 return ((evalf_funcp_${N})(opt.evalf_f))(${SEQ1});
144 END_OF_EVALF_SWITCH_STATEMENT
145
146 $conjugate_switch_statement=generate(
147         <<'END_OF_DIFF_SWITCH_STATEMENT','seq[${N}-1]','','');
148         case ${N}:
149                 return ((conjugate_funcp_${N})(opt.conjugate_f))(${SEQ1});
150 END_OF_DIFF_SWITCH_STATEMENT
151
152 $diff_switch_statement=generate(
153         <<'END_OF_DIFF_SWITCH_STATEMENT','seq[${N}-1]','','');
154         case ${N}:
155                 return ((derivative_funcp_${N})(opt.derivative_f))(${SEQ1},diff_param);
156 END_OF_DIFF_SWITCH_STATEMENT
157
158 $power_switch_statement=generate(
159         <<'END_OF_POWER_SWITCH_STATEMENT','seq[${N}-1]','','');
160         case ${N}:
161                 return ((power_funcp_${N})(opt.power_f))(${SEQ1},power_param);
162 END_OF_POWER_SWITCH_STATEMENT
163
164 $series_switch_statement=generate(
165         <<'END_OF_SERIES_SWITCH_STATEMENT','seq[${N}-1]','','');
166         case ${N}:
167                 try {
168                         res = ((series_funcp_${N})(opt.series_f))(${SEQ1},r,order,options);
169                 } catch (do_taylor) {
170                         res = basic::series(r, order, options);
171                 }
172                 return res;
173 END_OF_SERIES_SWITCH_STATEMENT
174
175 $print_switch_statement=generate(
176         <<'END_OF_PRINT_SWITCH_STATEMENT','seq[${N}-1]','','');
177                 case ${N}:
178                         ((print_funcp_${N})(pdt[id]))(${SEQ1}, c);
179                         break;
180 END_OF_PRINT_SWITCH_STATEMENT
181
182 $eval_func_implementation=generate(
183         <<'END_OF_EVAL_FUNC_IMPLEMENTATION','','','');
184 function_options & function_options::eval_func(eval_funcp_${N} e)
185 {
186         test_and_set_nparams(${N});
187         eval_f = eval_funcp(e);
188         return *this;
189 }
190 END_OF_EVAL_FUNC_IMPLEMENTATION
191
192 $evalf_func_implementation=generate(
193         <<'END_OF_EVALF_FUNC_IMPLEMENTATION','','','');
194 function_options & function_options::evalf_func(evalf_funcp_${N} ef)
195 {
196         test_and_set_nparams(${N});
197         evalf_f = evalf_funcp(ef);
198         return *this;
199 }
200 END_OF_EVALF_FUNC_IMPLEMENTATION
201
202 $conjugate_func_implementation=generate(
203         <<'END_OF_CONJUGATE_FUNC_IMPLEMENTATION','','','');
204 function_options & function_options::conjugate_func(conjugate_funcp_${N} c)
205 {
206         test_and_set_nparams(${N});
207         conjugate_f = conjugate_funcp(c);
208         return *this;
209 }
210 END_OF_CONJUGATE_FUNC_IMPLEMENTATION
211
212 $derivative_func_implementation=generate(
213         <<'END_OF_DERIVATIVE_FUNC_IMPLEMENTATION','','','');
214 function_options & function_options::derivative_func(derivative_funcp_${N} d)
215 {
216         test_and_set_nparams(${N});
217         derivative_f = derivative_funcp(d);
218         return *this;
219 }
220 END_OF_DERIVATIVE_FUNC_IMPLEMENTATION
221
222 $power_func_implementation=generate(
223         <<'END_OF_POWER_FUNC_IMPLEMENTATION','','','');
224 function_options & function_options::power_func(power_funcp_${N} d)
225 {
226         test_and_set_nparams(${N});
227         power_f = power_funcp(d);
228         return *this;
229 }
230 END_OF_POWER_FUNC_IMPLEMENTATION
231
232 $series_func_implementation=generate(
233         <<'END_OF_SERIES_FUNC_IMPLEMENTATION','','','');
234 function_options & function_options::series_func(series_funcp_${N} s)
235 {
236         test_and_set_nparams(${N});
237         series_f = series_funcp(s);
238         return *this;
239 }
240 END_OF_SERIES_FUNC_IMPLEMENTATION
241
242 $interface=<<END_OF_INTERFACE;
243 /** \@file function.h
244  *
245  *  Interface to class of symbolic functions. */
246
247 /*
248  *  This file was generated automatically by function.pl.
249  *  Please do not modify it directly, edit the perl script instead!
250  *  function.pl options: \$maxargs=${maxargs}
251  *
252  *  GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany
253  *
254  *  This program is free software; you can redistribute it and/or modify
255  *  it under the terms of the GNU General Public License as published by
256  *  the Free Software Foundation; either version 2 of the License, or
257  *  (at your option) any later version.
258  *
259  *  This program is distributed in the hope that it will be useful,
260  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
261  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
262  *  GNU General Public License for more details.
263  *
264  *  You should have received a copy of the GNU General Public License
265  *  along with this program; if not, write to the Free Software
266  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
267  */
268
269 #ifndef __GINAC_FUNCTION_H__
270 #define __GINAC_FUNCTION_H__
271
272 #include <string>
273 #include <vector>
274
275 // CINT needs <algorithm> to work properly with <vector>
276 #include <algorithm>
277
278 #include "exprseq.h"
279
280 // the following lines have been generated for max. ${maxargs} parameters
281 $declare_function_macro
282 // end of generated lines
283
284 #define REGISTER_FUNCTION(NAME,OPT) \\
285 unsigned NAME##_SERIAL::serial = \\
286         GiNaC::function::register_new(GiNaC::function_options(#NAME, NAME##_NPARAMS).OPT);
287
288 namespace GiNaC {
289
290 class function;
291 class symmetry;
292
293 typedef ex (* eval_funcp)();
294 typedef ex (* evalf_funcp)();
295 typedef ex (* conjugate_funcp)();
296 typedef ex (* derivative_funcp)();
297 typedef ex (* power_funcp)();
298 typedef ex (* series_funcp)();
299 typedef void (* print_funcp)();
300
301 // the following lines have been generated for max. ${maxargs} parameters
302 $typedef_eval_funcp
303 $typedef_evalf_funcp
304 $typedef_conjugate_funcp
305 $typedef_derivative_funcp
306 $typedef_power_funcp
307 $typedef_series_funcp
308 $typedef_print_funcp
309 // end of generated lines
310
311 // Alternatively, an exvector may be passed into the static function, instead
312 // of individual ex objects.  Then, the number of arguments is not limited.
313 typedef ex (* eval_funcp_exvector)(const exvector &);
314 typedef ex (* evalf_funcp_exvector)(const exvector &);
315 typedef ex (* conjugate_funcp_exvector)(const exvector &);
316 typedef ex (* derivative_funcp_exvector)(const exvector &, unsigned);
317 typedef ex (* power_funcp_exvector)(const exvector &, const ex &);
318 typedef ex (* series_funcp_exvector)(const exvector &, const relational &, int, unsigned);
319 typedef void (* print_funcp_exvector)(const exvector &, const print_context &);
320
321
322 class function_options
323 {
324         friend class function;
325         friend class fderivative;
326 public:
327         function_options();
328         function_options(std::string const & n, std::string const & tn=std::string());
329         function_options(std::string const & n, unsigned np);
330         ~function_options();
331         void initialize();
332
333         function_options & dummy() { return *this; }
334         function_options & set_name(std::string const & n, std::string const & tn=std::string());
335         function_options & latex_name(std::string const & tn);
336 // the following lines have been generated for max. ${maxargs} parameters
337 $eval_func_interface
338 $evalf_func_interface
339 $conjugate_func_interface
340 $derivative_func_interface
341 $power_func_interface
342 $series_func_interface
343 $print_func_interface
344 // end of generated lines
345         function_options & eval_func(eval_funcp_exvector e);
346         function_options & evalf_func(evalf_funcp_exvector ef);
347         function_options & conjugate_func(conjugate_funcp_exvector d);
348         function_options & derivative_func(derivative_funcp_exvector d);
349         function_options & power_func(power_funcp_exvector d);
350         function_options & series_func(series_funcp_exvector s);
351
352         template <class Ctx> function_options & print_func(print_funcp_exvector p)
353         {
354                 print_use_exvector_args = true;
355                 set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p));
356                 return *this;
357         }
358
359         function_options & set_return_type(unsigned rt, tinfo_t rtt=NULL);
360         function_options & do_not_evalf_params();
361         function_options & remember(unsigned size, unsigned assoc_size=0,
362                                     unsigned strategy=remember_strategies::delete_never);
363         function_options & overloaded(unsigned o);
364         function_options & set_symmetry(const symmetry & s);
365
366         std::string get_name() const { return name; }
367         unsigned get_nparams() const { return nparams; }
368
369 protected:
370         bool has_derivative() const { return derivative_f != NULL; }
371         bool has_power() const { return power_f != NULL; }
372         void test_and_set_nparams(unsigned n);
373         void set_print_func(unsigned id, print_funcp f);
374
375         std::string name;
376         std::string TeX_name;
377
378         unsigned nparams;
379
380         eval_funcp eval_f;
381         evalf_funcp evalf_f;
382         conjugate_funcp conjugate_f;
383         derivative_funcp derivative_f;
384         power_funcp power_f;
385         series_funcp series_f;
386         std::vector<print_funcp> print_dispatch_table;
387
388         bool evalf_params_first;
389
390         bool use_return_type;
391         unsigned return_type;
392         tinfo_t return_type_tinfo;
393
394         bool use_remember;
395         unsigned remember_size;
396         unsigned remember_assoc_size;
397         unsigned remember_strategy;
398
399         bool eval_use_exvector_args;
400         bool evalf_use_exvector_args;
401         bool conjugate_use_exvector_args;
402         bool derivative_use_exvector_args;
403         bool power_use_exvector_args;
404         bool series_use_exvector_args;
405         bool print_use_exvector_args;
406
407         unsigned functions_with_same_name;
408
409         ex symtree;
410 };
411
412
413 /** Exception class thrown by classes which provide their own series expansion
414  *  to signal that ordinary Taylor expansion is safe. */
415 class do_taylor {};
416
417
418 /** The class function is used to implement builtin functions like sin, cos...
419         and user defined functions */
420 class function : public exprseq
421 {
422         GINAC_DECLARE_REGISTERED_CLASS(function, exprseq)
423
424         // CINT has a linking problem
425 #ifndef __MAKECINT__
426         friend void ginsh_get_ginac_functions();
427 #endif // def __MAKECINT__
428
429         friend class remember_table_entry;
430         // friend class remember_table_list;
431         // friend class remember_table;
432
433 // member functions
434
435         // other constructors
436 public:
437         function(unsigned ser);
438         // the following lines have been generated for max. ${maxargs} parameters
439 $constructors_interface
440         // end of generated lines
441         function(unsigned ser, const exprseq & es);
442         function(unsigned ser, const exvector & v, bool discardable = false);
443         function(unsigned ser, std::auto_ptr<exvector> vp);
444
445         // functions overriding virtual functions from base classes
446 public:
447         void print(const print_context & c, unsigned level = 0) const;
448         unsigned precedence() const {return 70;}
449         ex expand(unsigned options=0) const;
450         ex eval(int level=0) const;
451         ex evalf(int level=0) const;
452         unsigned calchash() const;
453         ex series(const relational & r, int order, unsigned options = 0) const;
454         ex thiscontainer(const exvector & v) const;
455         ex thiscontainer(std::auto_ptr<exvector> vp) const;
456         ex conjugate() const;
457 protected:
458         ex derivative(const symbol & s) const;
459         bool is_equal_same_type(const basic & other) const;
460         bool match_same_type(const basic & other) const;
461         unsigned return_type() const;
462         tinfo_t return_type_tinfo() const;
463         
464         // new virtual functions which can be overridden by derived classes
465         // none
466         
467         // non-virtual functions in this class
468 protected:
469         ex pderivative(unsigned diff_param) const; // partial differentiation
470         static std::vector<function_options> & registered_functions();
471         bool lookup_remember_table(ex & result) const;
472         void store_remember_table(ex const & result) const;
473 public:
474         ex power(const ex & exp) const;
475         static unsigned register_new(function_options const & opt);
476         static unsigned current_serial;
477         static unsigned find_function(const std::string &name, unsigned nparams);
478         unsigned get_serial() const {return serial;}
479         std::string get_name() const;
480
481 // member variables
482
483 protected:
484         unsigned serial;
485 };
486
487 // utility functions/macros
488
489 template <typename T>
490 inline bool is_the_function(const ex & x)
491 {
492         return is_exactly_a<function>(x)
493             && ex_to<function>(x).get_serial() == T::serial;
494 }
495
496 // Check whether OBJ is the specified symbolic function.
497 #define is_ex_the_function(OBJ, FUNCNAME) (GiNaC::is_the_function<FUNCNAME##_SERIAL>(OBJ))
498
499 } // namespace GiNaC
500
501 #endif // ndef __GINAC_FUNCTION_H__
502
503 END_OF_INTERFACE
504
505 $implementation=<<END_OF_IMPLEMENTATION;
506 /** \@file function.cpp
507  *
508  *  Implementation of class of symbolic functions. */
509
510 /*
511  *  This file was generated automatically by function.pl.
512  *  Please do not modify it directly, edit the perl script instead!
513  *  function.pl options: \$maxargs=${maxargs}
514  *
515  *  GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany
516  *
517  *  This program is free software; you can redistribute it and/or modify
518  *  it under the terms of the GNU General Public License as published by
519  *  the Free Software Foundation; either version 2 of the License, or
520  *  (at your option) any later version.
521  *
522  *  This program is distributed in the hope that it will be useful,
523  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
524  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
525  *  GNU General Public License for more details.
526  *
527  *  You should have received a copy of the GNU General Public License
528  *  along with this program; if not, write to the Free Software
529  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
530  */
531
532 #include <iostream>
533 #include <string>
534 #include <stdexcept>
535 #include <list>
536
537 #include "function.h"
538 #include "operators.h"
539 #include "fderivative.h"
540 #include "ex.h"
541 #include "lst.h"
542 #include "symmetry.h"
543 #include "print.h"
544 #include "power.h"
545 #include "archive.h"
546 #include "inifcns.h"
547 #include "tostring.h"
548 #include "utils.h"
549 #include "remember.h"
550
551 namespace GiNaC {
552
553 //////////
554 // helper class function_options
555 //////////
556
557 function_options::function_options()
558 {
559         initialize();
560 }
561
562 function_options::function_options(std::string const & n, std::string const & tn)
563 {
564         initialize();
565         set_name(n, tn);
566 }
567
568 function_options::function_options(std::string const & n, unsigned np)
569 {
570         initialize();
571         set_name(n, std::string());
572         nparams = np;
573 }
574
575 function_options::~function_options()
576 {
577         // nothing to clean up at the moment
578 }
579
580 void function_options::initialize()
581 {
582         set_name("unnamed_function", "\\\\mbox{unnamed}");
583         nparams = 0;
584         eval_f = evalf_f = conjugate_f = derivative_f = power_f = series_f = 0;
585         evalf_params_first = true;
586         use_return_type = false;
587         eval_use_exvector_args = false;
588         evalf_use_exvector_args = false;
589         conjugate_use_exvector_args = false;
590         derivative_use_exvector_args = false;
591         power_use_exvector_args = false;
592         series_use_exvector_args = false;
593         print_use_exvector_args = false;
594         use_remember = false;
595         functions_with_same_name = 1;
596         symtree = 0;
597 }
598
599 function_options & function_options::set_name(std::string const & n,
600                                               std::string const & tn)
601 {
602         name = n;
603         if (tn==std::string())
604                 TeX_name = "\\\\mbox{"+name+"}";
605         else
606                 TeX_name = tn;
607         return *this;
608 }
609
610 function_options & function_options::latex_name(std::string const & tn)
611 {
612         TeX_name = tn;
613         return *this;
614 }
615
616 // the following lines have been generated for max. ${maxargs} parameters
617 $eval_func_implementation
618 $evalf_func_implementation
619 $conjugate_func_implementation
620 $derivative_func_implementation
621 $power_func_implementation
622 $series_func_implementation
623 // end of generated lines
624
625 function_options& function_options::eval_func(eval_funcp_exvector e)
626 {
627         eval_use_exvector_args = true;
628         eval_f = eval_funcp(e);
629         return *this;
630 }
631 function_options& function_options::evalf_func(evalf_funcp_exvector ef)
632 {
633         evalf_use_exvector_args = true;
634         evalf_f = evalf_funcp(ef);
635         return *this;
636 }
637 function_options& function_options::conjugate_func(conjugate_funcp_exvector c)
638 {
639         conjugate_use_exvector_args = true;
640         conjugate_f = conjugate_funcp(c);
641         return *this;
642 }
643 function_options& function_options::derivative_func(derivative_funcp_exvector d)
644 {
645         derivative_use_exvector_args = true;
646         derivative_f = derivative_funcp(d);
647         return *this;
648 }
649 function_options& function_options::power_func(power_funcp_exvector d)
650 {
651         power_use_exvector_args = true;
652         power_f = power_funcp(d);
653         return *this;
654 }
655 function_options& function_options::series_func(series_funcp_exvector s)
656 {
657         series_use_exvector_args = true;
658         series_f = series_funcp(s);
659         return *this;
660 }
661
662 function_options & function_options::set_return_type(unsigned rt, tinfo_t rtt)
663 {
664         use_return_type = true;
665         return_type = rt;
666         return_type_tinfo = rtt;
667         return *this;
668 }
669
670 function_options & function_options::do_not_evalf_params()
671 {
672         evalf_params_first = false;
673         return *this;
674 }
675
676 function_options & function_options::remember(unsigned size,
677                                               unsigned assoc_size,
678                                               unsigned strategy)
679 {
680         use_remember = true;
681         remember_size = size;
682         remember_assoc_size = assoc_size;
683         remember_strategy = strategy;
684         return *this;
685 }
686
687 function_options & function_options::overloaded(unsigned o)
688 {
689         functions_with_same_name = o;
690         return *this;
691 }
692
693 function_options & function_options::set_symmetry(const symmetry & s)
694 {
695         symtree = s;
696         return *this;
697 }
698         
699 void function_options::test_and_set_nparams(unsigned n)
700 {
701         if (nparams==0) {
702                 nparams = n;
703         } else if (nparams!=n) {
704                 // we do not throw an exception here because this code is
705                 // usually executed before main(), so the exception could not
706                 // be caught anyhow
707                 std::cerr << "WARNING: " << name << "(): number of parameters ("
708                           << n << ") differs from number set before (" 
709                           << nparams << ")" << std::endl;
710         }
711 }
712
713 void function_options::set_print_func(unsigned id, print_funcp f)
714 {
715         if (id >= print_dispatch_table.size())
716                 print_dispatch_table.resize(id + 1);
717         print_dispatch_table[id] = f;
718 }
719
720 /** This can be used as a hook for external applications. */
721 unsigned function::current_serial = 0;
722
723
724 GINAC_IMPLEMENT_REGISTERED_CLASS(function, exprseq)
725
726 //////////
727 // default constructor
728 //////////
729
730 // public
731
732 function::function() : serial(0)
733 {
734         tinfo_key = &function::tinfo_static;
735 }
736
737 //////////
738 // other constructors
739 //////////
740
741 // public
742
743 function::function(unsigned ser) : serial(ser)
744 {
745         tinfo_key = &function::tinfo_static;
746 }
747
748 // the following lines have been generated for max. ${maxargs} parameters
749 $constructors_implementation
750 // end of generated lines
751
752 function::function(unsigned ser, const exprseq & es) : exprseq(es), serial(ser)
753 {
754         tinfo_key = &function::tinfo_static;
755
756         // Force re-evaluation even if the exprseq was already evaluated
757         // (the exprseq copy constructor copies the flags)
758         clearflag(status_flags::evaluated);
759 }
760
761 function::function(unsigned ser, const exvector & v, bool discardable) 
762   : exprseq(v,discardable), serial(ser)
763 {
764         tinfo_key = &function::tinfo_static;
765 }
766
767 function::function(unsigned ser, std::auto_ptr<exvector> vp) 
768   : exprseq(vp), serial(ser)
769 {
770         tinfo_key = &function::tinfo_static;
771 }
772
773 //////////
774 // archiving
775 //////////
776
777 /** Construct object from archive_node. */
778 function::function(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
779 {
780         // Find serial number by function name
781         std::string s;
782         if (n.find_string("name", s)) {
783                 unsigned int ser = 0;
784                 std::vector<function_options>::const_iterator i = registered_functions().begin(), iend = registered_functions().end();
785                 while (i != iend) {
786                         if (s == i->name) {
787                                 serial = ser;
788                                 return;
789                         }
790                         ++i; ++ser;
791                 }
792                 throw (std::runtime_error("unknown function '" + s + "' in archive"));
793         } else
794                 throw (std::runtime_error("unnamed function in archive"));
795 }
796
797 /** Unarchive the object. */
798 ex function::unarchive(const archive_node &n, lst &sym_lst)
799 {
800         return (new function(n, sym_lst))->setflag(status_flags::dynallocated);
801 }
802
803 /** Archive the object. */
804 void function::archive(archive_node &n) const
805 {
806         inherited::archive(n);
807         GINAC_ASSERT(serial < registered_functions().size());
808         n.add_string("name", registered_functions()[serial].name);
809 }
810
811 //////////
812 // functions overriding virtual functions from base classes
813 //////////
814
815 // public
816
817 void function::print(const print_context & c, unsigned level) const
818 {
819         GINAC_ASSERT(serial<registered_functions().size());
820         const function_options &opt = registered_functions()[serial];
821         const std::vector<print_funcp> &pdt = opt.print_dispatch_table;
822
823         // Dynamically dispatch on print_context type
824         const print_context_class_info *pc_info = &c.get_class_info();
825
826 next_context:
827         unsigned id = pc_info->options.get_id();
828         if (id >= pdt.size() || pdt[id] == NULL) {
829
830                 // Method not found, try parent print_context class
831                 const print_context_class_info *parent_pc_info = pc_info->get_parent();
832                 if (parent_pc_info) {
833                         pc_info = parent_pc_info;
834                         goto next_context;
835                 }
836
837                 // Method still not found, use default output
838                 if (is_a<print_tree>(c)) {
839
840                         c.s << std::string(level, ' ') << class_name() << " "
841                             << opt.name << " @" << this
842                             << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
843                             << ", nops=" << nops()
844                             << std::endl;
845                         unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
846                         for (size_t i=0; i<seq.size(); ++i)
847                                 seq[i].print(c, level + delta_indent);
848                         c.s << std::string(level + delta_indent, ' ') << "=====" << std::endl;
849
850                 } else if (is_a<print_csrc>(c)) {
851
852                         // Print function name in lowercase
853                         std::string lname = opt.name;
854                         size_t num = lname.size();
855                         for (size_t i=0; i<num; i++)
856                                 lname[i] = tolower(lname[i]);
857                         c.s << lname;
858                         printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
859
860                 } else if (is_a<print_latex>(c)) {
861                         c.s << opt.TeX_name;
862                         printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
863                 } else {
864                         c.s << opt.name;
865                         printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
866                 }
867
868         } else {
869
870                 // Method found, call it
871                 current_serial = serial;
872                 if (opt.print_use_exvector_args)
873                         ((print_funcp_exvector)pdt[id])(seq, c);
874                 else switch (opt.nparams) {
875                         // the following lines have been generated for max. ${maxargs} parameters
876 ${print_switch_statement}
877                         // end of generated lines
878                 default:
879                         throw(std::logic_error("function::print(): invalid nparams"));
880                 }
881         }
882 }
883
884 ex function::expand(unsigned options) const
885 {
886         // Only expand arguments when asked to do so
887         if (options & expand_options::expand_function_args)
888                 return inherited::expand(options);
889         else
890                 return (options == 0) ? setflag(status_flags::expanded) : *this;
891 }
892
893 ex function::eval(int level) const
894 {
895         if (level>1) {
896                 // first evaluate children, then we will end up here again
897                 return function(serial,evalchildren(level));
898         }
899
900         GINAC_ASSERT(serial<registered_functions().size());
901         const function_options &opt = registered_functions()[serial];
902
903         // Canonicalize argument order according to the symmetry properties
904         if (seq.size() > 1 && !(opt.symtree.is_zero())) {
905                 exvector v = seq;
906                 GINAC_ASSERT(is_a<symmetry>(opt.symtree));
907                 int sig = canonicalize(v.begin(), ex_to<symmetry>(opt.symtree));
908                 if (sig != INT_MAX) {
909                         // Something has changed while sorting arguments, more evaluations later
910                         if (sig == 0)
911                                 return _ex0;
912                         return ex(sig) * thiscontainer(v);
913                 }
914         }
915
916         if (opt.eval_f==0) {
917                 return this->hold();
918         }
919
920         bool use_remember = opt.use_remember;
921         ex eval_result;
922         if (use_remember && lookup_remember_table(eval_result)) {
923                 return eval_result;
924         }
925         current_serial = serial;
926         if (opt.eval_use_exvector_args)
927                 eval_result = ((eval_funcp_exvector)(opt.eval_f))(seq);
928         else
929         switch (opt.nparams) {
930                 // the following lines have been generated for max. ${maxargs} parameters
931 ${eval_switch_statement}
932                 // end of generated lines
933         default:
934                 throw(std::logic_error("function::eval(): invalid nparams"));
935         }
936         if (use_remember) {
937                 store_remember_table(eval_result);
938         }
939         return eval_result;
940 }
941
942 ex function::evalf(int level) const
943 {
944         GINAC_ASSERT(serial<registered_functions().size());
945         const function_options &opt = registered_functions()[serial];
946
947         // Evaluate children first
948         exvector eseq;
949         if (level == 1 || !(opt.evalf_params_first))
950                 eseq = seq;
951         else if (level == -max_recursion_level)
952                 throw(std::runtime_error("max recursion level reached"));
953         else {
954                 eseq.reserve(seq.size());
955                 --level;
956                 exvector::const_iterator it = seq.begin(), itend = seq.end();
957                 while (it != itend) {
958                         eseq.push_back(it->evalf(level));
959                         ++it;
960                 }
961         }
962
963         if (opt.evalf_f==0) {
964                 return function(serial,eseq).hold();
965         }
966         current_serial = serial;
967         if (opt.evalf_use_exvector_args)
968                 return ((evalf_funcp_exvector)(opt.evalf_f))(seq);
969         switch (opt.nparams) {
970                 // the following lines have been generated for max. ${maxargs} parameters
971 ${evalf_switch_statement}
972                 // end of generated lines
973         }
974         throw(std::logic_error("function::evalf(): invalid nparams"));
975 }
976
977 unsigned function::calchash() const
978 {
979         unsigned v = golden_ratio_hash(golden_ratio_hash((p_int)tinfo()) ^ serial);
980         for (size_t i=0; i<nops(); i++) {
981                 v = rotate_left(v);
982                 v ^= this->op(i).gethash();
983         }
984
985         if (flags & status_flags::evaluated) {
986                 setflag(status_flags::hash_calculated);
987                 hashvalue = v;
988         }
989         return v;
990 }
991
992 ex function::thiscontainer(const exvector & v) const
993 {
994         return function(serial, v);
995 }
996
997 ex function::thiscontainer(std::auto_ptr<exvector> vp) const
998 {
999         return function(serial, vp);
1000 }
1001
1002 /** Implementation of ex::series for functions.
1003  *  \@see ex::series */
1004 ex function::series(const relational & r, int order, unsigned options) const
1005 {
1006         GINAC_ASSERT(serial<registered_functions().size());
1007         const function_options &opt = registered_functions()[serial];
1008
1009         if (opt.series_f==0) {
1010                 return basic::series(r, order);
1011         }
1012         ex res;
1013         current_serial = serial;
1014         if (opt.series_use_exvector_args) {
1015                 try {
1016                         res = ((series_funcp_exvector)(opt.series_f))(seq, r, order, options);
1017                 } catch (do_taylor) {
1018                         res = basic::series(r, order, options);
1019                 }
1020                 return res;
1021         }
1022         switch (opt.nparams) {
1023                 // the following lines have been generated for max. ${maxargs} parameters
1024 ${series_switch_statement}
1025                 // end of generated lines
1026         }
1027         throw(std::logic_error("function::series(): invalid nparams"));
1028 }
1029
1030 /** Implementation of ex::conjugate for functions. */
1031 ex function::conjugate() const
1032 {
1033         GINAC_ASSERT(serial<registered_functions().size());
1034         const function_options & opt = registered_functions()[serial];
1035
1036         if (opt.conjugate_f==0) {
1037                 return exprseq::conjugate();
1038         }
1039
1040         if (opt.conjugate_use_exvector_args) {
1041                 return ((conjugate_funcp_exvector)(opt.conjugate_f))(seq);
1042         }
1043
1044         switch (opt.nparams) {
1045                 // the following lines have been generated for max. ${maxargs} parameters
1046 ${conjugate_switch_statement}
1047                 // end of generated lines
1048         }
1049         throw(std::logic_error("function::conjugate(): invalid nparams"));
1050 }
1051
1052 // protected
1053
1054 /** Implementation of ex::diff() for functions. It applies the chain rule,
1055  *  except for the Order term function.
1056  *  \@see ex::diff */
1057 ex function::derivative(const symbol & s) const
1058 {
1059         ex result;
1060
1061         if (serial == Order_SERIAL::serial) {
1062                 // Order Term function only differentiates the argument
1063                 return Order(seq[0].diff(s));
1064         } else {
1065                 // Chain rule
1066                 ex arg_diff;
1067                 size_t num = seq.size();
1068                 for (size_t i=0; i<num; i++) {
1069                         arg_diff = seq[i].diff(s);
1070                         // We apply the chain rule only when it makes sense.  This is not
1071                         // just for performance reasons but also to allow functions to
1072                         // throw when differentiated with respect to one of its arguments
1073                         // without running into trouble with our automatic full
1074                         // differentiation:
1075                         if (!arg_diff.is_zero())
1076                                 result += pderivative(i)*arg_diff;
1077                 }
1078         }
1079         return result;
1080 }
1081
1082 int function::compare_same_type(const basic & other) const
1083 {
1084         GINAC_ASSERT(is_a<function>(other));
1085         const function & o = static_cast<const function &>(other);
1086
1087         if (serial != o.serial)
1088                 return serial < o.serial ? -1 : 1;
1089         else
1090                 return exprseq::compare_same_type(o);
1091 }
1092
1093 bool function::is_equal_same_type(const basic & other) const
1094 {
1095         GINAC_ASSERT(is_a<function>(other));
1096         const function & o = static_cast<const function &>(other);
1097
1098         if (serial != o.serial)
1099                 return false;
1100         else
1101                 return exprseq::is_equal_same_type(o);
1102 }
1103
1104 bool function::match_same_type(const basic & other) const
1105 {
1106         GINAC_ASSERT(is_a<function>(other));
1107         const function & o = static_cast<const function &>(other);
1108
1109         return serial == o.serial;
1110 }
1111
1112 unsigned function::return_type() const
1113 {
1114         GINAC_ASSERT(serial<registered_functions().size());
1115         const function_options &opt = registered_functions()[serial];
1116
1117         if (opt.use_return_type) {
1118                 // Return type was explicitly specified
1119                 return opt.return_type;
1120         } else {
1121                 // Default behavior is to use the return type of the first
1122                 // argument. Thus, exp() of a matrix behaves like a matrix, etc.
1123                 if (seq.empty())
1124                         return return_types::commutative;
1125                 else
1126                         return seq.begin()->return_type();
1127         }
1128 }
1129
1130 tinfo_t function::return_type_tinfo() const
1131 {
1132         GINAC_ASSERT(serial<registered_functions().size());
1133         const function_options &opt = registered_functions()[serial];
1134
1135         if (opt.use_return_type) {
1136                 // Return type was explicitly specified
1137                 return opt.return_type_tinfo;
1138         } else {
1139                 // Default behavior is to use the return type of the first
1140                 // argument. Thus, exp() of a matrix behaves like a matrix, etc.
1141                 if (seq.empty())
1142                         return this;
1143                 else
1144                         return seq.begin()->return_type_tinfo();
1145         }
1146 }
1147
1148 //////////
1149 // new virtual functions which can be overridden by derived classes
1150 //////////
1151
1152 // none
1153
1154 //////////
1155 // non-virtual functions in this class
1156 //////////
1157
1158 // protected
1159
1160 ex function::pderivative(unsigned diff_param) const // partial differentiation
1161 {
1162         GINAC_ASSERT(serial<registered_functions().size());
1163         const function_options &opt = registered_functions()[serial];
1164         
1165         // No derivative defined? Then return abstract derivative object
1166         if (opt.derivative_f == NULL)
1167                 return fderivative(serial, diff_param, seq);
1168
1169         current_serial = serial;
1170         if (opt.derivative_use_exvector_args)
1171                 return ((derivative_funcp_exvector)(opt.derivative_f))(seq, diff_param);
1172         switch (opt.nparams) {
1173                 // the following lines have been generated for max. ${maxargs} parameters
1174 ${diff_switch_statement}
1175                 // end of generated lines
1176         }
1177         throw(std::logic_error("function::pderivative(): no diff function defined"));
1178 }
1179
1180 ex function::power(const ex & power_param) const // power of function
1181 {
1182         GINAC_ASSERT(serial<registered_functions().size());
1183         const function_options &opt = registered_functions()[serial];
1184         
1185         // No derivative defined? Then return abstract derivative object
1186         if (opt.power_f == NULL)
1187                 return (new power::power(*this, power_param))->setflag(status_flags::dynallocated |
1188                                                        status_flags::evaluated);
1189
1190         current_serial = serial;
1191         if (opt.power_use_exvector_args)
1192                 return ((power_funcp_exvector)(opt.power_f))(seq,  power_param);
1193         switch (opt.nparams) {
1194                 // the following lines have been generated for max. ${maxargs} parameters
1195 ${power_switch_statement}
1196                 // end of generated lines
1197         }
1198         throw(std::logic_error("function::power(): no power function defined"));
1199 }
1200
1201 std::vector<function_options> & function::registered_functions()
1202 {
1203         static std::vector<function_options> * rf = new std::vector<function_options>;
1204         return *rf;
1205 }
1206
1207 bool function::lookup_remember_table(ex & result) const
1208 {
1209         return remember_table::remember_tables()[this->serial].lookup_entry(*this,result);
1210 }
1211
1212 void function::store_remember_table(ex const & result) const
1213 {
1214         remember_table::remember_tables()[this->serial].add_entry(*this,result);
1215 }
1216
1217 // public
1218
1219 unsigned function::register_new(function_options const & opt)
1220 {
1221         size_t same_name = 0;
1222         for (size_t i=0; i<registered_functions().size(); ++i) {
1223                 if (registered_functions()[i].name==opt.name) {
1224                         ++same_name;
1225                 }
1226         }
1227         if (same_name>=opt.functions_with_same_name) {
1228                 // we do not throw an exception here because this code is
1229                 // usually executed before main(), so the exception could not
1230                 // caught anyhow
1231                 std::cerr << "WARNING: function name " << opt.name
1232                           << " already in use!" << std::endl;
1233         }
1234         registered_functions().push_back(opt);
1235         if (opt.use_remember) {
1236                 remember_table::remember_tables().
1237                         push_back(remember_table(opt.remember_size,
1238                                                  opt.remember_assoc_size,
1239                                                  opt.remember_strategy));
1240         } else {
1241                 remember_table::remember_tables().push_back(remember_table());
1242         }
1243         return registered_functions().size()-1;
1244 }
1245
1246 /** Find serial number of function by name and number of parameters.
1247  *  Throws exception if function was not found. */
1248 unsigned function::find_function(const std::string &name, unsigned nparams)
1249 {
1250         std::vector<function_options>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
1251         unsigned serial = 0;
1252         while (i != end) {
1253                 if (i->get_name() == name && i->get_nparams() == nparams)
1254                         return serial;
1255                 ++i;
1256                 ++serial;
1257         }
1258         throw (std::runtime_error("no function '" + name + "' with " + ToString(nparams) + " parameters defined"));
1259 }
1260
1261 /** Return the print name of the function. */
1262 std::string function::get_name() const
1263 {
1264         GINAC_ASSERT(serial<registered_functions().size());
1265         return registered_functions()[serial].name;
1266 }
1267
1268 } // namespace GiNaC
1269
1270 END_OF_IMPLEMENTATION
1271
1272 print "Creating interface file function.h...";
1273 open OUT,">function.h" or die "cannot open function.h";
1274 print OUT $interface;
1275 close OUT;
1276 print "ok.\n";
1277
1278 print "Creating implementation file function.cpp...";
1279 open OUT,">function.cpp" or die "cannot open function.cpp";
1280 print OUT $implementation;
1281 close OUT;
1282 print "ok.\n";
1283
1284 print "done.\n";