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