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