]> www.ginac.de Git - ginac.git/blob - cint/ginaccint.bin.cpp
edb0e806a6cb816220e64d78c6e2513b91a083a3
[ginac.git] / cint / ginaccint.bin.cpp
1 /* ginaccint.bin.cpp:  Binary depends on CINTSYSDIR, better don't call it
2  * directly.  Use the launcher (compiled from ginaccint.cpp) instead. */
3
4 #include "G__ci.h"   /* G__atpause is defined in G__ci.h */
5
6 #if (!defined(G__CINTVERSION)) || (G__CINTVERSION < 501460)
7 #error You need at least cint 5.14.60 to compile GiNaC-cint. Download it via http from root.cern.ch/root/Cint.html or via ftp from ftpthep.physik.uni-mainz.de/pub/cint
8 #endif // (!defined(G__CINTVERSION)) || (G__CINTVERSION < 501438)
9
10 #include <iostream>
11 #include <fstream>
12 #include <string>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include "ginac/ginac.h"
16 #include "config.h"
17 #include <list>
18
19 #ifndef NO_NAMESPACE_GINAC
20 using namespace GiNaC;
21 #endif // ndef NO_NAMESPACE_GINAC
22
23 extern "C" G__value G__exec_tempfile G__P((char *file));
24 extern "C" void G__store_undo_position(void);
25
26 #define PROMPT1 "GiNaC> "
27 #define PROMPT2 "     > "
28
29 #ifdef OBSCURE_CINT_HACK
30
31 #include <strstream>
32
33 template<class T>
34 std::string ToString(const T & t)
35 {
36         char buf[256];
37         ostrstream(buf,sizeof(buf)) << t << ends;
38         return buf;
39 }
40
41 basic * ex::last_created_or_assigned_bp = 0;
42 basic * ex::dummy_bp = 0;
43 long ex::last_created_or_assigned_exp = 0;
44
45 #endif // def OBSCURE_CINT_HACK
46
47 G__value exec_tempfile(std::string const & command);
48 char * process_permanentfile(std::string const & command);
49 void process_tempfile(std::string const & command);
50 void printversionmessage(std::ostream & os);
51 void greeting(void);
52 void helpmessage(void);
53 std::string preprocess(char const * const line, bool & comment, bool & single_quote,
54                        bool & double_quote, unsigned & open_braces);
55 void cleanup(void);
56 void sigterm_handler(int n);
57 void initialize(void);
58 void initialize_cint(void);
59 void restart(void);
60 bool is_command(std::string const & command, std::string & preprocessed,
61                 std::string const & comparevalue, bool substr=false);
62 bool readlines(istream * is, std::string & allcommands);
63 bool readfile(std::string const & filename, std::string & allcommands, bool shutup=false);
64 void savefile(std::string const & filename, std::string const & allcommands);
65
66 typedef list<char *> cplist;
67 cplist filenames;
68 bool redirect_output = false;
69 bool silent = false;
70
71 G__value exec_tempfile(std::string const & command)
72 {
73         G__value retval;
74         char *tmpfilename = tempnam(NULL,"ginac");
75         std::ofstream fout;
76         fout.open(tmpfilename);
77         fout << "{" << std::endl << command << std::endl << "}" << std::endl;
78         fout.close();
79         G__store_undo_position();
80         retval = G__exec_tempfile(tmpfilename);
81         G__security_recover(stdout);
82         remove(tmpfilename);
83         free(tmpfilename);
84         return retval;
85 }
86
87 char * process_permanentfile(std::string const & command)
88 {
89         char *tmpfilename = tempnam(NULL,"ginac");
90         if (!silent)
91                 std::cout << "creating file " << tmpfilename << std::endl;
92         std::ofstream fout;
93         fout.open(tmpfilename);
94         fout << command << std::endl;
95         fout.close();
96         G__store_undo_position();
97         G__loadfile(tmpfilename);
98         G__security_recover(stdout);
99         return tmpfilename;
100 }
101
102 void process_tempfile(std::string const & command)
103 {
104 #ifdef OBSCURE_CINT_HACK
105         static G__value ref_symbol = exec_tempfile("symbol ginac_cint_internal_symbol; ginac_cint_internal_symbol;");
106         static G__value ref_constant = exec_tempfile("constant ginac_cint_internal_constant; ginac_cint_internal_constant;");
107         static G__value ref_function = exec_tempfile("sin(ginac_cint_internal_symbol);");
108         static G__value ref_power = exec_tempfile("power(ex(ginac_cint_internal_symbol),ex(ginac_cint_internal_symbol));");
109         static G__value ref_numeric = exec_tempfile("numeric ginac_cint_internal_numeric; ginac_cint_internal_numeric;");
110         static G__value ref_ex = exec_tempfile("ex ginac_cint_internal_ex; ginac_cint_internal_ex;");
111         static bool basic_type_warning_already_displayed = false;
112 #endif // def OBSCURE_CINT_HACK
113
114         G__value retval = exec_tempfile(command);
115
116 #ifdef OBSCURE_CINT_HACK
117
118         #define TYPES_EQUAL(A,B) (((A).type==(B).type) && ((A).tagnum==(B).tagnum))
119         
120         static unsigned out_count = 0;
121         if (TYPES_EQUAL(retval,ref_ex)) {
122                 std::string varname = "Out"+ToString(++out_count);
123                 if (retval.obj.i!=ex::last_created_or_assigned_exp) {
124                         // an ex was returned, but this is not the ex which was created last
125                         // => this is not a temporary ex, but one that resides safely in memory
126                         
127                         // std::cout << "warning: using ex from retval (experimental)" << std::endl;
128                         ex::dummy_bp = ((ex *)(void *)(retval.obj.i))->bp;
129                         exec_tempfile("ex "+varname+"(*ex::dummy_bp);");
130                 } else if (ex::last_created_or_assigned_bp_can_be_converted_to_ex()) {
131                         exec_tempfile("ex "+varname+"(*ex::last_created_or_assigned_bp);");
132                 } else {
133                         std::cout << "warning: last_created_or_assigned_bp modified 0 or not evaluated or not dynallocated" << std::endl;
134                 }
135                 exec_tempfile(std::string()+"LLLAST=LLAST;\n"
136                               +"LLAST=LAST;\n"
137                               +"LAST="+varname+";\n"
138                               +"if (ginac_cint_internal_redirect_output&&"
139                               +"    ginac_cint_internal_fout.good()) {" 
140                               +"    ginac_cint_internal_fout << \""+varname+" = \" << "+varname+" << endl << endl;"
141                               +"} else {"
142                               +"    std::cout << \""+varname+" = \" << "+varname+" << endl << endl;"
143                               +"}");
144         } else if (TYPES_EQUAL(retval,ref_symbol)||
145                    TYPES_EQUAL(retval,ref_constant)||
146                    TYPES_EQUAL(retval,ref_function)||
147                    TYPES_EQUAL(retval,ref_power)||
148                    TYPES_EQUAL(retval,ref_numeric)) {
149                 if (!basic_type_warning_already_displayed) {
150                         std::cout << std::endl
151                                   <<"WARNING: The return value of the last expression you entered was a symbol," << std::endl
152                                   << "constant, function, power or numeric, which cannot be safely displayed." << std::endl
153                                   << "To force the output, cast it explicitly to type 'ex' or use 'cout'," << std::endl
154                                   << "for example (assume 'x' is a symbol):" << std::endl
155                                   << PROMPT1 "ex(x);" << std::endl
156                                   << "OutX = x" << std::endl << std::endl
157                                   << PROMPT1 "cout << x << endl;" << std::endl
158                                   << "x" << std::endl << std::endl
159                                   << "This warning will not be shown again." << std::endl;
160                         basic_type_warning_already_displayed = true;
161                 }
162         }
163 #endif // def OBSCURE_CINT_HACK
164         return;
165 }
166
167 void printversionmessage(std::ostream & os)
168 {
169         os << "GiNaC-cint (" << PACKAGE << " V" << VERSION
170            << ", Cint V" << G__CINTVERSION/1000000
171            << '.' << G__CINTVERSION/1000%1000
172            << '.' << G__CINTVERSION%1000 << ')' << endl;
173         return;
174 }
175
176 void greeting(void)
177 {
178         std::cout << "Welcome to ";
179         printversionmessage(std::cout);
180         std::cout << "  __,  _______  GiNaC: (C) 1999-2001 Johannes Gutenberg University Mainz,\n"
181                   << " (__) *       | Germany.  Cint C/C++ interpreter: (C) 1995-2001 Masaharu\n"
182                   << "  ._) i N a C | Goto and Agilent Technologies, Japan.  This is free software\n"
183                   << "<-------------' with ABSOLUTELY NO WARRANTY.  For details, type `.warranty'\n"
184                   << "Type `.help' for help.\n\n";
185         return;
186 }
187
188 void helpmessage(void)
189 {
190     std::cout << "GiNaC-cint recognizes some special commands which start with a dot:\n\n"
191                   << "  .cint                    switch to cint interactive mode (see cint\n"
192                   << "                           documentation for further details)\n"
193                   << "  .function                define the body of a function (necessary due to a\n"
194                   << "                           cint limitation)\n"
195                   << "  .help                    the text you are currently reading\n"
196                   << "  .q, .quit, .exit, .bye   quit GiNaC-cint\n"
197                   << "  .read filename           read a file from disk and execute it in GiNaC-cint\n"
198                   << "                           (recursive call is possible)\n"
199                   << "  .redirect [filename]     redirect 'OutXY = ...' output to a file\n"
200                   << "                           (.redirect alone redirects output back to console)\n"
201                   << "  .restart                 restart GiNaC-cint (does not re-read command line\n"
202                   << "                           files)\n"
203                   << "  .save filename           save the commands you have entered so far in a file\n"
204                   << "  .silent                  suppress 'OutXY = ...' output (variables are still\n"
205                   << "                           accessible)\n"
206                   << "  .warranty                information on redistribution and warranty\n"
207                   << "  .> [filename]            same as .redirect [filename]\n\n"
208                   << "Instead of '.cmd' you can also write '//GiNaC-cint.cmd' to be compatible with\n"
209                   << "programs that will be compiled later.\n"
210                   << "Additionally you can exit GiNaC-cint with quit; exit; or bye;\n\n";
211     return;
212 }
213
214 void warrantymessage(void)
215 {
216         std::cout << "GiNaC is free software; you can redistribute it and/or modify it under the\n"
217                   << "the terms of the GNU General Public License as published by the Free Software\n"
218                   << "Foundation; either version 2 of the License, or (at your option) any later\n"
219                   << "version.\n"
220                   << "This program is distributed in the hope that it will be useful, but WITHOUT\n"
221                   << "ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n"
222                   << "FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n"
223                   << "details.\n"
224                   << "You should have received a copy of the GNU General Public License along with\n"
225                   << "this program. If not, write to the Free Software Foundation, 675 Mass Ave,\n"
226                   << "Cambridge, MA 02139, USA.\n\n";
227         std::cout << "Cint and associated tools are copyright by Agilent Technologies Japan Company\n"
228                   << "and Masaharu Goto <MXJ02154@niftyserve.or.jp>.\n"
229                   << "Source code, binary executable or library of Cint and associated tools can be\n"
230                   << "used, modified and distributed with no royalty for any purpose provided that\n"
231                   << "the copyright notice appear in all copies and that both that copyright notice\n"
232                   << "and this permission notice appear in supporting documentation.\n"
233                   << "Agilent Technologies Japan and the author make no representations about the\n"
234                   << "suitability of this software for any purpose.  It is provided \"AS IS\"\n"
235                   << "without express or implied warranty.\n";
236     return;
237 }
238
239 /** "preprocess" the line entered to be able to decide if the command shall be
240  *  executed directly or more input is needed or this is a special command.
241  *  All whitespace will be removed.  All comments will be removed.  Open and
242  *  close braces ( { and } ) outside strings will be counted. */
243 std::string preprocess(char const * const line, bool & comment, bool & single_quote,
244                        bool & double_quote, unsigned & open_braces)
245 {
246         std::string preprocessed;
247         int pos = 0;
248         bool end = false;
249         bool escape = false;
250         bool slash = false;
251         bool asterisk = false;
252         while ((line[pos]!='\0')&&!end) {
253                 if (escape) {
254                         // last character was a \, ignore this one
255                         escape = false;
256                 } else if (slash) {
257                         // last character was a /, test if * or /
258                         slash = false;
259                         if (line[pos]=='/') {
260                                 end = true;
261                         } else if (line[pos]=='*') {
262                                 comment = true;
263                         } else {
264                                 preprocessed += '/';
265                                 preprocessed += line[pos];
266                         }
267                 } else if (asterisk) {
268                         // last character was a *, test if /
269                         asterisk = false;
270                         if (line[pos]=='/') {
271                                 comment = false;
272                         } else if (line[pos]=='*') {
273                                 preprocessed += '*';
274                                 asterisk = true;
275                         }
276                 } else {
277                         switch (line[pos]) {
278                         case ' ':
279                         case '\t':
280                         case '\n':
281                         case '\r':
282                                 // whitespace: ignore
283                                 break;
284                         case '\\':
285                                 // escape character, ignore next
286                                 escape = true;
287                                 break;
288                         case '"':
289                                 if ((!single_quote)&&(!comment)) {
290                                         double_quote = !double_quote;
291                                 }
292                                 break;
293                                 case '\'':
294                                         if ((!double_quote)&&(!comment)) {
295                                                 single_quote = !single_quote;
296                                         }
297                                         break;
298                         case '{':
299                                 if ((!single_quote)&&(!double_quote)&&(!comment)) {
300                                         ++open_braces;
301                                 }
302                                 break;
303                         case '}':
304                                 if ((!single_quote)&&(!double_quote)&&(!comment)&&(open_braces>0)) {
305                                         --open_braces;
306                                 }
307                                 break;
308                         case '/':
309                                 slash = true;
310                                 break;
311                         case '*':
312                                 asterisk = true;
313                                 break;
314                         default:
315                                 preprocessed += line[pos];
316                         }
317                 }
318                 ++pos;
319         }
320         
321         return preprocessed;
322 }
323
324 void cleanup(void)
325 {
326         for (cplist::iterator it=filenames.begin(); it!=filenames.end(); ++it) {
327                 if (!silent)
328                         std::cout << "removing file " << *it << std::endl;
329                 remove(*it);
330                 free(*it);
331         }
332 }
333
334 void sigterm_handler(int n)
335 {
336         G__scratch_all();
337         exit(1);
338 }
339
340 void initialize(void)
341 {
342         atexit(cleanup);
343         signal(SIGTERM, sigterm_handler);
344         initialize_cint();
345 }    
346
347 void initialize_cint(void)
348 {
349         G__init_cint("cint");    /* initialize cint */
350         
351 #ifndef NO_NAMESPACE_GINAC
352         exec_tempfile("using namespace GiNaC;");
353 #endif // ndef NO_NAMESPACE_GINAC
354         
355         exec_tempfile("ex LAST,LLAST,LLLAST;\n");
356         exec_tempfile("bool ginac_cint_internal_redirect_output=false;\n");
357         exec_tempfile("ofstream ginac_cint_internal_fout;\n");
358 }    
359
360 void restart(void)
361 {
362         std::cout << "Restarting GiNaC-cint." << std::endl;
363         G__scratch_all();
364         initialize_cint();
365 }
366
367 void redirect(std::string const & filename,
368               bool shutup=false)
369 {
370         if (filename=="") {
371                 if (!shutup)
372                         std::cout << "Redirecting output back to console..." << std::endl;
373                 exec_tempfile(std::string()
374                               +"ginac_cint_internal_redirect_output=false;\n"
375                               +"ginac_cint_internal_fout.close();");
376         } else {
377                 if (!shutup)
378                         std::cout << "Redirecting output to " << filename << "..." << std::endl;
379                 exec_tempfile(std::string()
380                               +"ginac_cint_internal_redirect_output=true;\n"
381                               +"ginac_cint_internal_fout.open(\""+filename+"\");\n");
382         }
383 }
384
385 /** Sort out command line options and evaluate them.  Returns true if it
386  *  succeeds and false otherwise. */
387 bool evaloption(const std::string & option)
388 {
389         if (option=="--version") {
390                 printversionmessage(std::cout);
391                 exit(0);
392         }
393         if (option=="--help") {
394                 printversionmessage(std::cout);
395                 std::cout << "usage: ginaccint [option] [file ...]\n";
396                 std::cout << " --help           print this help message and exit\n"
397                           << " --silent         invoke ginaccint in silent mode\n"
398                           << " --version        print GiNaC version and Cint version and exit\n";
399                 exit(0);
400         }
401         if (option=="--silent") {
402                 redirect("/dev/null",true);
403                 silent = true;
404                 return true;
405         }
406         return false;
407 }
408
409 bool is_command(std::string const & command,
410                 std::string & preprocessed,
411                 std::string const & comparevalue,
412                 bool substr)
413 {
414         bool single_quote = false;
415         bool double_quote = false;
416         bool comment = false;
417         unsigned open_braces = 0;
418         if ((preprocessed=="."+comparevalue)||
419                 substr&&(preprocessed.substr(0,comparevalue.length()+1)==
420                                  "."+comparevalue)) {
421                 return true;
422         }
423         if ((command=="//GiNaC-cint."+comparevalue+"\n") ||
424                 substr &&
425                 (command.substr(0,comparevalue.length()+13)=="//GiNaC-cint."+comparevalue)) {
426                 preprocessed = preprocess(command.substr(12).c_str(),comment,
427                                           single_quote,double_quote,open_braces);
428                 return true;
429         }
430         return false;
431 }
432
433 bool readlines(istream * is,
434                std::string & allcommands)
435 {
436         char const * line;
437         char prompt[G__ONELINE];
438         std::string linebuffer;
439         
440         bool quit = false;
441         bool eof = false;
442         bool next_command_is_function = false;
443         bool single_quote = false;
444         bool double_quote = false;
445         bool comment = false;
446         unsigned open_braces = 0;
447
448         while ((!quit)&&(!eof)) {
449                 strcpy(prompt,PROMPT1);
450                 bool end_of_command = false;
451                 std::string command;
452                 std::string preprocessed;
453                 while (!end_of_command) {
454                         if (is==NULL) {
455                                 line = G__input(prompt);
456                         } else {
457                                 getline(*is,linebuffer);
458                                 line = linebuffer.c_str();
459                         }
460                         command += line;
461                         command += "\n";
462                         preprocessed += preprocess(line,comment,single_quote,double_quote,open_braces);
463                         if ((open_braces==0)&&(!single_quote)&&(!double_quote)&&(!comment)) {
464                                 unsigned l = preprocessed.length();
465                                 if ((l==0)||
466                                     (preprocessed[0]=='#')||
467                                     (preprocessed[0]=='.')||
468                                     (preprocessed[l-1]==';')||
469                                     (preprocessed[l-1]=='}')) {
470                                     end_of_command = true;
471                                 }
472                         }
473                         strcpy(prompt,PROMPT2);
474                 }
475                 if ((preprocessed=="quit;")||
476                     (preprocessed=="exit;")||
477                     (preprocessed=="bye;")||
478                     (is_command(command,preprocessed,"quit"))||
479                     (is_command(command,preprocessed,"exit"))||
480                     (is_command(command,preprocessed,"bye"))||
481                     (is_command(command,preprocessed,"q"))) {
482                     quit = true;
483                 } else if (is_command(command,preprocessed,"function")) {
484                         if (!silent)
485                                 std::cout << "next expression can be a function definition" << std::endl;
486                         next_command_is_function = true;
487                 } else if (is_command(command,preprocessed,"cint")) {
488                         std::cout << std::endl << "switching to cint interactive mode" << std::endl;
489                         std::cout << "'h' for help, 'q' to quit, '{ statements }' or 'p [expression]' to evaluate" << std::endl;
490                         G__pause();
491                         std::cout << "back from cint" << std::endl;
492                 } else if (is_command(command,preprocessed,"help")) {
493                         helpmessage();
494                 } else if (is_command(command,preprocessed,"read",true)) {
495                         quit = readfile(preprocessed.substr(5),allcommands);
496                 } else if (is_command(command,preprocessed,"save",true)) {
497                         command = "/* "+command+" */"; // we do not want the .save command itself in saved files
498                         savefile(preprocessed.substr(5),allcommands);
499                 } else if (is_command(command,preprocessed,"restart")) {
500                         restart();
501                 } else if (is_command(command,preprocessed,"redirect",true)) {
502                         redirect(preprocessed.substr(9));
503                 } else if (is_command(command,preprocessed,">",true)) {
504                         redirect(preprocessed.substr(2));
505                 } else if (is_command(command,preprocessed,"silent")) {
506                         if (!silent) {
507                                 redirect("/dev/null");
508                                 silent = true;
509                         } else {
510                                 redirect("");
511                                 silent = false;
512                         }
513                 } else if (is_command(command,preprocessed,"warranty")) {
514                         warrantymessage();
515                 /* insert tests for more special commands here */
516                 } else if (command.substr(0,2)=="#!") {
517                         // ignore lines which indicate that this file is executed as a script
518                 } else {
519                         // std::cout << "now processing: " << command << std::endl;
520                         if (next_command_is_function) {
521                                 next_command_is_function = false;
522                                 filenames.push_back(process_permanentfile(command));
523                         } else {
524                                 process_tempfile(command);
525                         }
526                 }
527                 if (is!=NULL) {
528                         // test for end of file if reading from a stream
529                         eof = is->eof();
530                 } else {
531                         // save commands only when reading from keyboard
532                         allcommands += command;
533                 }
534
535         }
536         return quit;
537
538
539 bool readfile(std::string const & filename,
540               std::string & allcommands,
541               bool shutup = false)
542 {
543         if (!shutup)
544                 std::cout << "Reading commands from file " << filename << "." << std::endl;
545         bool quit = false;
546         std::ifstream fin;
547         fin.open(filename.c_str());
548         if (fin.good())
549                 quit = readlines(&fin,allcommands);
550         else
551                 std::cout << "Cannot open " << filename << " for reading." << std::endl;
552         fin.close();
553         return quit;
554 }
555
556 void savefile(std::string const & filename, std::string const & allcommands)
557 {
558         std::cout << "Saving commands to file " << filename << "." << std::endl;
559         std::ofstream fout;
560         fout.open(filename.c_str());
561         if (fout.good()) {
562                 fout << allcommands;
563                 if (!fout.good()) {
564                         std::cout << "Cannot save commands to " << filename << "." << std::endl;
565                 }
566         } else {
567                 std::cout << "Cannot open " << filename << " for writing." << std::endl;
568         }
569         fout.close();
570 }
571
572 int main(int argc, char * *argv) 
573 {
574         std::string allcommands;
575         initialize();
576         
577         bool quit = false;
578         // sort out and evaluate recognized options from the argument list
579         for (int i=1; i<argc; ++i)
580                 if (evaloption(argv[i])) {
581                         for (int j=i; j<argc-1; ++j)
582                                 argv[j] = argv[j+1];
583                         --argc;
584                 }
585         bool argsexist = argc>1;
586         
587         // greet the user if it makes sense
588         if (isatty(0) && !silent)
589                 greeting();
590         
591         // evaluate files given as command line arguments
592         if (argsexist) {
593                 allcommands = "/* Files given as command line arguments:\n";
594                 --argc;
595                 while (argc && !quit) {
596                         allcommands += std::string(argv[argc])+'\n';
597                         quit = readfile(argv[argc], allcommands, silent);
598                         --argc;
599                 }
600                 allcommands += "*/\n";
601         }
602         
603         // evaluate input from command line or script
604         if (!quit)
605                 readlines(NULL, allcommands);
606         
607         return 0;
608 }