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