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