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