2 * ginsh.y - GiNaC Interactive Shell, input grammar definition
4 * This file must be processed with yacc/bison
15 #include <sys/resource.h>
18 #include <sys/types.h>
29 #include <readline/readline.h>
30 #include <readline/history.h>
36 #include <GiNaC/ginac.h>
40 // Original readline settings
41 static int orig_completion_append_character;
42 static char *orig_basic_word_break_characters;
44 // Expression stack for ", "" and """
45 static void push(const ex &e);
48 // Start and end time for the time() function
49 static struct rusage start_time, end_time;
51 // Table of functions (a multimap, because one function may appear with different
52 // numbers of parameters)
53 typedef ex (*fcnp)(const exprseq &e);
54 typedef ex (*fcnp2)(const exprseq &e, int serial);
57 fcn_desc() : p(NULL), num_params(0) {}
58 fcn_desc(fcnp func, int num) : p(func), num_params(num), is_ginac(false) {}
59 fcn_desc(fcnp2 func, int num, int ser) : p((fcnp)func), num_params(num), is_ginac(true), serial(ser) {}
61 fcnp p; // Pointer to function
62 int num_params; // Number of parameters (0 = arbitrary)
63 bool is_ginac; // Flag: function is GiNaC function
64 int serial; // GiNaC function serial number (if is_ginac == true)
67 typedef multimap<string, fcn_desc> fcn_tab;
70 static fcn_tab::const_iterator find_function(const ex &sym, int req_params);
72 static ex lst2matrix(const ex &l);
75 /* Tokens (T_LITERAL means a literal value returned by the parser, but not
76 of class numeric or symbol (e.g. a constant or the FAIL object)) */
77 %token T_NUMBER T_SYMBOL T_LITERAL T_DIGITS T_QUOTE T_QUOTE2 T_QUOTE3
78 %token T_EQUAL T_NOTEQ T_LESSEQ T_GREATEREQ T_MATRIX_BEGIN T_MATRIX_END
80 %token T_QUIT T_PRINT T_TIME T_XYZZY T_INVENTORY T_LOOK T_SCORE
82 /* Operator precedence and associativity */
85 %left '<' '>' T_LESSEQ T_GREATEREQ
110 } catch (exception &e) {
111 cerr << e.what() << endl;
115 | T_PRINT '(' exp ')' ';'
119 } catch (exception &e) {
120 cerr << e.what() << endl;
125 | T_XYZZY {cout << "Nothing happens.\n";}
126 | T_INVENTORY {cout << "You're not carrying anything.\n";}
127 | T_LOOK {cout << "You're in a twisty little maze of passages, all alike.\n";}
130 cout << "If you were to quit now, you would score ";
131 cout << (syms.size() > 350 ? 350 : syms.size());
132 cout << " out of a possible 350.\n";
134 | error ';' {yyclearin; yyerrok;}
137 exp : T_NUMBER {$$ = $1;}
138 | T_SYMBOL {$$ = $1.eval();}
139 | '\'' T_SYMBOL '\'' {$$ = $2;}
140 | T_LITERAL {$$ = $1;}
141 | T_DIGITS {$$ = $1;}
142 | T_QUOTE {$$ = exstack[0];}
143 | T_QUOTE2 {$$ = exstack[1];}
144 | T_QUOTE3 {$$ = exstack[2];}
145 | T_TIME {getrusage(RUSAGE_SELF, &start_time);} '(' exp ')'
147 getrusage(RUSAGE_SELF, &end_time);
148 $$ = (end_time.ru_utime.tv_sec - start_time.ru_utime.tv_sec) +
149 (end_time.ru_stime.tv_sec - start_time.ru_stime.tv_sec) +
150 double(end_time.ru_utime.tv_usec - start_time.ru_utime.tv_usec) / 1e6 +
151 double(end_time.ru_stime.tv_usec - start_time.ru_stime.tv_usec) / 1e6;
153 | T_SYMBOL '(' exprseq ')'
155 fcn_tab::const_iterator i = find_function($1, $3.nops());
156 if (i->second.is_ginac) {
157 $$ = ((fcnp2)(i->second.p))(static_cast<const exprseq &>(*($3.bp)), i->second.serial);
159 $$ = (i->second.p)(static_cast<const exprseq &>(*($3.bp)));
162 | T_DIGITS '=' T_NUMBER
163 {$$ = $3; Digits = ex_to_numeric($3).to_int();}
165 {$$ = $3; const_cast<symbol *>(&ex_to_symbol($1))->assign($3);}
166 | exp T_EQUAL exp {$$ = $1 == $3;}
167 | exp T_NOTEQ exp {$$ = $1 != $3;}
168 | exp '<' exp {$$ = $1 < $3;}
169 | exp T_LESSEQ exp {$$ = $1 <= $3;}
170 | exp '>' exp {$$ = $1 > $3;}
171 | exp T_GREATEREQ exp {$$ = $1 >= $3;}
172 | exp '+' exp {$$ = $1 + $3;}
173 | exp '-' exp {$$ = $1 - $3;}
174 | exp '*' exp {$$ = $1 * $3;}
175 | exp '/' exp {$$ = $1 / $3;}
176 | exp '%' exp {$$ = $1 % $3;}
177 | '-' exp %prec NEG {$$ = -$2;}
178 | '+' exp %prec NEG {$$ = $2;}
179 | exp '^' exp {$$ = power($1, $3);}
180 | exp '!' {$$ = factorial($1);}
181 | '(' exp ')' {$$ = $2;}
182 | '[' list_or_empty ']' {$$ = $2;}
183 | T_MATRIX_BEGIN matrix T_MATRIX_END {$$ = lst2matrix($2);}
186 exprseq : exp {$$ = exprseq($1);}
187 | exprseq ',' exp {exprseq es(static_cast<exprseq &>(*($1.bp))); $$ = es.append($3);}
190 list_or_empty: /* empty */ {$$ = *new lst;}
194 list : exp {$$ = lst($1);}
195 | list ',' exp {lst l(static_cast<lst &>(*($1.bp))); $$ = l.append($3);}
198 matrix : T_MATRIX_BEGIN row T_MATRIX_END {$$ = lst($2);}
199 | matrix ',' T_MATRIX_BEGIN row T_MATRIX_END {lst l(static_cast<lst &>(*($1.bp))); $$ = l.append($4);}
202 row : exp {$$ = lst($1);}
203 | row ',' exp {lst l(static_cast<lst &>(*($1.bp))); $$ = l.append($3);}
212 const int GINSH_VERSION = 0;
213 const int GINSH_REVISION = 3;
215 // Error print routine
218 cerr << s << " at " << yytext << endl;
222 // Push expression "e" onto the expression stack (for ", "" and """)
223 static void push(const ex &e)
225 exstack[2] = exstack[1];
226 exstack[1] = exstack[0];
235 static ex f_beta(const exprseq &e) {return gamma(e[0])*gamma(e[1])/gamma(e[0]+e[1]);}
236 static ex f_denom(const exprseq &e) {return e[0].denom();}
237 static ex f_eval1(const exprseq &e) {return e[0].eval();}
238 static ex f_evalf1(const exprseq &e) {return e[0].evalf();}
239 static ex f_expand(const exprseq &e) {return e[0].expand();}
240 static ex f_gcd(const exprseq &e) {return gcd(e[0], e[1]);}
241 static ex f_lcm(const exprseq &e) {return lcm(e[0], e[1]);}
242 static ex f_lsolve(const exprseq &e) {return lsolve(e[0], e[1]);}
243 static ex f_nops(const exprseq &e) {return e[0].nops();}
244 static ex f_normal1(const exprseq &e) {return e[0].normal();}
245 static ex f_numer(const exprseq &e) {return e[0].numer();}
246 static ex f_power(const exprseq &e) {return power(e[0], e[1]);}
247 static ex f_sqrt(const exprseq &e) {return sqrt(e[0]);}
248 static ex f_subs2(const exprseq &e) {return e[0].subs(e[1]);}
250 #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))
252 static ex f_charpoly(const exprseq &e)
254 CHECK_ARG(0, matrix, charpoly);
255 CHECK_ARG(1, symbol, charpoly);
256 return ex_to_matrix(e[0]).charpoly(ex_to_symbol(e[1]));
259 static ex f_coeff(const exprseq &e)
261 CHECK_ARG(1, symbol, coeff);
262 CHECK_ARG(2, numeric, coeff);
263 return e[0].coeff(ex_to_symbol(e[1]), ex_to_numeric(e[2]).to_int());
266 static ex f_collect(const exprseq &e)
268 CHECK_ARG(1, symbol, collect);
269 return e[0].collect(ex_to_symbol(e[1]));
272 static ex f_content(const exprseq &e)
274 CHECK_ARG(1, symbol, content);
275 return e[0].content(ex_to_symbol(e[1]));
278 static ex f_degree(const exprseq &e)
280 CHECK_ARG(1, symbol, degree);
281 return e[0].degree(ex_to_symbol(e[1]));
284 static ex f_determinant(const exprseq &e)
286 CHECK_ARG(0, matrix, determinant);
287 return ex_to_matrix(e[0]).determinant();
290 static ex f_diag(const exprseq &e)
293 matrix &m = *new matrix(dim, dim);
294 for (int i=0; i<dim; i++)
295 m.set(i, i, e.op(i));
299 static ex f_diff2(const exprseq &e)
301 CHECK_ARG(1, symbol, diff);
302 return e[0].diff(ex_to_symbol(e[1]));
305 static ex f_diff3(const exprseq &e)
307 CHECK_ARG(1, symbol, diff);
308 CHECK_ARG(2, numeric, diff);
309 return e[0].diff(ex_to_symbol(e[1]), ex_to_numeric(e[2]).to_int());
312 static ex f_divide(const exprseq &e)
315 if (divide(e[0], e[1], q))
321 static ex f_eval2(const exprseq &e)
323 CHECK_ARG(1, numeric, eval);
324 return e[0].eval(ex_to_numeric(e[1]).to_int());
327 static ex f_evalf2(const exprseq &e)
329 CHECK_ARG(1, numeric, evalf);
330 return e[0].evalf(ex_to_numeric(e[1]).to_int());
333 static ex f_has(const exprseq &e)
335 return e[0].has(e[1]) ? exONE() : exZERO();
338 static ex f_inverse(const exprseq &e)
340 CHECK_ARG(0, matrix, inverse);
341 return ex_to_matrix(e[0]).inverse();
344 static ex f_is(const exprseq &e)
346 CHECK_ARG(0, relational, is);
347 return (bool)ex_to_relational(e[0]) ? exONE() : exZERO();
350 static ex f_lcoeff(const exprseq &e)
352 CHECK_ARG(1, symbol, lcoeff);
353 return e[0].lcoeff(ex_to_symbol(e[1]));
356 static ex f_ldegree(const exprseq &e)
358 CHECK_ARG(1, symbol, ldegree);
359 return e[0].ldegree(ex_to_symbol(e[1]));
362 static ex f_normal2(const exprseq &e)
364 CHECK_ARG(1, numeric, normal);
365 return e[0].normal(ex_to_numeric(e[1]).to_int());
368 static ex f_op(const exprseq &e)
370 CHECK_ARG(1, numeric, op);
371 int n = ex_to_numeric(e[1]).to_int();
372 if (n < 0 || n >= e[0].nops())
373 throw(std::out_of_range("second argument to op() is out of range"));
377 static ex f_prem(const exprseq &e)
379 CHECK_ARG(2, symbol, prem);
380 return prem(e[0], e[1], ex_to_symbol(e[2]));
383 static ex f_primpart(const exprseq &e)
385 CHECK_ARG(1, symbol, primpart);
386 return e[0].primpart(ex_to_symbol(e[1]));
389 static ex f_quo(const exprseq &e)
391 CHECK_ARG(2, symbol, quo);
392 return quo(e[0], e[1], ex_to_symbol(e[2]));
395 static ex f_rem(const exprseq &e)
397 CHECK_ARG(2, symbol, rem);
398 return rem(e[0], e[1], ex_to_symbol(e[2]));
401 static ex f_series2(const exprseq &e)
403 CHECK_ARG(1, symbol, series);
404 return e[0].series(ex_to_symbol(e[1]), exZERO());
407 static ex f_series3(const exprseq &e)
409 CHECK_ARG(1, symbol, series);
410 return e[0].series(ex_to_symbol(e[1]), e[2]);
413 static ex f_series4(const exprseq &e)
415 CHECK_ARG(1, symbol, series);
416 CHECK_ARG(3, numeric, series);
417 return e[0].series(ex_to_symbol(e[1]), e[2], ex_to_numeric(e[3]).to_int());
420 static ex f_sqrfree(const exprseq &e)
422 CHECK_ARG(1, symbol, sqrfree);
423 return sqrfree(e[0], ex_to_symbol(e[1]));
426 static ex f_subs3(const exprseq &e)
428 CHECK_ARG(1, lst, subs);
429 CHECK_ARG(2, lst, subs);
430 return e[0].subs(ex_to_lst(e[1]), ex_to_lst(e[2]));
433 static ex f_tcoeff(const exprseq &e)
435 CHECK_ARG(1, symbol, tcoeff);
436 return e[0].tcoeff(ex_to_symbol(e[1]));
439 static ex f_trace(const exprseq &e)
441 CHECK_ARG(0, matrix, trace);
442 return ex_to_matrix(e[0]).trace();
445 static ex f_transpose(const exprseq &e)
447 CHECK_ARG(0, matrix, transpose);
448 return ex_to_matrix(e[0]).transpose();
451 static ex f_unassign(const exprseq &e)
453 CHECK_ARG(0, symbol, unassign);
454 (const_cast<symbol *>(&ex_to_symbol(e[0])))->unassign();
458 static ex f_unit(const exprseq &e)
460 CHECK_ARG(1, symbol, unit);
461 return e[0].unit(ex_to_symbol(e[1]));
464 static ex f_dummy(const exprseq &e)
466 throw(std::logic_error("dummy function called (shouldn't happen)"));
471 * Add all registered GiNaC functions to ginsh
474 static ex f_ginac_function(const exprseq &es, int serial)
476 return function(serial, es).eval(1);
479 void ginsh_get_ginac_functions(void)
481 vector<registered_function_info>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
484 fcns.insert(make_pair(i->name, fcn_desc(f_ginac_function, i->nparams, serial)));
492 * Find a function given a name and number of parameters. Throw exceptions on error.
495 static fcn_tab::const_iterator find_function(const ex &sym, int req_params)
497 const string &name = ex_to_symbol(sym).getname();
498 typedef fcn_tab::const_iterator I;
499 pair<I, I> b = fcns.equal_range(name);
500 if (b.first == b.second)
501 throw(std::logic_error("unknown function '" + name + "'"));
503 for (I i=b.first; i!=b.second; i++)
504 if ((i->second.num_params == 0) || (i->second.num_params == req_params))
507 throw(std::logic_error("invalid number of arguments to " + name + "()"));
512 * Convert list of lists to matrix
515 static ex lst2matrix(const ex &l)
517 if (!is_ex_of_type(l, lst))
518 throw(std::logic_error("internal error: argument to lst2matrix() is not a list"));
520 // Find number of rows and columns
521 int rows = l.nops(), cols = 0, i, j;
522 for (i=0; i<rows; i++)
523 if (l.op(i).nops() > cols)
524 cols = l.op(i).nops();
526 // Allocate and fill matrix
527 matrix &m = *new matrix(rows, cols);
528 for (i=0; i<rows; i++)
529 for (j=0; j<cols; j++)
530 if (l.op(i).nops() > j)
531 m.set(i, j, l.op(i).op(j));
533 m.set(i, j, exZERO());
539 * Function name completion functions for readline
542 static char *fcn_generator(char *text, int state)
544 static int len; // Length of word to complete
545 static fcn_tab::const_iterator index; // Iterator to function being currently considered
547 // If this is a new word to complete, initialize now
549 index = fcns.begin();
553 // Return the next function which partially matches
554 while (index != fcns.end()) {
555 const char *fcn_name = index->first.c_str();
557 if (strncmp(fcn_name, text, len) == 0)
558 return strdup(fcn_name);
563 static char **fcn_completion(char *text, int start, int end)
565 if (rl_line_buffer[0] == '!') {
566 // For shell commands, revert back to filename completion
567 rl_completion_append_character = orig_completion_append_character;
568 rl_basic_word_break_characters = orig_basic_word_break_characters;
569 return completion_matches(text, filename_completion_function);
571 // Otherwise, complete function names
572 rl_completion_append_character = '(';
573 rl_basic_word_break_characters = " \t\n\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~";
574 return completion_matches(text, fcn_generator);
583 int main(int argc, char **argv)
585 // Print banner in interactive mode
587 cout << "ginsh - GiNaC Interactive Shell V" << GINSH_VERSION << "." << GINSH_REVISION << endl;
588 cout << "Copyright (C) 1999 Johannes Gutenberg Universitaet Mainz, Germany\n";
589 cout << "This is free software, and you are welcome to redistribute it\n";
590 cout << "under certain conditions; see the file COPYING for details.\n";
593 // Init table of built-in functions
594 fcns.insert(make_pair(string("beta"), fcn_desc(f_beta, 2)));
595 fcns.insert(make_pair(string("charpoly"), fcn_desc(f_charpoly, 2)));
596 fcns.insert(make_pair(string("coeff"), fcn_desc(f_coeff, 3)));
597 fcns.insert(make_pair(string("collect"), fcn_desc(f_collect, 2)));
598 fcns.insert(make_pair(string("content"), fcn_desc(f_content, 2)));
599 fcns.insert(make_pair(string("degree"), fcn_desc(f_degree, 2)));
600 fcns.insert(make_pair(string("denom"), fcn_desc(f_denom, 1)));
601 fcns.insert(make_pair(string("determinant"), fcn_desc(f_determinant, 1)));
602 fcns.insert(make_pair(string("diag"), fcn_desc(f_diag, 0)));
603 fcns.insert(make_pair(string("diff"), fcn_desc(f_diff2, 2)));
604 fcns.insert(make_pair(string("diff"), fcn_desc(f_diff3, 3)));
605 fcns.insert(make_pair(string("divide"), fcn_desc(f_divide, 2)));
606 fcns.insert(make_pair(string("eval"), fcn_desc(f_eval1, 1)));
607 fcns.insert(make_pair(string("eval"), fcn_desc(f_eval2, 2)));
608 fcns.insert(make_pair(string("evalf"), fcn_desc(f_evalf1, 1)));
609 fcns.insert(make_pair(string("evalf"), fcn_desc(f_evalf2, 2)));
610 fcns.insert(make_pair(string("expand"), fcn_desc(f_expand, 1)));
611 fcns.insert(make_pair(string("gcd"), fcn_desc(f_gcd, 2)));
612 fcns.insert(make_pair(string("has"), fcn_desc(f_has, 2)));
613 fcns.insert(make_pair(string("inverse"), fcn_desc(f_inverse, 1)));
614 fcns.insert(make_pair(string("is"), fcn_desc(f_is, 1)));
615 fcns.insert(make_pair(string("lcm"), fcn_desc(f_lcm, 2)));
616 fcns.insert(make_pair(string("lcoeff"), fcn_desc(f_lcoeff, 2)));
617 fcns.insert(make_pair(string("ldegree"), fcn_desc(f_ldegree, 2)));
618 fcns.insert(make_pair(string("lsolve"), fcn_desc(f_lsolve, 2)));
619 fcns.insert(make_pair(string("nops"), fcn_desc(f_nops, 1)));
620 fcns.insert(make_pair(string("normal"), fcn_desc(f_normal1, 1)));
621 fcns.insert(make_pair(string("normal"), fcn_desc(f_normal2, 2)));
622 fcns.insert(make_pair(string("numer"), fcn_desc(f_numer, 1)));
623 fcns.insert(make_pair(string("op"), fcn_desc(f_op, 2)));
624 fcns.insert(make_pair(string("power"), fcn_desc(f_power, 2)));
625 fcns.insert(make_pair(string("prem"), fcn_desc(f_prem, 3)));
626 fcns.insert(make_pair(string("primpart"), fcn_desc(f_primpart, 2)));
627 fcns.insert(make_pair(string("quo"), fcn_desc(f_quo, 3)));
628 fcns.insert(make_pair(string("rem"), fcn_desc(f_rem, 3)));
629 fcns.insert(make_pair(string("series"), fcn_desc(f_series2, 2)));
630 fcns.insert(make_pair(string("series"), fcn_desc(f_series3, 3)));
631 fcns.insert(make_pair(string("series"), fcn_desc(f_series4, 4)));
632 fcns.insert(make_pair(string("sqrfree"), fcn_desc(f_sqrfree, 2)));
633 fcns.insert(make_pair(string("sqrt"), fcn_desc(f_sqrt, 1)));
634 fcns.insert(make_pair(string("subs"), fcn_desc(f_subs2, 2)));
635 fcns.insert(make_pair(string("subs"), fcn_desc(f_subs3, 3)));
636 fcns.insert(make_pair(string("tcoeff"), fcn_desc(f_tcoeff, 2)));
637 fcns.insert(make_pair(string("time"), fcn_desc(f_dummy, 0)));
638 fcns.insert(make_pair(string("trace"), fcn_desc(f_trace, 1)));
639 fcns.insert(make_pair(string("transpose"), fcn_desc(f_transpose, 1)));
640 fcns.insert(make_pair(string("unassign"), fcn_desc(f_unassign, 1)));
641 fcns.insert(make_pair(string("unit"), fcn_desc(f_unit, 2)));
642 ginsh_get_ginac_functions();
644 // Init readline completer
645 rl_readline_name = argv[0];
646 rl_attempted_completion_function = (CPPFunction *)fcn_completion;
647 orig_completion_append_character = rl_completion_append_character;
648 orig_basic_word_break_characters = rl_basic_word_break_characters;
650 // Parse input, catch all remaining exceptions
654 } catch (exception &e) {
655 cerr << e.what() << endl;