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