]> www.ginac.de Git - ginac.git/blob - ginsh/ginsh_parser.yy
* Finilize version 1.0.4 (version numbers, copyrights and such rubbish).
[ginac.git] / ginsh / ginsh_parser.yy
1 /** @file ginsh_parser.yy
2  *
3  *  Input grammar definition for ginsh.
4  *  This file must be processed with yacc/bison. */
5
6 /*
7  *  GiNaC Copyright (C) 1999-2002 Johannes Gutenberg University Mainz, Germany
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24
25 /*
26  *  Definitions
27  */
28
29 %{
30 #include "config.h"
31
32 #include <sys/resource.h>
33
34 #if HAVE_UNISTD_H
35 #include <sys/types.h>
36 #include <unistd.h>
37 #endif
38
39 #include <stdexcept>
40
41 #include "ginsh.h"
42
43 #define YYERROR_VERBOSE 1
44
45 // Original readline settings
46 static int orig_completion_append_character;
47 #if (GINAC_RL_VERSION_MAJOR < 4) || (GINAC_RL_VERSION_MAJOR == 4 && GINAC_RL_VERSION_MINOR < 2)
48 static char *orig_basic_word_break_characters;
49 #else
50 static const char *orig_basic_word_break_characters;
51 #endif
52
53 // Expression stack for ", "" and """
54 static void push(const ex &e);
55 static ex exstack[3];
56
57 // Start and end time for the time() function
58 static struct rusage start_time, end_time;
59
60 // Table of functions (a multimap, because one function may appear with different
61 // numbers of parameters)
62 typedef ex (*fcnp)(const exprseq &e);
63 typedef ex (*fcnp2)(const exprseq &e, int serial);
64
65 struct fcn_desc {
66         fcn_desc() : p(NULL), num_params(0) {}
67         fcn_desc(fcnp func, int num) : p(func), num_params(num), is_ginac(false) {}
68         fcn_desc(fcnp2 func, int num, int ser) : p((fcnp)func), num_params(num), is_ginac(true), serial(ser) {}
69
70         fcnp p;         // Pointer to function
71         int num_params; // Number of parameters (0 = arbitrary)
72         bool is_ginac;  // Flag: function is GiNaC function
73         int serial;     // GiNaC function serial number (if is_ginac == true)
74 };
75
76 typedef multimap<string, fcn_desc> fcn_tab;
77 static fcn_tab fcns;
78
79 static fcn_tab::const_iterator find_function(const ex &sym, int req_params);
80
81 // Table to map help topics to help strings
82 typedef multimap<string, string> help_tab;
83 static help_tab help;
84
85 static void insert_fcn_help(const char *name, const char *str);
86 static void print_help(const string &topic);
87 static void print_help_topics(void);
88 %}
89
90 /* Tokens (T_LITERAL means a literal value returned by the parser, but not
91    of class numeric or symbol (e.g. a constant or the FAIL object)) */
92 %token T_NUMBER T_SYMBOL T_LITERAL T_DIGITS T_QUOTE T_QUOTE2 T_QUOTE3
93 %token T_EQUAL T_NOTEQ T_LESSEQ T_GREATEREQ
94
95 %token T_QUIT T_WARRANTY T_PRINT T_IPRINT T_TIME T_XYZZY T_INVENTORY T_LOOK T_SCORE
96
97 /* Operator precedence and associativity */
98 %right '='
99 %left T_EQUAL T_NOTEQ
100 %left '<' '>' T_LESSEQ T_GREATEREQ
101 %left '+' '-'
102 %left '*' '/' '%'
103 %nonassoc NEG
104 %right '^'
105 %nonassoc '!'
106
107 %start input
108
109
110 /*
111  *  Grammar rules
112  */
113
114 %%
115 input   : /* empty */
116         | input line
117         ;
118
119 line    : ';'
120         | exp ';' {
121                 try {
122                         cout << $1 << endl;
123                         push($1);
124                 } catch (exception &e) {
125                         cerr << e.what() << endl;
126                         YYERROR;
127                 }
128         }
129         | exp ':' {
130                 try {
131                         push($1);
132                 } catch (exception &e) {
133                         std::cerr << e.what() << endl;
134                         YYERROR;
135                 }
136         }
137         | T_PRINT '(' exp ')' ';' {
138                 try {
139                         $3.print(print_tree(std::cout));
140                 } catch (exception &e) {
141                         std::cerr << e.what() << endl;
142                         YYERROR;
143                 }
144         }
145         | T_IPRINT '(' exp ')' ';' {
146                 try {
147                         ex e = $3;
148                         if (!e.info(info_flags::integer))
149                                 throw (std::invalid_argument("argument to iprint() must be an integer"));
150                         long i = ex_to<numeric>(e).to_long();
151                         cout << i << endl;
152                         cout << "#o" << oct << i << endl;
153                         cout << "#x" << hex << i << dec << endl;
154                 } catch (exception &e) {
155                         cerr << e.what() << endl;
156                         YYERROR;
157                 }
158         }
159         | '?' T_SYMBOL          {print_help(ex_to<symbol>($2).get_name());}
160         | '?' T_TIME            {print_help("time");}
161         | '?' '?'               {print_help_topics();}
162         | T_QUIT                {YYACCEPT;}
163         | T_WARRANTY {
164                 cout << "This program is free software; you can redistribute it and/or modify it under\n";
165                 cout << "the terms of the GNU General Public License as published by the Free Software\n";
166                 cout << "Foundation; either version 2 of the License, or (at your option) any later\n";
167                 cout << "version.\n";
168                 cout << "This program is distributed in the hope that it will be useful, but WITHOUT\n";
169                 cout << "ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n";
170                 cout << "FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n";
171                 cout << "details.\n";
172                 cout << "You should have received a copy of the GNU General Public License along with\n";
173                 cout << "this program. If not, write to the Free Software Foundation, 675 Mass Ave,\n";
174                 cout << "Cambridge, MA 02139, USA.\n";
175         }
176         | T_XYZZY               {cout << "Nothing happens.\n";}
177         | T_INVENTORY           {cout << "You're not carrying anything.\n";}
178         | T_LOOK                {cout << "You're in a twisty little maze of passages, all alike.\n";}
179         | T_SCORE {
180                 cout << "If you were to quit now, you would score ";
181                 cout << (syms.size() > 350 ? 350 : syms.size());
182                 cout << " out of a possible 350.\n";
183         }
184         | T_TIME {getrusage(RUSAGE_SELF, &start_time);} '(' exp ')' {
185                 getrusage(RUSAGE_SELF, &end_time);
186                 cout << (end_time.ru_utime.tv_sec - start_time.ru_utime.tv_sec) +
187                         (end_time.ru_stime.tv_sec - start_time.ru_stime.tv_sec) +
188                          double(end_time.ru_utime.tv_usec - start_time.ru_utime.tv_usec) / 1e6 +
189                          double(end_time.ru_stime.tv_usec - start_time.ru_stime.tv_usec) / 1e6 << 's' << endl;
190         }
191         | error ';'             {yyclearin; yyerrok;}
192         | error ':'             {yyclearin; yyerrok;}
193         ;
194
195 exp     : T_NUMBER              {$$ = $1;}
196         | T_SYMBOL              {$$ = $1.eval();}
197         | '\'' T_SYMBOL '\''    {$$ = $2;}
198         | T_LITERAL             {$$ = $1;}
199         | T_DIGITS              {$$ = $1;}
200         | T_QUOTE               {$$ = exstack[0];}
201         | T_QUOTE2              {$$ = exstack[1];}
202         | T_QUOTE3              {$$ = exstack[2];}
203         | T_SYMBOL '(' exprseq ')' {
204                 fcn_tab::const_iterator i = find_function($1, $3.nops());
205                 if (i->second.is_ginac) {
206                         $$ = ((fcnp2)(i->second.p))(ex_to<exprseq>($3), i->second.serial);
207                 } else {
208                         $$ = (i->second.p)(ex_to<exprseq>($3));
209                 }
210         }
211         | T_DIGITS '=' T_NUMBER {$$ = $3; Digits = ex_to<numeric>($3).to_int();}
212         | T_SYMBOL '=' exp      {$$ = $3; const_cast<symbol&>(ex_to<symbol>($1)).assign($3);}
213         | exp T_EQUAL exp       {$$ = $1 == $3;}
214         | exp T_NOTEQ exp       {$$ = $1 != $3;}
215         | exp '<' exp           {$$ = $1 < $3;}
216         | exp T_LESSEQ exp      {$$ = $1 <= $3;}
217         | exp '>' exp           {$$ = $1 > $3;}
218         | exp T_GREATEREQ exp   {$$ = $1 >= $3;}
219         | exp '+' exp           {$$ = $1 + $3;}
220         | exp '-' exp           {$$ = $1 - $3;}
221         | exp '*' exp           {$$ = $1 * $3;}
222         | exp '/' exp           {$$ = $1 / $3;}
223         | '-' exp %prec NEG     {$$ = -$2;}
224         | '+' exp %prec NEG     {$$ = $2;}
225         | exp '^' exp           {$$ = power($1, $3);}
226         | exp '!'               {$$ = factorial($1);}
227         | '(' exp ')'           {$$ = $2;}
228         | '{' list_or_empty '}' {$$ = $2;}
229         | '[' matrix ']'        {$$ = lst_to_matrix(ex_to<lst>($2));}
230         ;
231
232 exprseq : exp                   {$$ = exprseq($1);}
233         | exprseq ',' exp       {exprseq es(ex_to<exprseq>($1)); $$ = es.append($3);}
234         ;
235
236 list_or_empty: /* empty */      {$$ = *new lst;}
237         | list                  {$$ = $1;}
238         ;
239
240 list    : exp                   {$$ = lst($1);}
241         | list ',' exp          {lst l(ex_to<lst>($1)); $$ = l.append($3);}
242         ;
243
244 matrix  : '[' row ']'           {$$ = lst($2);}
245         | matrix ',' '[' row ']' {lst l(ex_to<lst>($1)); $$ = l.append($4);}
246         ;
247
248 row     : exp                   {$$ = lst($1);}
249         | row ',' exp           {lst l(ex_to<lst>($1)); $$ = l.append($3);}
250         ;
251
252
253 /*
254  *  Routines
255  */
256
257 %%
258 // Error print routine
259 int yyerror(char *s)
260 {
261         cerr << s << " at " << yytext << endl;
262         return 0;
263 }
264
265 // Push expression "e" onto the expression stack (for ", "" and """)
266 static void push(const ex &e)
267 {
268         exstack[2] = exstack[1];
269         exstack[1] = exstack[0];
270         exstack[0] = e;
271 }
272
273
274 /*
275  *  Built-in functions
276  */
277
278 static ex f_collect(const exprseq &e) {return e[0].collect(e[1]);}
279 static ex f_collect_distributed(const exprseq &e) {return e[0].collect(e[1], true);}
280 static ex f_degree(const exprseq &e) {return e[0].degree(e[1]);}
281 static ex f_denom(const exprseq &e) {return e[0].denom();}
282 static ex f_eval1(const exprseq &e) {return e[0].eval();}
283 static ex f_evalf1(const exprseq &e) {return e[0].evalf();}
284 static ex f_evalm(const exprseq &e) {return e[0].evalm();}
285 static ex f_expand(const exprseq &e) {return e[0].expand();}
286 static ex f_gcd(const exprseq &e) {return gcd(e[0], e[1]);}
287 static ex f_has(const exprseq &e) {return e[0].has(e[1]) ? ex(1) : ex(0);}
288 static ex f_lcm(const exprseq &e) {return lcm(e[0], e[1]);}
289 static ex f_lcoeff(const exprseq &e) {return e[0].lcoeff(e[1]);}
290 static ex f_ldegree(const exprseq &e) {return e[0].ldegree(e[1]);}
291 static ex f_lsolve(const exprseq &e) {return lsolve(e[0], e[1]);}
292 static ex f_nops(const exprseq &e) {return e[0].nops();}
293 static ex f_normal1(const exprseq &e) {return e[0].normal();}
294 static ex f_numer(const exprseq &e) {return e[0].numer();}
295 static ex f_numer_denom(const exprseq &e) {return e[0].numer_denom();}
296 static ex f_pow(const exprseq &e) {return pow(e[0], e[1]);}
297 static ex f_sqrt(const exprseq &e) {return sqrt(e[0]);}
298 static ex f_sqrfree1(const exprseq &e) {return sqrfree(e[0]);}
299 static ex f_subs2(const exprseq &e) {return e[0].subs(e[1]);}
300 static ex f_tcoeff(const exprseq &e) {return e[0].tcoeff(e[1]);}
301
302 #define CHECK_ARG(num, type, fcn) if (!is_a<type>(e[num])) throw(std::invalid_argument("argument " #num " to " #fcn "() must be a " #type))
303
304 static ex f_charpoly(const exprseq &e)
305 {
306         CHECK_ARG(0, matrix, charpoly);
307         CHECK_ARG(1, symbol, charpoly);
308         return ex_to<matrix>(e[0]).charpoly(ex_to<symbol>(e[1]));
309 }
310
311 static ex f_coeff(const exprseq &e)
312 {
313         CHECK_ARG(2, numeric, coeff);
314         return e[0].coeff(e[1], ex_to<numeric>(e[2]).to_int());
315 }
316
317 static ex f_content(const exprseq &e)
318 {
319         CHECK_ARG(1, symbol, content);
320         return e[0].content(ex_to<symbol>(e[1]));
321 }
322
323 static ex f_decomp_rational(const exprseq &e)
324 {
325         CHECK_ARG(1, symbol, decomp_rational);
326         return decomp_rational(e[0], ex_to<symbol>(e[1]));
327 }
328
329 static ex f_determinant(const exprseq &e)
330 {
331         CHECK_ARG(0, matrix, determinant);
332         return ex_to<matrix>(e[0]).determinant();
333 }
334
335 static ex f_diag(const exprseq &e)
336 {
337         unsigned dim = e.nops();
338         matrix &m = *new matrix(dim, dim);
339         for (unsigned i=0; i<dim; i++)
340                 m.set(i, i, e.op(i));
341         return m;
342 }
343
344 static ex f_diff2(const exprseq &e)
345 {
346         CHECK_ARG(1, symbol, diff);
347         return e[0].diff(ex_to<symbol>(e[1]));
348 }
349
350 static ex f_diff3(const exprseq &e)
351 {
352         CHECK_ARG(1, symbol, diff);
353         CHECK_ARG(2, numeric, diff);
354         return e[0].diff(ex_to<symbol>(e[1]), ex_to<numeric>(e[2]).to_int());
355 }
356
357 static ex f_divide(const exprseq &e)
358 {
359         ex q;
360         if (divide(e[0], e[1], q))
361                 return q;
362         else
363                 return fail();
364 }
365
366 static ex f_eval2(const exprseq &e)
367 {
368         CHECK_ARG(1, numeric, eval);
369         return e[0].eval(ex_to<numeric>(e[1]).to_int());
370 }
371
372 static ex f_evalf2(const exprseq &e)
373 {
374         CHECK_ARG(1, numeric, evalf);
375         return e[0].evalf(ex_to<numeric>(e[1]).to_int());
376 }
377
378 static ex f_find(const exprseq &e)
379 {
380         lst found;
381         e[0].find(e[1], found);
382         return found;
383 }
384
385 static ex f_inverse(const exprseq &e)
386 {
387         CHECK_ARG(0, matrix, inverse);
388         return ex_to<matrix>(e[0]).inverse();
389 }
390
391 static ex f_is(const exprseq &e)
392 {
393         CHECK_ARG(0, relational, is);
394         return (bool)ex_to<relational>(e[0]) ? ex(1) : ex(0);
395 }
396
397 class apply_map_function : public map_function {
398         ex apply;
399 public:
400         apply_map_function(const ex & a) : apply(a) {}
401         virtual ~apply_map_function() {}
402         ex operator()(const ex & e) { return apply.subs(wild() == e, true); }
403 };
404
405 static ex f_map(const exprseq &e)
406 {
407         apply_map_function fcn(e[1]);
408         return e[0].map(fcn);
409 }
410
411 static ex f_match(const exprseq &e)
412 {
413         lst repl_lst;
414         if (e[0].match(e[1], repl_lst))
415                 return repl_lst;
416         else
417                 return fail();
418 }
419
420 static ex f_normal2(const exprseq &e)
421 {
422         CHECK_ARG(1, numeric, normal);
423         return e[0].normal(ex_to<numeric>(e[1]).to_int());
424 }
425
426 static ex f_op(const exprseq &e)
427 {
428         CHECK_ARG(1, numeric, op);
429         int n = ex_to<numeric>(e[1]).to_int();
430         if (n < 0 || n >= (int)e[0].nops())
431                 throw(std::out_of_range("second argument to op() is out of range"));
432         return e[0].op(n);
433 }
434
435 static ex f_prem(const exprseq &e)
436 {
437         CHECK_ARG(2, symbol, prem);
438         return prem(e[0], e[1], ex_to<symbol>(e[2]));
439 }
440
441 static ex f_primpart(const exprseq &e)
442 {
443         CHECK_ARG(1, symbol, primpart);
444         return e[0].primpart(ex_to<symbol>(e[1]));
445 }
446
447 static ex f_quo(const exprseq &e)
448 {
449         CHECK_ARG(2, symbol, quo);
450         return quo(e[0], e[1], ex_to<symbol>(e[2]));
451 }
452
453 static ex f_rem(const exprseq &e)
454 {
455         CHECK_ARG(2, symbol, rem);
456         return rem(e[0], e[1], ex_to<symbol>(e[2]));
457 }
458
459 static ex f_series(const exprseq &e)
460 {
461         CHECK_ARG(2, numeric, series);
462         return e[0].series(e[1], ex_to<numeric>(e[2]).to_int());
463 }
464
465 static ex f_sqrfree2(const exprseq &e)
466 {
467         CHECK_ARG(1, lst, sqrfree);
468         return sqrfree(e[0], ex_to<lst>(e[1]));
469 }
470
471 static ex f_subs3(const exprseq &e)
472 {
473         CHECK_ARG(1, lst, subs);
474         CHECK_ARG(2, lst, subs);
475         return e[0].subs(ex_to<lst>(e[1]), ex_to<lst>(e[2]));
476 }
477
478 static ex f_trace(const exprseq &e)
479 {
480         CHECK_ARG(0, matrix, trace);
481         return ex_to<matrix>(e[0]).trace();
482 }
483
484 static ex f_transpose(const exprseq &e)
485 {
486         CHECK_ARG(0, matrix, transpose);
487         return ex_to<matrix>(e[0]).transpose();
488 }
489
490 static ex f_unassign(const exprseq &e)
491 {
492         CHECK_ARG(0, symbol, unassign);
493         const_cast<symbol&>(ex_to<symbol>(e[0])).unassign();
494         return e[0];
495 }
496
497 static ex f_unit(const exprseq &e)
498 {
499         CHECK_ARG(1, symbol, unit);
500         return e[0].unit(ex_to<symbol>(e[1]));
501 }
502
503 static ex f_dummy(const exprseq &e)
504 {
505         throw(std::logic_error("dummy function called (shouldn't happen)"));
506 }
507
508 // Tables for initializing the "fcns" map and the function help topics
509 struct fcn_init {
510         const char *name;
511         const fcn_desc desc;
512 };
513
514 static const fcn_init builtin_fcns[] = {
515         {"charpoly", fcn_desc(f_charpoly, 2)},
516         {"coeff", fcn_desc(f_coeff, 3)},
517         {"collect", fcn_desc(f_collect, 2)},
518         {"collect_distributed", fcn_desc(f_collect_distributed, 2)},
519         {"content", fcn_desc(f_content, 2)},
520         {"decomp_rational", fcn_desc(f_decomp_rational, 2)},
521         {"degree", fcn_desc(f_degree, 2)},
522         {"denom", fcn_desc(f_denom, 1)},
523         {"determinant", fcn_desc(f_determinant, 1)},
524         {"diag", fcn_desc(f_diag, 0)},
525         {"diff", fcn_desc(f_diff2, 2)},
526         {"diff", fcn_desc(f_diff3, 3)},
527         {"divide", fcn_desc(f_divide, 2)},
528         {"eval", fcn_desc(f_eval1, 1)},
529         {"eval", fcn_desc(f_eval2, 2)},
530         {"evalf", fcn_desc(f_evalf1, 1)},
531         {"evalf", fcn_desc(f_evalf2, 2)},
532         {"evalm", fcn_desc(f_evalm, 1)},
533         {"expand", fcn_desc(f_expand, 1)},
534         {"find", fcn_desc(f_find, 2)},
535         {"gcd", fcn_desc(f_gcd, 2)},
536         {"has", fcn_desc(f_has, 2)},
537         {"inverse", fcn_desc(f_inverse, 1)},
538         {"is", fcn_desc(f_is, 1)},
539         {"lcm", fcn_desc(f_lcm, 2)},
540         {"lcoeff", fcn_desc(f_lcoeff, 2)},
541         {"ldegree", fcn_desc(f_ldegree, 2)},
542         {"lsolve", fcn_desc(f_lsolve, 2)},
543         {"map", fcn_desc(f_map, 2)},
544         {"match", fcn_desc(f_match, 2)},
545         {"nops", fcn_desc(f_nops, 1)},
546         {"normal", fcn_desc(f_normal1, 1)},
547         {"normal", fcn_desc(f_normal2, 2)},
548         {"numer", fcn_desc(f_numer, 1)},
549         {"numer_denom", fcn_desc(f_numer_denom, 1)},
550         {"op", fcn_desc(f_op, 2)},
551         {"pow", fcn_desc(f_pow, 2)},
552         {"prem", fcn_desc(f_prem, 3)},
553         {"primpart", fcn_desc(f_primpart, 2)},
554         {"quo", fcn_desc(f_quo, 3)},
555         {"rem", fcn_desc(f_rem, 3)},
556         {"series", fcn_desc(f_series, 3)},
557         {"sqrfree", fcn_desc(f_sqrfree1, 1)},
558         {"sqrfree", fcn_desc(f_sqrfree2, 2)},
559         {"sqrt", fcn_desc(f_sqrt, 1)},
560         {"subs", fcn_desc(f_subs2, 2)},
561         {"subs", fcn_desc(f_subs3, 3)},
562         {"tcoeff", fcn_desc(f_tcoeff, 2)},
563         {"time", fcn_desc(f_dummy, 0)},
564         {"trace", fcn_desc(f_trace, 1)},
565         {"transpose", fcn_desc(f_transpose, 1)},
566         {"unassign", fcn_desc(f_unassign, 1)},
567         {"unit", fcn_desc(f_unit, 2)},
568         {NULL, fcn_desc(f_dummy, 0)}    // End marker
569 };
570
571 struct fcn_help_init {
572         const char *name;
573         const char *help;
574 };
575
576 static const fcn_help_init builtin_help[] = {
577         {"acos", "inverse cosine function"},
578         {"acosh", "inverse hyperbolic cosine function"},
579         {"asin", "inverse sine function"},
580         {"asinh", "inverse hyperbolic sine function"},
581         {"atan", "inverse tangent function"},
582         {"atan2", "inverse tangent function with two arguments"},
583         {"atanh", "inverse hyperbolic tangent function"},
584         {"beta", "Beta function"},
585         {"binomial", "binomial function"},
586         {"cos", "cosine function"},
587         {"cosh", "hyperbolic cosine function"},
588         {"exp", "exponential function"},
589         {"factorial", "factorial function"},
590         {"lgamma", "natural logarithm of Gamma function"},
591         {"tgamma", "Gamma function"},
592         {"log", "natural logarithm"},
593         {"psi", "psi function\npsi(x) is the digamma function, psi(n,x) the nth polygamma function"},
594         {"sin", "sine function"},
595         {"sinh", "hyperbolic sine function"},
596         {"tan", "tangent function"},
597         {"tanh", "hyperbolic tangent function"},
598         {"zeta", "zeta function\nzeta(x) is Riemann's zeta function, zeta(n,x) its nth derivative"},
599         {"Li2", "dilogarithm"},
600         {"Li3", "trilogarithm"},
601         {"Order", "order term function (for truncated power series)"},
602         {"Derivative", "inert differential operator"},
603         {NULL, NULL}    // End marker
604 };
605
606 #include "ginsh_extensions.h"
607
608
609 /*
610  *  Add functions to ginsh
611  */
612
613 // Functions from fcn_init array
614 static void insert_fcns(const fcn_init *p)
615 {
616         while (p->name) {
617                 fcns.insert(make_pair(string(p->name), p->desc));
618                 p++;
619         }
620 }
621
622 static ex f_ginac_function(const exprseq &es, int serial)
623 {
624         return function(serial, es).eval(1);
625 }
626
627 // All registered GiNaC functions
628 void GiNaC::ginsh_get_ginac_functions(void)
629 {
630         vector<function_options>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
631         unsigned serial = 0;
632         while (i != end) {
633                 fcns.insert(make_pair(i->get_name(), fcn_desc(f_ginac_function, i->get_nparams(), serial)));
634                 ++i;
635                 serial++;
636         }
637 }
638
639
640 /*
641  *  Find a function given a name and number of parameters. Throw exceptions on error.
642  */
643
644 static fcn_tab::const_iterator find_function(const ex &sym, int req_params)
645 {
646         const string &name = ex_to<symbol>(sym).get_name();
647         typedef fcn_tab::const_iterator I;
648         pair<I, I> b = fcns.equal_range(name);
649         if (b.first == b.second)
650                 throw(std::logic_error("unknown function '" + name + "'"));
651         else {
652                 for (I i=b.first; i!=b.second; i++)
653                         if ((i->second.num_params == 0) || (i->second.num_params == req_params))
654                                 return i;
655         }
656         throw(std::logic_error("invalid number of arguments to " + name + "()"));
657 }
658
659
660 /*
661  *  Insert help strings
662  */
663
664 // Normal help string
665 static void insert_help(const char *topic, const char *str)
666 {
667         help.insert(make_pair(string(topic), string(str)));
668 }
669
670 // Help string for functions, automatically generates synopsis
671 static void insert_fcn_help(const char *name, const char *str)
672 {
673         typedef fcn_tab::const_iterator I;
674         pair<I, I> b = fcns.equal_range(name);
675         if (b.first != b.second) {
676                 string help_str = string(name) + "(";
677                 for (int i=0; i<b.first->second.num_params; i++) {
678                         if (i)
679                                 help_str += ", ";
680                         help_str += "expression";
681                 }
682                 help_str += ") - ";
683                 help_str += str;
684                 help.insert(make_pair(string(name), help_str));
685         }
686 }
687
688 // Help strings for functions from fcn_help_init array
689 static void insert_help(const fcn_help_init *p)
690 {
691         while (p->name) {
692                 insert_fcn_help(p->name, p->help);
693                 p++;
694         }
695 }
696
697
698 /*
699  *  Print help to cout
700  */
701
702 // Help for a given topic
703 static void print_help(const string &topic)
704 {
705         typedef help_tab::const_iterator I;
706         pair<I, I> b = help.equal_range(topic);
707         if (b.first == b.second)
708                 cout << "no help for '" << topic << "'\n";
709         else {
710                 for (I i=b.first; i!=b.second; i++)
711                         cout << i->second << endl;
712         }
713 }
714
715 // List of help topics
716 static void print_help_topics(void)
717 {
718         cout << "Available help topics:\n";
719         help_tab::const_iterator i;
720         string last_name = string("*");
721         int num = 0;
722         for (i=help.begin(); i!=help.end(); i++) {
723                 // Don't print duplicates
724                 if (i->first != last_name) {
725                         if (num)
726                                 cout << ", ";
727                         num++;
728                         cout << i->first;
729                         last_name = i->first;
730                 }
731         }
732         cout << "\nTo get help for a certain topic, type ?topic\n";
733 }
734
735
736 /*
737  *  Function name completion functions for readline
738  */
739
740 static char *fcn_generator(const char *text, int state)
741 {
742         static int len;                         // Length of word to complete
743         static fcn_tab::const_iterator index;   // Iterator to function being currently considered
744
745         // If this is a new word to complete, initialize now
746         if (state == 0) {
747                 index = fcns.begin();
748                 len = strlen(text);
749         }
750
751         // Return the next function which partially matches
752         while (index != fcns.end()) {
753                 const char *fcn_name = index->first.c_str();
754                 ++index;
755                 if (strncmp(fcn_name, text, len) == 0)
756                         return strdup(fcn_name);
757         }
758         return NULL;
759 }
760
761 static char **fcn_completion(const char *text, int start, int end)
762 {
763         if (rl_line_buffer[0] == '!') {
764                 // For shell commands, revert back to filename completion
765                 rl_completion_append_character = orig_completion_append_character;
766                 rl_basic_word_break_characters = orig_basic_word_break_characters;
767                 rl_completer_word_break_characters = rl_basic_word_break_characters;
768 #if (GINAC_RL_VERSION_MAJOR < 4) || (GINAC_RL_VERSION_MAJOR == 4 && GINAC_RL_VERSION_MINOR < 2)
769                 return completion_matches(const_cast<char *>(text), (CPFunction *)filename_completion_function);
770 #else
771                 return rl_completion_matches(text, rl_filename_completion_function);
772 #endif
773         } else {
774                 // Otherwise, complete function names
775                 rl_completion_append_character = '(';
776                 rl_basic_word_break_characters = " \t\n\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~";
777                 rl_completer_word_break_characters = rl_basic_word_break_characters;
778 #if (GINAC_RL_VERSION_MAJOR < 4) || (GINAC_RL_VERSION_MAJOR == 4 && GINAC_RL_VERSION_MINOR < 2)
779                 return completion_matches(const_cast<char *>(text), (CPFunction *)fcn_generator);
780 #else
781                 return rl_completion_matches(text, fcn_generator);
782 #endif
783         }
784 }
785
786 void greeting(void)
787 {
788     cout << "ginsh - GiNaC Interactive Shell (" << PACKAGE << " V" << VERSION << ")" << endl;
789     cout << "  __,  _______  Copyright (C) 1999-2002 Johannes Gutenberg University Mainz,\n"
790          << " (__) *       | Germany.  This is free software with ABSOLUTELY NO WARRANTY.\n"
791          << "  ._) i N a C | You are welcome to redistribute it under certain conditions.\n"
792          << "<-------------' For details type `warranty;'.\n" << endl;
793     cout << "Type ?? for a list of help topics." << endl;
794 }
795
796 /*
797  *  Main program
798  */
799
800 int main(int argc, char **argv)
801 {
802         // Print banner in interactive mode
803         if (isatty(0)) 
804                 greeting();
805
806         // Init function table
807         insert_fcns(builtin_fcns);
808         insert_fcns(extended_fcns);
809         ginsh_get_ginac_functions();
810
811         // Init help for operators (automatically generated from man page)
812         insert_help("operators", "Operators in falling order of precedence:");
813 #include "ginsh_op_help.h"
814
815         // Init help for built-in functions (automatically generated from man page)
816 #include "ginsh_fcn_help.h"
817
818         // Help for GiNaC functions is added manually
819         insert_help(builtin_help);
820         insert_help(extended_help);
821
822         // Init readline completer
823         rl_readline_name = argv[0];
824 #if (GINAC_RL_VERSION_MAJOR < 4) || (GINAC_RL_VERSION_MAJOR == 4 && GINAC_RL_VERSION_MINOR < 2)
825         rl_attempted_completion_function = (CPPFunction *)fcn_completion;
826 #else
827         rl_attempted_completion_function = fcn_completion;
828 #endif
829         orig_completion_append_character = rl_completion_append_character;
830         orig_basic_word_break_characters = rl_basic_word_break_characters;
831
832         // Init input file list, open first file
833         num_files = argc - 1;
834         file_list = argv + 1;
835         if (num_files) {
836                 yyin = fopen(*file_list, "r");
837                 if (yyin == NULL) {
838                         cerr << "Can't open " << *file_list << endl;
839                         exit(1);
840                 }
841                 num_files--;
842                 file_list++;
843         }
844
845         // Parse input, catch all remaining exceptions
846         int result;
847 again:  try {
848                 result = yyparse();
849         } catch (exception &e) {
850                 cerr << e.what() << endl;
851                 goto again;
852         }
853         return result;
854 }