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