]> www.ginac.de Git - ginac.git/blob - cint/ginaccint.bin.cpp
2641c18bce006a7f3175ab630237a81dd7098b2b
[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     return;
162 }
163 //----+----#----+----#----+----#----+----#----+----#----+----#----+----#----+----#
164 //  __,  _______  Cint: Copyright 1995-2000 Masaharu Goto and Agilent Technologies, JP." << endl
165 void greeting(void)
166 {
167     cout << "Welcome to GiNaC-cint (" << PACKAGE << " V" << VERSION << ")" << endl;
168     cout << "  __,  _______  GiNaC: (C) 1999-2000 Johannes Gutenberg University Mainz," << endl
169          << " (__) *       | Germany.  Cint C/C++ interpreter: (C) 1995-2000 Masaharu" << endl
170          << "  ._) i N a C | Goto and Agilent Technologies, Japan.  This is free software" << endl
171          << "<-------------' with ABSOLUTELY NO WARRANTY.  For details, type `.warranty'" << endl
172          << "Type .help for help." << endl
173          << endl;
174     return;
175 }
176
177 void helpmessage(void)
178 {
179     cout << "GiNaC-cint recognizes some special commands which start with a dot:" << endl << endl
180          << "  .cint                    switch to cint interactive mode (see cint" << endl
181          << "                           documentation for further details)" << endl
182          << "  .function                define the body of a function (necessary due to a" << endl
183          << "                           cint limitation)" << endl
184          << "  .help                    the text you are currently reading" << endl
185          << "  .q, .quit, .exit, .bye   quit GiNaC-cint" << endl
186          << "  .read filename           read a file from disk and execute it in GiNaC-cint" << endl
187          << "                           (recursive call is possible)" << endl
188          << "  .redirect [filename]     redirect 'OutXY = ...' output to a file" << endl
189          << "                           (.redirect alone redirects output back to console)" << endl
190          << "  .restart                 restart GiNaC-cint (does not re-read command line" << endl
191          << "                           files)" << endl
192          << "  .save filename           save the commands you have entered so far in a file" << endl
193          << "  .silent                  suppress 'OutXY = ...' output (variables are still" << endl
194          << "                           accessible)" << endl
195          << "  .warranty                information on redistribution and warranty" << endl
196          << "  .> [filename]            same as .redirect [filename]" << endl << endl
197          << "Instead of '.cmd' you can also write '//GiNaC-cint.cmd' to be compatible with" << endl
198          << "programs that will be compiled later." << endl
199          << "Additionally you can exit GiNaC-cint with quit; exit; or bye;" << endl
200          << endl;
201     return;
202 }
203
204 void warrantymessage(void)
205 {
206     cout << "GiNaC is free software; you can redistribute it and/or modify it under the" << endl
207          << "the terms of the GNU General Public License as published by the Free Software" << endl
208          << "Foundation; either version 2 of the License, or (at your option) any later" << endl
209          << "version." << endl
210          << "This program is distributed in the hope that it will be useful, but WITHOUT" << endl
211          << "ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS" << endl
212          << "FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more" << endl
213          << "details." << endl
214          << "You should have received a copy of the GNU General Public License along with" << endl
215          << "this program. If not, write to the Free Software Foundation, 675 Mass Ave," << endl
216          << "Cambridge, MA 02139, USA." << endl << endl;
217     cout << "Cint and associated tools are copyright by Agilent Technologies Japan Company" << endl
218          << "and Masaharu Goto <MXJ02154@niftyserve.or.jp>." << endl
219          << "Source code, binary executable or library of Cint and associated tools can be" << endl
220          << "used, modified and distributed with no royalty for any purpose provided that" << endl
221          << "the copyright notice appear in all copies and that both that copyright notice" << endl
222          << "and this permission notice appear in supporting documentation." << endl
223          << "Agilent Technologies Japan and the author make no representations about the" << endl
224          << "suitability of this software for any purpose.  It is provided \"AS IS\"" << endl
225          << "without express or implied warranty." << endl;
226     return;
227 }
228
229 string preprocess(char const * const line, bool & comment, bool & single_quote,
230                   bool & double_quote, unsigned & open_braces)
231 {
232     // "preprocess" the line entered to be able to decide if the command shall be
233     // executed directly or more input is needed or this is a special command
234
235     // ALL whitespace will be removed
236     // all comments (/* */ and //) will be removed
237     // open and close braces ( { and } ) outside strings will be counted 
238
239     /*
240     cout << "line=" << line << endl;
241     cout << "comment=" << comment << ", single_quote=" << single_quote
242          << ",double_quote=" << double_quote << ", open_braces=" << open_braces
243          << endl;
244     */
245     
246     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     /*
322     cout << "preprocessed=" << preprocessed << endl;
323     cout << "comment=" << comment << ", single_quote=" << single_quote
324          << ",double_quote=" << double_quote << ", open_braces=" << open_braces
325          << endl;
326     */
327     
328     return preprocessed;
329 }
330
331 void cleanup(void)
332 {
333     for (cplist::iterator it=filenames.begin(); it!=filenames.end(); ++it) {
334         cout << "removing file " << *it << endl;
335         remove(*it);
336         free(*it);
337     }
338 }
339
340 void sigterm_handler(int n)
341 {
342     exit(1);
343 }
344
345 void initialize(void)
346 {
347     if (isatty(0))
348         greeting();
349
350     atexit(cleanup);
351     signal(SIGTERM,sigterm_handler);
352     initialize_cint();
353 }    
354
355 void initialize_cint(void)
356 {
357     G__init_cint("cint");    /* initialize cint */
358
359     // no longer needed as of cint 5.14.31:
360     // exec_tempfile("#include <string>\n");
361
362 #ifndef NO_NAMESPACE_GINAC
363     exec_tempfile("using namespace GiNaC;");
364 #endif // ndef NO_NAMESPACE_GINAC
365     
366     exec_tempfile("ex LAST,LLAST,LLLAST;\n");
367     exec_tempfile("bool ginac_cint_internal_redirect_output=false;\n");
368     exec_tempfile("ofstream ginac_cint_internal_fout;\n");
369 }    
370
371 void restart(void)
372 {
373     cout << "Restarting GiNaC-cint." << endl;
374     G__scratch_all();
375     initialize_cint();
376 }
377
378 void redirect(string const & filename)
379 {
380     if (filename=="") {
381         cout << "Redirecting output back to console..." << endl;
382         exec_tempfile( string()
383                       +"ginac_cint_internal_redirect_output=false;\n"
384                       +"ginac_cint_internal_fout.close();");
385     } else {
386         cout << "Redirecting output to " << filename << "..." << endl;
387         exec_tempfile( string()
388                       +"ginac_cint_internal_redirect_output=true;\n"
389                       +"ginac_cint_internal_fout.open(\""+filename+"\");\n");
390     }
391 }
392
393 bool is_command(string const & command, string & preprocessed,
394                 string const & comparevalue, bool substr)
395 {
396     bool single_quote = false;
397     bool double_quote = false;
398     bool comment = false;
399     unsigned open_braces = 0;
400     if ((preprocessed=="."+comparevalue)||
401         substr&&(preprocessed.substr(0,comparevalue.length()+1)==
402                  "."+comparevalue)) {
403         return true;
404     }
405     if ((command=="//GiNaC-cint."+comparevalue+"\n")||
406         substr&&(command.substr(0,comparevalue.length()+13)==
407                  "//GiNaC-cint."+comparevalue)) {
408         preprocessed = preprocess(command.substr(12).c_str(),comment,
409                                   single_quote,double_quote,open_braces);
410         return true;
411     }
412     return false;
413 }       
414
415 bool readlines(istream * is, string & allcommands)
416 {
417     char const * line;
418     char prompt[G__ONELINE];
419     string linebuffer;
420     
421     bool quit = false;
422     bool eof = false;
423     bool next_command_is_function = false;
424     bool single_quote = false;
425     bool double_quote = false;
426     bool comment = false;
427     unsigned open_braces = 0;
428
429     while ((!quit)&&(!eof)) {
430         strcpy(prompt,PROMPT1);
431         bool end_of_command = false;
432         string command;
433         string preprocessed;
434         while (!end_of_command) {
435             if (is==NULL) {
436                 line = G__input(prompt);
437             } else {
438                 getline(*is,linebuffer);
439                 line = linebuffer.c_str();
440             }
441             command += line;
442             command += "\n";
443             preprocessed += preprocess(line,comment,single_quote,double_quote,open_braces);
444             if ((open_braces==0)&&(!single_quote)&&(!double_quote)&&(!comment)) {
445                 unsigned l = preprocessed.length();
446                 if ((l==0)||
447                     (preprocessed[0]=='#')||
448                     (preprocessed[0]=='.')||
449                     (preprocessed[l-1]==';')||
450                     (preprocessed[l-1]=='}')) {
451                     end_of_command = true;
452                 }
453             }
454             strcpy(prompt,PROMPT2);
455         }
456         if ((preprocessed=="quit;")||
457             (preprocessed=="exit;")||
458             (preprocessed=="bye;")||
459             (is_command(command,preprocessed,"quit"))||
460             (is_command(command,preprocessed,"exit"))||
461             (is_command(command,preprocessed,"bye"))||
462             (is_command(command,preprocessed,"q"))) {
463             quit = true;
464         } else if (is_command(command,preprocessed,"function")) {
465             cout << "next expression can be a function definition" << endl;
466             next_command_is_function=true;
467         } else if (is_command(command,preprocessed,"cint")) {
468             cout << endl << "switching to cint interactive mode" << endl;
469             cout << "'h' for help, 'q' to quit, '{ statements }' or 'p [expression]' to evaluate" << endl;
470             G__pause();
471             cout << "back from cint" << endl;
472         } else if (is_command(command,preprocessed,"help")) {
473             helpmessage();
474         } else if (is_command(command,preprocessed,"read",true)) {
475             quit=readfile(preprocessed.substr(5),allcommands);
476         } else if (is_command(command,preprocessed,"save",true)) {
477             command = "/* "+command+" */"; // we do not want the .save command itself in saved files
478             savefile(preprocessed.substr(5),allcommands);
479         } else if (is_command(command,preprocessed,"restart")) {
480             restart();
481         } else if (is_command(command,preprocessed,"redirect",true)) {
482             redirect(preprocessed.substr(9));
483         } else if (is_command(command,preprocessed,">",true)) {
484             redirect(preprocessed.substr(2));
485         } else if (is_command(command,preprocessed,"silent")) {
486             redirect("/dev/null");
487         } else if (is_command(command,preprocessed,"warranty")) {
488             warrantymessage();
489         /* test for more special commands
490         } else if (preprocessed==".xyz") {
491             cout << "special command (TBD): " << command << endl;
492         */
493         } else if (command.substr(0,2)=="#!") {
494             // ignore lines which indicate that this file is executed as a script
495         } else {
496             // cout << "now processing: " << command << endl;
497             if (next_command_is_function) {
498                 next_command_is_function = false;
499                 filenames.push_back(process_permanentfile(command));
500             } else {
501                 process_tempfile(command);
502             }
503         }
504         if (is!=NULL) {
505             // test for end of file if reading from a stream
506             eof=is->eof();
507         } else {
508             // save commands only when reading from keyboard
509             allcommands += command;
510         }
511
512     }
513     return quit;
514 }    
515
516 bool readfile(string const & filename, string & allcommands)
517 {
518     cout << "Reading commands from file " << filename << "." << endl;
519     bool quit = false;
520     ifstream fin;
521     fin.open(filename.c_str());
522     if (fin.good()) {
523         quit = readlines(&fin,allcommands);
524     } else {
525         cout << "Cannot open " << filename << " for reading." << endl;
526     }
527     fin.close();
528     return quit;
529 }
530
531 void savefile(string const & filename, string const & allcommands)
532 {
533     cout << "Saving commands to file " << filename << "." << endl;
534     ofstream fout;
535     fout.open(filename.c_str());
536     if (fout.good()) {
537         fout << allcommands;
538         if (!fout.good()) {
539             cout << "Cannot save commands to " << filename << "." << endl;
540         }
541     } else {
542         cout << "Cannot open " << filename << " for writing." << endl;
543     }
544     fout.close();
545 }
546
547 int main(int argc, char ** argv) 
548 {
549     string allcommands;
550     initialize();
551
552     bool quit = false;
553     bool argsexist = argc>1;
554
555     if (argsexist) {
556         allcommands = "/* Files given as command line arguments:\n";
557     }
558     
559     argc--; argv++;
560     while (argc && !quit) {
561         allcommands += *argv;
562         allcommands += "\n";
563         quit=readfile(*argv,allcommands);
564         argc--; argv++;
565     }
566
567     if (argsexist) {
568         allcommands += "*/\n";
569     }
570
571     if (!quit) {
572         readlines(NULL,allcommands);
573     }
574
575     return 0;
576 }