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