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