source: Sophya/trunk/SophyaLib/SysTools/commander.cc@ 2520

Last change on this file since 2520 was 2518, checked in by ansari, 22 years ago

Suite (presque finie) des modifications de l'interpreteur - gestion des variables en particulier - Reste au moins un bug ds CExpressionEvaluator - Reza 18/03/2004

File size: 55.0 KB
Line 
1#include "commander.h"
2#include <stdio.h>
3#include <stdlib.h>
4#include <unistd.h>
5#include <ctype.h>
6#include <math.h>
7
8#include "strutil.h"
9#include "strutilxx.h"
10#include "cexpre.h"
11#include "rpneval.h"
12#include "srandgen.h"
13
14
15namespace SOPHYA {
16
17// Differents code de retour specifiques
18#define CMD_RETURN_RC 99900
19#define CMD_BREAK_RC 99990
20#define CMD_BREAKEXE_RC 99999
21
22// ------------------------------------------------------------
23// Bloc de commandes (Foreach, ...)
24// Classe CommanderBloc
25// ------------------------------------------------------------
26/*!
27 \class SOPHYA::CommanderBloc
28 \ingroup SysTools
29 Class for internal use by SOPHYA::Commander to handle loops
30*/
31class CommanderBloc {
32public:
33 enum BType { BT_None, BT_ForeachList, BT_ForeachInt, BT_ForeachFloat,
34 BT_ForeachLineInFile };
35
36 CommanderBloc(Commander* piac, CommanderBloc* par, string& kw, vector<string>& args);
37 ~CommanderBloc();
38 inline CommanderBloc* Parent() { return(parent); }
39 inline bool CheckOK() { return blkok; }
40 inline void AddLine(string& line)
41 { lines.push_back(line); bloclineid.push_back(lines.size()); }
42 void AddLine(string& line, string& kw);
43 inline void AddBloc(CommanderBloc* blk)
44 { blocs.push_back(blk); bloclineid.push_back(-blocs.size()); }
45
46 // Execution complete du bloc (boucle)
47 int Execute();
48 // Execution pour un element de bloc
49 int ExecuteOnce(string& lvv);
50
51 inline int& TestLevel() { return testlevel; }
52 inline int& LoopLevel() { return looplevel; }
53 inline bool CheckBloc()
54 { return ((testlevel == 0)&&(looplevel == 0)&&(!scrdef)); }
55
56protected:
57 Commander* _commander;
58 CommanderBloc* parent;
59 bool blkok; // true -> block OK
60 BType typ; // foreach , integer loop, float loop, test
61 string varname;
62 string filename; // forinfile bloc
63 vector<string> strlist;
64 vector<string> lines;
65 vector<CommanderBloc *> blocs;
66 vector<int> bloclineid;
67 int i1,i2,di;
68 float f1,f2,df;
69 int testlevel; // niveau d'imbrication des if
70 int looplevel; // niveau d'imbrication des for/foreach
71 bool scrdef; // true -> commande defscript ds for/foreach
72};
73
74/* --Methode-- */
75CommanderBloc::CommanderBloc(Commander* piac, CommanderBloc* par, string& kw, vector<string>& args)
76{
77_commander = piac;
78parent = par;
79blkok = false;
80typ = BT_None;
81i1 = 0; i2 = -1; di = 1;
82f1 = 0.; f2 = -1.; df = 1.;
83testlevel = looplevel = 0;
84scrdef = false;
85
86if ((args.size() < 2) || !isalpha((int)args[0][0]) ) return;
87if ((kw != "foreach") && (kw != "for") && (kw != "forinfile")) return;
88if (!piac->CheckVarName(args[0])) return;
89varname = args[0];
90
91//if (isalpha((int)args[1][0]) ) { This is a foreach bloc with string list
92if (kw == "forinfile") {
93 filename = args[1];
94 typ = BT_ForeachLineInFile;
95 blkok = true;
96}
97else if (kw == "foreach" ) { // This is a foreach bloc with string list
98 if ( (args[1] == "(") && (args[args.size()-1] == ")") ) {
99 // foreach varname ( w1 w2 w3 ... )
100 for(int kk=2; kk<args.size()-1; kk++) strlist.push_back(args[kk]);
101 }
102 else {
103 // foreach varname WordVectorName
104 if (!piac->GetVar(args[1], strlist)) return;
105 }
106 if (strlist.size() < 1) return;
107 typ = BT_ForeachList;
108 blkok = true;
109}
110else { // This is an integer or float loop
111 size_t l = args[1].length();
112 size_t p = args[1].find(':');
113 size_t pp = args[1].find('.');
114 bool fl = (pp < l) ? true : false; // Float loop or integer loop
115 if (p >= l) return; // Syntaxe error
116 string a1 = args[1].substr(0, p);
117 string aa = args[1].substr(p+1);
118 p = aa.find(':');
119 string a2, a3;
120 bool hasa3 = false;
121 if (p < aa.length() ) {
122 a2 = aa.substr(0,p);
123 a3 = aa.substr(p+1);
124 hasa3 = true;
125 }
126 else a2 = aa;
127 if (fl) {
128 typ = BT_ForeachFloat;
129 blkok = true;
130 f1 = atof(a1.c_str());
131 f2 = atof(a2.c_str());
132 if (hasa3) df = atof(a3.c_str());
133 else df = 1.;
134 }
135 else {
136 typ = BT_ForeachInt;
137 blkok = true;
138 i1 = atoi(a1.c_str());
139 i2 = atoi(a2.c_str());
140 if (hasa3) di = atoi(a3.c_str());
141 else di = 1;
142 }
143 }
144}
145
146/* --Methode-- */
147CommanderBloc::~CommanderBloc()
148{
149for(int k=0; k<blocs.size(); k++) delete blocs[k];
150}
151
152/* --Methode-- */
153void CommanderBloc::AddLine(string& line, string& kw)
154{
155 AddLine(line);
156 if (kw == "if") testlevel++;
157 else if (kw == "endif") testlevel--;
158 else if ((kw == "for") || (kw == "foreach")) looplevel++;
159 else if (kw == "end") looplevel--;
160 else if (kw == "defscript") scrdef = true;
161}
162
163/* --Methode-- */
164int CommanderBloc::Execute()
165{
166int k=0;
167char buff[32];
168int rcc = 0;
169
170int mxloop = _commander->GetMaxLoopLimit();
171
172if (typ == BT_ForeachLineInFile) { // foreach line in file loop
173 ifstream is(filename.c_str());
174 char buff[256];
175 string line;
176 while (!is.eof()) {
177 rcc = 0;
178 is.clear();
179 is.getline(buff, 256);
180 line += buff;
181 if (is.good()) {
182 rcc = ExecuteOnce(line);
183 line = "";
184 }
185 if (rcc == CMD_BREAKEXE_RC) return rcc;
186 else if (rcc == CMD_BREAK_RC) break;
187 }
188}
189else if (typ == BT_ForeachList) { // foreach string loop
190 for(k=0; k<strlist.size(); k++) {
191 rcc = ExecuteOnce(strlist[k]);
192 if (rcc == CMD_BREAKEXE_RC) return rcc;
193 else if (rcc == CMD_BREAK_RC) break;
194 }
195}
196else if (typ == BT_ForeachInt) { // Integer loop
197 for(int i=i1; i<i2; i+=di) {
198 k++;
199 if ((mxloop>0) && (k > mxloop)) {
200 cout << ">>> Maximum CommanderBloc loop limit ("<< mxloop << ") -> break " << endl;
201 break;
202 }
203 sprintf(buff, "%d", i);
204 string lvv = buff;
205 rcc = ExecuteOnce(lvv);
206 if (rcc == CMD_BREAKEXE_RC) return rcc;
207 else if (rcc == CMD_BREAK_RC) break;
208 }
209}
210else if (typ == BT_ForeachFloat) { // float loop
211 for(double f=f1; f<f2; f+=df) {
212 k++;
213 if ((mxloop>0) && (k > mxloop)) {
214 cout << ">>> Maximum CommanderBloc loop limit ("<< mxloop << ") -> break " << endl;
215 break;
216 }
217 sprintf(buff, "%g", f);
218 string lvv = buff;
219 rcc = ExecuteOnce(lvv);
220 if (rcc == CMD_BREAKEXE_RC) return rcc;
221 else if (rcc == CMD_BREAK_RC) break;
222 }
223}
224return(rcc);
225}
226
227/* --Methode-- */
228int CommanderBloc::ExecuteOnce(string& lvv)
229{
230 int kj=0;
231 int kk=0;
232 int rcc = 0;
233 _commander->SetVar(varname, lvv);
234 for(kj=0; kj<bloclineid.size(); kj++) {
235 rcc = 0;
236 kk = bloclineid[kj];
237 if (kk > 0)
238 rcc = _commander->Interpret(lines[kk-1]);
239 else
240 rcc = blocs[-kk-1]->Execute();
241 if (rcc == CMD_BREAKEXE_RC) return (rcc);
242 if (rcc == CMD_BREAK_RC) break;
243 }
244 return rcc;
245}
246
247// ---------------------------------------------------------------
248// Classe CommanderScript
249// Definition et execution d'un script de Commander
250// script : Une liste de commande Commander - Lors de l'execution,
251// les variables-argument $# $0 $1 sont definies.
252// ---------------------------------------------------------------
253
254/*!
255 \class SOPHYA::CommanderScript
256 \ingroup SysTools
257 Class for internal use by SOPHYA::Commander to handle functions
258 or scripts
259*/
260
261class CommanderScript {
262public:
263 CommanderScript(Commander* piac, string const& name, string const& comm);
264 virtual ~CommanderScript();
265
266 void AddLine(string& line, string& kw);
267 virtual int Execute(vector<string>& args);
268
269 inline string& Name() { return mName; }
270 inline string& Comment() { return mComm; }
271 inline int& TestLevel() { return testlevel; }
272 inline int& LoopLevel() { return looplevel; }
273 inline bool CheckScript()
274 { return ((testlevel == 0)&&(looplevel == 0)&&(!scrdef)&&fgok); }
275
276protected:
277 Commander* _commander;
278 string mName;
279 string mComm;
280 vector<string> lines;
281 int testlevel; // niveau d'imbrication des if
282 int looplevel; // niveau d'imbrication des for/foreach
283 bool scrdef; // true -> commande defscript ds for/foreach
284 bool fgok; // Script name OK
285
286};
287
288/* --Methode-- */
289CommanderScript::CommanderScript(Commander* piac, string const& name,
290 string const& comm)
291{
292_commander = piac;
293testlevel = looplevel = 0;
294scrdef = false;
295mName = name;
296if (!isalpha(name[0])) fgok = false;
297else fgok = true;
298mComm = comm;
299}
300
301/* --Methode-- */
302CommanderScript::~CommanderScript()
303{
304}
305
306/* --Methode-- */
307void CommanderScript::AddLine(string& line, string& kw)
308{
309 if (kw == "if") testlevel++;
310 else if (kw == "endif") testlevel--;
311 else if ((kw == "for") || (kw == "foreach")) looplevel++;
312 else if (kw == "end") looplevel--;
313 else if (kw == "defscript") scrdef = true;
314 lines.push_back(line);
315}
316
317/* --Methode-- */
318int CommanderScript::Execute(vector<string>& args)
319{
320 int rcc;
321 if (!CheckScript()) return(-1);
322 cout << " CommanderScript::Execute() - Executing script " << Name() << endl;
323 for(int k=0; k<lines.size(); k++) {
324 rcc = _commander->Interpret(lines[k]);
325 if ( (rcc == CMD_BREAKEXE_RC) || (rcc == CMD_RETURN_RC) ) break;
326 }
327 return(rcc);
328}
329
330// ------------------------------------------------------------
331// Classe Commander
332// ------------------------------------------------------------
333typedef void (* DlModuleInitEndFunction) ();
334
335/*!
336 \class SOPHYA::Commander
337 \ingroup SysTools
338 Simple command interpreter with c-shell like syntax and dynamic
339 load capabilities. Can be used to add scripting capabilities
340 to applications
341*/
342
343#define _MAGENTA_ 1
344
345static Commander* cur_commander = NULL;
346/* --Methode-- */
347Commander::Commander()
348{
349system("cp history.pic hisold.pic");
350hist.open("history.pic");
351histon = true;
352trace = false; timing = false;
353gltimer = NULL;
354felevel = 0;
355
356mulinecmd = "";
357mulinefg = false;
358spromptmul = "Cmd> ";
359SetCurrentPrompt(spromptmul);
360SetDefaultPrompt(spromptmul);
361curscript = NULL;
362
363_xstatus = 0;
364 _retstr = "";
365
366// Controle du flot d'execution
367 fgexebrk = false;
368
369CmdBlks.push(NULL);
370list<char> xtx;
371TestsStack.push(xtx);
372curtestresult = true;
373
374// Numero de help-groupe courant - Le premier groupe ajoute aura un gid = 1
375// gid = 0 n'existe pas : c'est le groupe de toutes les commandes
376cmdgrpid = 0;
377
378string grp = "Commander";
379string gdesc = "Basic (generic) interpreter (class SOPHYA::Commander) builtin commands";
380AddHelpGroup(grp, gdesc);
381
382string kw = "Commander";
383string usage;
384usage = ">>> (Commander) Interpreter's keywords : \n";
385usage += " > set varname string # To set a variable, $varname \n";
386usage += " > unset varname # clear variable definition \n";
387usage += " > rpneval varname RPNExpression # Reverse Polish Notation evaluation \n";
388usage += " > varname = ArithmeticExpression # C-like Expression evaluation \n";
389usage += " > varname = 'String' # Set variable vname \n";
390usage += " > var2words varname wordvarname [sep] # to break varname into words \n";
391usage += " > echo string # output string \n";
392usage += " > echo2file filename string # Append the string to the specified file \n";
393usage += " > alias name string # define a command alias \n";
394usage += " > foreach varname ( string-list ) # Loop \n";
395usage += " > for varname i1:i2[:di] # Integer loop \n";
396usage += " > for varname f1:f2[:df] # Float loop \n";
397usage += " > forinfile varname FileName # Loop over lines in file \n";
398usage += " > end # end loops \n";
399usage += " > if ( test ) then # Conditional test : a == != < > <= >= b \n";
400usage += " > else # Conditional \n";
401usage += " > endif # End of conditional if bloc \n";
402usage += " > break # Delete (clears) all test and loop blocs \n";
403usage += " > return # Stops command execution from a file \n";
404usage += " > defscript endscript # Command script definition \n";
405usage += " > listvars # List of variable names and values \n";
406usage += " > listalias # List of alias names and values \n";
407usage += " > listcommands # List of all known commands \n";
408usage += " > listscripts # List of all known scripts \n";
409usage += " > clearcript # Clear a script definition \n";
410usage += " > exec filename # Execute commands from file \n";
411usage += " > help <command_name> # <command_name> usage info \n";
412usage += " > sleep nsec # sleep nsec seconds \n";
413usage += " > readstdin varname # reads a line from stdin into $varname \n";
414usage += " > timingon timingoff traceon traceoff \n";
415RegisterHelp(kw, usage, grp);
416
417kw = "RPNEvaluator";
418usage = " Reverse Polish Notation (HP calculator like) expression evaluation \n";
419usage += " >> Stack: \n";
420usage += " ... (4) (3) z=(2) y=(1) x=(0)=Stack.Top() \n";
421usage += " >> Examples: \n";
422usage += " - sin(PI/6): pi 6 / sin \n";
423usage += " - 1*2*...*5: 1 2 3 4 5 product \n";
424usage += " - x=x+y: x = $x $y * \n";
425usage += " >>> Stack operations : \n";
426usage += " print x<>y pop push (duplicate x) \n";
427usage += " >>> Constants (Cst pushed to stack): \n";
428usage += " pi e \n";
429usage += " >>> Arithmetic operators (x,y) --> x@y \n";
430usage += " + - * / % ( (int)y % (int)x )\n";
431usage += " >>> F(X): x --> F(x) \n";
432usage += " chs sqrt sq log log10 exp \n";
433usage += " fabs floor ceil \n";
434usage += " cos sin tan acos asin atan deg2rad rad2deg \n";
435usage += " >>> F(X,Y): (x,y) --> F(x,y) \n";
436usage += " pow atan2 \n";
437usage += " >>> F(): random number generators \n";
438usage += " rand (flat 0..1) norand (normal/gaussian) \n";
439usage += " >>> Stack sum/product/mean/sigma/sigma^2 \n";
440usage += " sum product mean sigma sigma2 sigmean (y->sigma x->mean) \n";
441RegisterHelp(kw, usage, grp);
442
443kw = "autoiniranf";
444usage = "> Automatic random number generator initialisation\n";
445usage += " by Auto_Ini_Ranf(int lp) \n";
446usage += " Usage: autoiniranf";
447RegisterCommand(kw, usage, NULL, grp);
448
449kw = "shell execute";
450usage = "> shell command_string # Execute shell command\n";
451usage += "> cshell command_string # Execute cshell command\n";
452usage += "---Examples:\n";
453usage += " > shell ls\n";
454usage += " > cshell echo '$LD_LIBRARY_PATH'; map2cl -h; ls\n";
455usage += " > shell myfile.csh [arg1] [arg2] [...]\n";
456usage += " (where the first line of \"myfile.csh\" is \"#!/bin/csh\")\n";
457RegisterCommand(kw, usage, NULL, grp);
458
459
460AddInterpreter(this);
461curcmdi = this;
462}
463
464/* --Methode-- */
465Commander::~Commander()
466{
467hist.close();
468if (gltimer) { delete gltimer; gltimer = NULL; }
469Modmap::iterator it;
470for(it = modmap.begin(); it != modmap.end(); it++) {
471 string name = (*it).first + "_end";
472 DlModuleInitEndFunction fend = (*it).second->GetFunction(name);
473 if (fend) fend();
474 delete (*it).second;
475 }
476
477for(ScriptList::iterator sit = mScripts.begin();
478 sit != mScripts.end(); sit++) delete (*sit).second;
479
480if (cur_commander == this) cur_commander = NULL;
481}
482
483/* --Methode-- */
484Commander* Commander::GetInterpreter()
485{
486return(cur_commander);
487}
488
489/* --Methode-- */
490string Commander::Name()
491{
492return("Commander");
493}
494
495/* --Methode-- */
496void Commander::AddHelpGroup(string& grp, string& desc)
497{
498 int gid;
499 CheckHelpGrp(grp, gid, desc);
500}
501
502/* --Methode-- */
503void Commander::RegisterCommand(string& keyw, string& usage, CmdExecutor * ce, string& grp)
504{
505if (!ce) {
506 RegisterHelp(keyw, usage, grp);
507 return;
508 }
509int gid;
510CheckHelpGrp(grp,gid);
511cmdex cme;
512cme.group = gid;
513cme.us = usage;
514cme.cex = ce;
515cmdexmap[keyw] = cme;
516}
517
518/* --Methode-- */
519void Commander::RegisterHelp(string& keyw, string& usage, string& grp)
520{
521int gid;
522CheckHelpGrp(grp,gid);
523cmdex cme;
524cme.group = gid;
525cme.us = usage;
526cme.cex = NULL;
527helpexmap[keyw] = cme;
528}
529
530/* --Methode-- */
531bool Commander::CheckHelpGrp(string& grp, int& gid, string& desc)
532{
533gid = 0;
534CmdHGroup::iterator it = cmdhgrp.find(grp);
535if (it == cmdhgrp.end()) {
536 cmdgrpid++; gid = cmdgrpid;
537 hgrpst hgs; hgs.gid = gid; hgs.desc = desc;
538 cmdhgrp[grp] = hgs;
539 return true;
540 }
541else {
542 if (desc.length() > 0) (*it).second.desc = desc;
543 gid = (*it).second.gid;
544 return false;
545}
546}
547
548
549/* --Methode-- */
550void Commander::LoadModule(string& fnameso, string& name)
551{
552PDynLinkMgr * dynlink = new PDynLinkMgr(fnameso, false);
553if (dynlink == NULL) {
554 cerr << "Commander/LoadModule_Error: Pb opening SO " << fnameso << endl;
555 return;
556 }
557string fname = name + "_init";
558DlModuleInitEndFunction finit = dynlink->GetFunction(fname);
559if (!finit) {
560 cerr << "Commander/LoadModule_Error: Pb linking " << fname << endl;
561 return;
562 }
563cout << "Commander/LoadModule_Info: Initialisation module" << name
564 << " " << fname << "() ..." << endl;
565finit();
566modmap[name] = dynlink;
567return;
568}
569
570/* --Methode-- */
571void Commander::AddInterpreter(CmdInterpreter * cl)
572{
573if (!cl) return;
574interpmap[cl->Name()] = cl;}
575
576/* --Methode-- */
577void Commander::SelInterpreter(string& name)
578{
579InterpMap::iterator it = interpmap.find(name);
580if (it == interpmap.end()) return;
581curcmdi = (*it).second;
582}
583
584
585
586/* Fonction */
587static string GetStringFrStdin(Commander* piac)
588{
589char buff[128];
590fgets(buff, 128, stdin);
591buff[127] = '\0';
592return((string)buff);
593}
594
595/* --Methode-- */
596int Commander::Interpret(string& s)
597{
598int rc = 0;
599ScriptList::iterator sit;
600
601// On saute de commandes vides
602size_t l;
603l = s.length();
604if (!mulinefg && (l < 1)) return(0);
605
606// On enregistre les commandes
607if (histon) hist << s << endl;
608
609if (s[0] == '#') return(0); // si c'est un commentaire
610
611// Logique de gestion des lignes suite
612// un \ en derniere position indique la presence d'une ligne suite
613size_t lnb = s.find_last_not_of(' ');
614if (s[lnb] == '\\' ) { // Lignes suite ...
615 mulinecmd += s.substr(0,lnb);
616 if (!mulinefg) {
617 spromptmul = GetCurrentPrompt();
618 SetCurrentPrompt("...? ");
619 mulinefg = true;
620 }
621 return(0);
622}
623
624if (mulinefg) { // Il y avait des lignes suite
625 s = mulinecmd + s;
626 l = s.length();
627 mulinecmd = "";
628 mulinefg = false;
629 SetCurrentPrompt(spromptmul);
630}
631
632// Removing leading blanks
633size_t p,q;
634
635// On enleve le dernier caractere, si celui-ci est \n
636if (s[l-1] == '\n') s[l-1] = '\0';
637p=s.find_first_not_of(" \t");
638if (p < l) s = s.substr(p);
639// >>>> Substitution d'alias (1er mot)
640CmdStrList::iterator it;
641p = 0;
642q = s.find_first_of(" \t");
643l = s.length();
644string w1 = (q < l) ? s.substr(p,q-p) : s.substr(p);
645it = mAliases.find(w1);
646if (it != mAliases.end()) {
647 s = (q < l) ? ((*it).second + s.substr(q)) : (*it).second ;
648 l = s.length();
649 p=s.find_first_not_of(" \t");
650 if (p < l) s = s.substr(p);
651 p = 0;
652 q = s.find_first_of(" ");
653 }
654
655// >>>> Separating keyword
656string toks,kw;
657if (q < l)
658 { kw = s.substr(p,q-p); toks = s.substr(q, l-q); }
659else { kw = s.substr(p,l-p); toks = ""; }
660
661// les mot-cle end else endif doivent etre le seul mot de la ligne
662if ( (kw == "end") || (kw == "else") || (kw == "endif") || (kw == "endscript") ) {
663 size_t ltk = toks.length();
664 if (toks.find_first_not_of(" \t") < ltk) {
665 cerr << "Commander::Interpret()/syntax error near end else endif endscript \n"
666 << "line: " << s << endl;
667 _xstatus = 91;
668 return(91);
669 }
670}
671
672// On verifie si on est en train de definir un script
673if (curscript) {
674 if (kw == "endscript") {
675 if (curscript->CheckScript()) {
676 sit = mScripts.find(curscript->Name());
677 if (sit != mScripts.end()) {
678 cout << "Commander::Interpret() replacing script "
679 << curscript->Name() << endl;
680 CommanderScript* scr = mScripts[curscript->Name()];
681 mScripts.erase(sit);
682 delete scr;
683 }
684 cout << "Commander::Interpret() Script " << curscript->Name()
685 << " defined successfully" << endl;
686 mScripts[curscript->Name()] = curscript;
687 SetCurrentPrompt("Cmd> ");
688 curscript = NULL;
689 _xstatus = 0;
690 return(0);
691 }
692 else {
693 cout << "Commander::Interpret() Error in Script " << curscript->Name()
694 << " definition " << endl;
695 SetCurrentPrompt("Cmd> ");
696 curscript = NULL;
697 _xstatus = 92;
698 return(92);
699 }
700 }
701 else curscript->AddLine(s, kw);
702 _xstatus = 0;
703 return(0);
704}
705// On verifie si nous sommes dans un bloc (for , foreach)
706if (CmdBlks.top() != NULL) { // On est dans un bloc
707 if ( (kw == "for") || (kw == "foreach")) felevel++;
708 else if (kw == "end") felevel--;
709 if (felevel == 0) { // Il faut executer le bloc
710 CommanderBloc* curb = CmdBlks.top();
711 CmdBlks.top() = curb->Parent();
712 SetCurrentPrompt("Cmd> ");
713 if (!curb->CheckBloc()) {
714 cerr << "Commander::Interpret()/syntax error - unbalenced if ... endif"
715 << " within for/foreach bloc ! " << endl;
716 delete curb;
717 _xstatus = 93;
718 return(93);
719 }
720 // cout << " *DBG* Executing bloc " << endl;
721 bool ohv = histon;
722 histon = false;
723 if (curtestresult) {
724 // We push also CommanderBloc and testresult on the stack
725 CmdBlks.push(NULL);
726 list<char> xtx;
727 TestsStack.push(xtx);
728 curb->Execute();
729 // And CommanderBloc and TestResult from the corresponding stacks
730 PopStack(false);
731 }
732 SetCurrentPrompt(defprompt);
733 delete curb;
734 histon = ohv;
735 }
736 else CmdBlks.top()->AddLine(s, kw);
737 _xstatus = 0;
738 return(0);
739}
740else if (kw == "end") {
741 cerr << "Commander::Interpret()/syntax error - end outside for/foreach bloc \n"
742 << "line: " << s << endl;
743 _xstatus = 94;
744 return(94);
745}
746
747// Sommes-nous dans un bloc de test if then else
748if (TestsStack.top().size() > 0) { // Nous sommes ds un bloc if
749 if (kw == "else") {
750 if ((*tresit) & 2) {
751 cerr << "Commander::Interpret()/syntax error - multiple else in if bloc \n"
752 << "line: " << s << endl;
753 _xstatus = 95;
754 return(95);
755 }
756 else {
757 const char * npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
758 if ((*tresit)&1) curtestresult = false;
759 SetCurrentPrompt(npr);
760 (*tresit) |= 2;
761 _xstatus = 0;
762 return(0);
763 }
764 }
765 else if (kw == "endif") {
766 list<char>::iterator dbit = tresit;
767 tresit--;
768 TestsStack.top().erase(dbit);
769 const char * npr = "Cmd> ";
770 if (TestsStack.top().size() > 1) {
771 curtestresult = true;
772 list<char>::iterator it;
773 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
774 // Si on n'est pas ds le else et le if est faux
775 if ( !((*it)&2) && !((*it)&1) ) curtestresult = false;
776 // Si on est ds else et le if etait vrai !
777 if ( ((*it)&2) && ((*it)&1) ) curtestresult = false;
778 if (!curtestresult) break;
779 }
780
781 if (!((*tresit)&2))
782 npr = ((*tresit)&1) ? "if-T> " : "if-F> ";
783 else
784 npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
785 }
786 else curtestresult = true;
787 SetCurrentPrompt(npr);
788 _xstatus = 0;
789 return(0);
790 }
791}
792else if ((kw == "else") || (kw == "endif")) {
793 cerr << "Commander::Interpret()/syntax error - else,endif outside if bloc \n"
794 << "line: " << s << endl;
795 _xstatus = 91;
796 return(91);
797}
798
799bool fgcont = true;
800if (TestsStack.top().size() > 0) { // Resultat de if ou else
801 list<char>::iterator it;
802 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
803 // Si on n'est pas ds le else et le if est faux
804 if ( !((*it)&2) && !((*it)&1) ) fgcont = false;
805 // Si on est ds else et le if etait vrai !
806 if ( ((*it)&2) && ((*it)&1) ) fgcont = false;
807 if (!fgcont) break;
808 }
809}
810
811if ((!fgcont) && (kw != "if")) {
812 _xstatus = 0;
813 return(0);
814}
815
816
817// Les mots cles break et return peuvent de sortir de boucles/scripts/execfile
818if (kw == "break") return CMD_BREAK_RC;
819else if (kw == "return") {
820 _retstr = toks;
821 return CMD_RETURN_RC;
822}
823
824// Nous ne sommes donc pas dans un bloc .... Substitution de variables
825string s2;
826int rcs ;
827
828rcs = SubstituteVars(s, s2);
829if (rcs) {
830 cerr << "Commander::Interpret()/syntax error in SubstituteVars() \n"
831 << "line: " << s << endl;
832 _xstatus = 99;
833 return(99);
834}
835// >>>> Separating keyword and tokens
836vector<string> tokens;
837vector<bool> qottoks;
838/* decoupage en mots */
839LineToWords(s2, kw, tokens, qottoks, toks, true);
840
841// Si c'est un for/foreach, on cree un nouveau bloc
842if ((kw == "foreach") || (kw == "for") || (kw == "forinfile") ) {
843 // cout << " *DBG* We got a foreach... " << endl;
844 CommanderBloc* bloc = new CommanderBloc(this, CmdBlks.top(), kw, tokens);
845 if (!bloc->CheckOK()) {
846 cerr << "Commander::Interpret() for/foreach syntax Error ! " << endl;
847 delete bloc;
848 _xstatus = 91;
849 return(91);
850 }
851 felevel++;
852 if (CmdBlks.top()) CmdBlks.top()->AddBloc(bloc);
853 else SetCurrentPrompt("for...> ");
854 CmdBlks.top() = bloc;
855 // cout << " *DBG* New Bloc created ... " << endl;
856 return(0);
857 }
858else if (kw == "if") { // Un test if
859 bool restst = true;
860 int rct = EvaluateTest(tokens, s, restst);
861 if (rct) {
862 cerr << "Commander::Interpret() if syntax Error ! " << "line: " << s << endl;
863 _xstatus = 91;
864 return(91);
865 }
866 char res_tst = (restst) ? 1 : 0;
867 TestsStack.top().push_back(res_tst);
868 if (TestsStack.top().size() == 1) tresit = TestsStack.top().begin();
869 else tresit++;
870 const char * npr = (restst) ? "if-T> " : "if-F> ";
871 SetCurrentPrompt(npr);
872}
873else if ((tokens.size() > 0) && (tokens[0] == "=")) {
874 // x = Expression
875 if (qottoks[1]) { // decodage sous forme de chaine
876 SetVariable(kw, tokens[1]);
877 }
878 else {
879 try {
880 double res = 0.;
881 if (tokens.size() > 2) {
882 string sex = tokens[1];
883 for(int js=2; js<tokens.size(); js++) sex += tokens[js];
884 CExpressionEvaluator cex(sex);
885 res = cex.Value();
886 }
887 else {
888 CExpressionEvaluator cex(tokens[1]);
889 res = cex.Value();
890 }
891 char cbuff[64];
892 sprintf(cbuff,"%g",res);
893 string vv = cbuff;
894 SetVariable(kw, vv);
895 }
896 catch (CExprException& cexerr) {
897 cerr << "Commander::Interpret() evaluation Error : \n " << "line: " << s
898 << " \n Msg=" << cexerr.Msg() << endl;
899 _xstatus = 98;
900 return(98);
901 }
902 }
903}
904else if (kw == "defscript") { // definition de script
905 if (tokens.size() > 0) {
906 if (tokens.size() < 2) tokens.push_back("");
907 curscript = new CommanderScript(this, tokens[0], tokens[1]);
908 SetCurrentPrompt("Script...> ");
909 return(0);
910 }
911 else {
912 cerr << "Commander::Interpret() No script name in defscript" << "line: " << s << endl;
913 _xstatus = 91;
914 return(91);
915 }
916}
917else {
918 // Si c'est le nom d'un script
919 sit = mScripts.find(kw);
920 if (sit != mScripts.end()) {
921 bool ohv = histon;
922 histon = false;
923 tokens.insert(tokens.begin(), kw);
924 PushStack(tokens);
925 (*sit).second->Execute(tokens);
926 PopStack(true);
927 histon = ohv;
928 }
929 // Execution de commandes
930 else rc = ExecuteCommandLine(kw, tokens, toks);
931 _xstatus = rc;
932 return(rc);
933}
934// cout << "Commander::Do() DBG KeyW= " << kw << " NbArgs= " << tokens.size() << endl;
935// for(int ii=0; ii<tokens.size(); ii++)
936// cout << "arg[ " << ii << " ] : " << tokens[ii] << endl;
937
938return(0);
939}
940
941
942/* --Methode-- */
943int Commander::LineToWords(string& line, string& kw, vector<string>& tokens,
944 vector<bool>& qottoks, string& toks, bool uq)
945{
946if (line.length() < 1) return(0);
947int nw = 1;
948size_t p = line.find_first_not_of(" ");
949line = line.substr(p);
950p = 0;
951size_t q = line.find_first_of(" ");
952size_t l = line.length();
953
954if (q < l)
955 { kw = line.substr(p,q-p); toks = line.substr(q, l-q); }
956else { kw = line.substr(p,l-p); toks = ""; }
957
958q = 0;
959while (q < l) {
960 bool swq = false; // true -> chaine delimite par ' ou "
961 p = toks.find_first_not_of(" \t",q+1); // au debut d'un token
962 if (p>=l) break;
963 if ( uq && ((toks[p] == '\'') || (toks[p] == '"')) ) {
964 q = toks.find(toks[p],p+1);
965 if (q>=l) {
966 cerr << "Commander::LineToWords/Syntax Error - Unbalenced quotes " << toks[p] << '.' << endl;
967 return(-1);
968 }
969 p++; swq = true;
970 }
971 else {
972 q = toks.find_first_of(" \t",p); // la fin du token;
973 }
974 string token = toks.substr(p,q-p);
975 tokens.push_back(token);
976 qottoks.push_back(swq);
977 nw++;
978 }
979
980return(nw);
981}
982
983/* --Methode-- */
984int Commander::SubstituteVars(string & s, string & s2)
985// Variable substitution
986{
987
988int iarr = -1; // index d'element de tableau
989size_t p,q,q2,q3,l;
990
991s2="";
992p = 0;
993l = s.length();
994string vn, vv;
995while (p < l) {
996 iarr = -1;
997 q = s.find('$',p);
998 if (q > l) break;
999 q2 = s.find('\'',p);
1000 if ((q2 < l) && (q2 < q)) { // On saute la chaine delimitee par ' '
1001 q2 = s.find('\'',q2+1);
1002 if (q2 >= l) {
1003 cerr << " Syntax error - Unbalenced quotes !!! " << endl;
1004 return(1);
1005 }
1006 s2 += s.substr(p, q2-p+1);
1007 p = q2+1; continue;
1008 }
1009 // cout << "DBG: " << s2 << " p= " << p << " q= " << q << " L= " << l << endl;
1010 if ((q>0) && (s[q-1] == '\\')) { // Escape character \$
1011 s2 += (s.substr(p,q-1-p) + '$') ; p = q+1;
1012 continue;
1013 }
1014 if (q >= l-1) {
1015 cerr << " Syntax error - line ending with $ !!! " << endl;
1016 return(2);
1017 }
1018 vn = "";
1019 if ( s[q+1] == '{' ) { // Variable in the form ${name}
1020 q2 = s.find('}',q+1);
1021 if (q2 >= l) {
1022 cerr << " Syntax error - Unbalenced brace {} !!! " << endl;
1023 return(3);
1024 }
1025 vn = s.substr(q+2,q2-q-2);
1026 q2++;
1027 }
1028 else if ( s[q+1] == '(' ) { // Variable in the form $(name)
1029 q2 = s.find(')',q+1);
1030 if (q2 >= l) {
1031 cerr << " Syntax error - Unbalenced parenthesis () !!! " << endl;
1032 return(3);
1033 }
1034 vn = s.substr(q+2,q2-q-2);
1035 q2++;
1036 }
1037 else if ( s[q+1] == '[' ) { // Variable in the form $[varname] -> This is $$varname
1038 q2 = s.find(']',q+1);
1039 if (q2 >= l) {
1040 cerr << " Syntax error - Unbalenced brace [] !!! " << endl;
1041 return(4);
1042 }
1043 vn = s.substr(q+2,q2-q-2);
1044 if (!Var2Str(vn, vv)) return(5);
1045 vn = vv;
1046 q2++;
1047 }
1048 else {
1049 q2 = s.find_first_of(" .:+-*/,[](){}&|!$\"'",q+1);
1050 if (q2 > l) q2 = l;
1051 q3 = q2;
1052 vn = s.substr(q+1, q2-q-1);
1053 // Si variable de type $varname[index] : element de tableau
1054 if ((q2 < l) && (s[q2] == '[') ) {
1055 q3 = s.find_first_of("]",q2+1);
1056 string sia = s.substr(q2+1, q3-q2-1);
1057 if (sia.length() < 1) {
1058 cerr << " Syntax error - in $varname[index] : $"
1059 << vn << "[" << sia <<"]" << endl;
1060 return(4);
1061 }
1062 if (isalpha(sia[0])) {
1063 string sia2;
1064 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1065 cerr << " Syntax error - in $varname[index] : $"
1066 << vn << "[" << sia <<"]" << endl;
1067 return(4);
1068 }
1069 sia = sia2;
1070 }
1071 int rcdia = ctoi(sia.c_str(), &iarr);
1072 if (rcdia < 0) {
1073 cerr << " Syntax error - in $varname[iarr] : $"
1074 << vn << "[" << sia <<"]" << endl;
1075 return(4);
1076 }
1077 }
1078 }
1079 if (iarr < 0) {
1080 if (!Var2Str(vn, vv)) return(5);
1081 s2 += (s.substr(p, q-p) + vv);
1082 p = q2;
1083 }
1084 else {
1085 if (! Var2Str(vn, iarr, vv) ) {
1086 cerr << " Substitution error - word index out of range in "
1087 << "$varname[iarr] : $" << vn << "[" << iarr <<"]" << endl;
1088 return(4);
1089 }
1090 else s2 += (s.substr(p, q-p) + vv);
1091 p = q3+1;
1092 }
1093}
1094if (p < l) s2 += s.substr(p);
1095
1096p = s2.find_first_not_of(" \t");
1097if (p < l) s2 = s2.substr(p);
1098
1099return(0);
1100}
1101
1102/* --Methode-- */
1103bool Commander::Var2Str(string const & vn, string & vv)
1104{
1105if (vn.length() < 1) {
1106 cerr << " Commander::Var2Str/Error: length(varname=" << vn << ")<1 !" << endl;
1107 vv = ""; return(false);
1108}
1109// Variable de type $# $0 $1 ... (argument de .pic ou de script)
1110int ka = 0;
1111char buff[32];
1112
1113if (vn == "#") {
1114 if (ArgsStack.empty()) {
1115 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1116 << " ($" << vn << ")" << endl;
1117 vv = ""; return(false);
1118 }
1119 char buff[32];
1120 long an = ArgsStack.top().size();
1121 if (an > 0) an--; // Pour se conformer a l'usage de csh : Nb args sans le $0
1122 sprintf(buff,"%ld", an);
1123 vv = buff; return(true);
1124}
1125else if (vn == "*") {
1126 if (ArgsStack.empty()) {
1127 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1128 << " ($" << vn << ")" << endl;
1129 vv = ""; return(false);
1130 }
1131 vv = ArgsStack.top()[0];
1132 for(int ssk=1; ssk<ArgsStack.top().size(); ssk++) vv += ArgsStack.top()[ssk];
1133 return(true);
1134}
1135else if (ctoi(vn.c_str(), &ka) > 0) { // $0 $1 $2 ...
1136 if (ArgsStack.empty()) {
1137 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1138 << " ($" << vn << ")" << endl;
1139 vv = ""; return(false);
1140 }
1141 if ( (ka < 0) || (ka >= ArgsStack.top().size()) ) {
1142 cerr << " Commander::Var2Str/Error: ArgsStack index <0 or >=args.size() ! "
1143 << " ($" << vn << ")" << endl;
1144 vv = ""; return(false);
1145 }
1146 vv = ArgsStack.top()[ka]; return(true);
1147}
1148else if (vn[0] == '#') { // Variable de type $#vname --> size(vname)
1149 CmdVarList::iterator it = variables.find(vn.substr(1));
1150 if (it == variables.end()) {
1151 cerr << " Commander::Var2Str/Error #vname Undefined variable "
1152 << vn << " ! " << endl;
1153 vv = ""; return(false);
1154 }
1155 sprintf(buff,"%d", (int)(*it).second.size());
1156 vv = buff; return(true);
1157}
1158else if (vn == "status") {
1159 sprintf(buff,"%d", _xstatus);
1160 vv = buff;
1161 return true;
1162}
1163else if ((vn == "retstr") || (vn == "retval")) {
1164 vv = _retstr;
1165 return true;
1166}
1167else { // Variable de l'interpreteur, ou de l'environnement application , env. global
1168 if (GetVar(vn, vv)) return true;
1169 else if (GetVarApp(vn, vv)) return true;
1170 else if (GetVarEnv(vn, vv)) return true;
1171 else {
1172 cerr << " Commander::Var2Str/Error Undefined variable "
1173 << vn << " ! " << endl;
1174 vv = ""; return false;
1175 }
1176}
1177
1178return false;
1179}
1180
1181/* --Methode-- */
1182bool Commander::SetVariable(string const & vn, string const & vv)
1183{
1184 // On verifie si le nom est de type vname[idx]
1185 size_t p,q,l;
1186 l = vn.length();
1187 p = vn.find('[');
1188 if (p < l) {
1189 q = vn.find(']');
1190 if (q != (l-1)) {
1191 cout << "Commander::Str2Var/SetVar() - Bad varname with []: "
1192 << vn << endl;
1193 return false;
1194 }
1195 string vna = vn.substr(0, p);
1196 string sia = vn.substr(p+1, q-(p+1));
1197 if (isalpha(sia[0])) {
1198 string sia2;
1199 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1200 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[index]:"
1201 << vn << endl;
1202 return false;
1203 }
1204 sia = sia2;
1205 }
1206 int iarr;
1207 int rcdia = ctoi(sia.c_str(), &iarr);
1208 if (rcdia < 0) {
1209 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[iarr]: "
1210 << vn << endl;
1211 return false;
1212 }
1213 return SetVar(vna, iarr, vv);
1214 }
1215 else {
1216 if (vn == "status") {
1217 _xstatus = atoi(vv.c_str());
1218 return true;
1219 }
1220 else if (vn == "retstr") {
1221 _retstr = vv;
1222 return true;
1223 }
1224 else return SetVar(vn, vv);
1225 }
1226}
1227
1228/* --Methode-- */
1229bool Commander::GetVar(string const & vn, string & vv)
1230{
1231 CmdVarList::iterator it = variables.find(vn);
1232 if (it == variables.end()) {
1233 vv = "";
1234 return false;
1235 }
1236 vv = (*it).second[0];
1237 if ((*it).second.size() > 1) {
1238 for(int k=1; k<(*it).second.size(); k++) {
1239 vv += ' '; vv += (*it).second[k];
1240 }
1241 }
1242 return true;
1243}
1244
1245/* --Methode-- */
1246bool Commander::GetVar(string const & vn, int idx, string & vv)
1247{
1248 vv = "";
1249 CmdVarList::iterator it = variables.find(vn);
1250 if (it == variables.end()) return false;
1251 if ((idx < 0) || (idx > (*it).second.size()-1))
1252 return false;
1253 vv = (*it).second[idx];
1254 return true;
1255}
1256
1257/* --Methode-- */
1258bool Commander::GetVar(string const & vn, vector<string> & vv)
1259{
1260 vv.clear();
1261 // vv.erase(vv.begin(),vv.end());
1262 CmdVarList::iterator it = variables.find(vn);
1263 if (it == variables.end()) return false;
1264 vv = (*it).second;
1265 return true;
1266}
1267
1268/* --Methode-- */
1269bool Commander::SetVar(string const & vn, string const & val)
1270{
1271 if ( !CheckVarName(vn) ) {
1272 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1273 return(false);
1274 }
1275 bool fg = false;
1276 vector<string> nouv;
1277 nouv.push_back(val);
1278 CmdVarList::iterator it = variables.find(vn);
1279 if (it == variables.end()) variables[vn] = nouv;
1280 else {
1281 (*it).second = nouv;
1282 fg = true;
1283 }
1284 return fg;
1285}
1286
1287/* --Methode-- */
1288bool Commander::SetVar(string const & vn, int idx, string const & val)
1289{
1290 if ( !CheckVarName(vn) ) {
1291 cerr << "Commander::SetVar( " << vn << " ,idx, ...) Bad VarName " << endl;
1292 return(false);
1293 }
1294 if ((vn == "status") || (vn == "retstr")) {
1295 cerr << "Commander::SetVar(vn,idx,val) ERROR - special var status/retstr "
1296 << endl;
1297 return(false);
1298 }
1299 if (idx < 0) {
1300 cout << "Commander::SetVar(vn," << idx << ",...) Error idx < 0" << endl;
1301 return(false);
1302 }
1303 bool fg = false;
1304 CmdVarList::iterator it = variables.find(vn);
1305 if (it == variables.end()) {
1306 vector<string> nouv;
1307 for(int j=0; j<idx; j++) nouv.push_back("");
1308 nouv.push_back(val);
1309 variables[vn] = nouv;
1310 }
1311 else {
1312 if (idx >= (*it).second.size())
1313 for(int j=(*it).second.size(); j<=idx; j++) (*it).second.push_back("");
1314 (*it).second[idx] = val;
1315 fg = true;
1316 }
1317 return fg;
1318}
1319
1320/* --Methode-- */
1321bool Commander::SetVar(string const & vn, vector<string> const & val)
1322{
1323 if ( !CheckVarName(vn) ) {
1324 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1325 return(false);
1326 }
1327 if ((vn == "status") || (vn == "retstr")) {
1328 cerr << "Commander::SetVar(vn, vector<string>) ERROR - special var status/retstr "
1329 << endl;
1330 return(false);
1331 }
1332 bool fg = false;
1333 CmdVarList::iterator it = variables.find(vn);
1334 if (it == variables.end()) variables[vn] = val;
1335 else {
1336 (*it).second = val;
1337 fg = true;
1338 }
1339 return fg;
1340}
1341
1342/* --Methode-- */
1343bool Commander::CheckVarName(string const & vn)
1344{
1345 size_t l,k;
1346 l = vn.length();
1347 if (l < 1) return false;
1348 if (!isalpha(vn[0])) return false;
1349 for(k=1; k<l; k++)
1350 if ((!isalnum(vn[k])) && (vn[k] != '_')) return false;
1351 return true;
1352}
1353
1354/* --Methode-- */
1355bool Commander::DeleteVar(string const & vn)
1356{
1357 CmdVarList::iterator it = variables.find(vn);
1358 if (it == variables.end()) {
1359 cerr << "Commander::DeleteVar() Var " << vn << " undefined!" << endl;
1360 return false;
1361 }
1362 variables.erase(it);
1363 return true;
1364}
1365
1366/* --Methode-- */
1367void Commander::ListVar()
1368{
1369 cout << " ---- Commander::ListVar() List of defined variables ---- "
1370 << endl;
1371 CmdVarList::iterator it;
1372 for(it = variables.begin(); it != variables.end(); it++) {
1373 string vn = (*it).first;
1374 int vs = (*it).second.size();
1375 cout << vn << " -> Size= " << vs << endl;
1376 }
1377 cout << "---------------------------------------------------------- "
1378 << endl;
1379}
1380
1381/* --Methode-- */
1382bool Commander::GetVarApp(string const & vn, string & vv)
1383{
1384 vv = "";
1385 // cout << " Commander::GetVarApp() Not available ! " << endl;
1386 return false;
1387}
1388
1389/* --Methode-- */
1390bool Commander::SetVarApp(string const & vn, string const & vv)
1391{
1392 // cout << " Commander::SetVarApp() Not available ! " << endl;
1393 return false;
1394}
1395
1396/* --Methode-- */
1397bool Commander::DeleteVarApp(string const & vn)
1398{
1399 // cout << " Commander::DeleteVarApp() Not available ! " << endl;
1400 return false;
1401}
1402
1403/* --Methode-- */
1404void Commander::ListVarApp()
1405{
1406 // cout << " Commander::ListVarApp() Not available ! " << endl;
1407 return;
1408}
1409
1410
1411/* --Methode-- */
1412bool Commander::GetVarEnv(string const & vn, string & vv)
1413{
1414 char* vev = getenv(vn.c_str());
1415 if (vev) {
1416 vv = vev;
1417 return true;
1418 }
1419 else {
1420 vv = "";
1421 return false;
1422 }
1423}
1424
1425/* --Methode-- */
1426bool Commander::SetVarEnv(string const & vn, string const & vv)
1427{
1428 string pev = vn;
1429 pev += '=';
1430 pev += vv;
1431 if (putenv(pev.c_str()) == 0) return true;
1432 else return false;
1433}
1434
1435/* --Methode-- */
1436bool Commander::DeleteVarEnv(string const & vn)
1437{
1438 // cout << " Commander::DeleteVarEnv() Not available ! " << endl;
1439 return false;
1440}
1441
1442/* --Methode-- */
1443void Commander::ListVarEnv()
1444{
1445 cout << " Commander::ListVarEnv() Not available ! " << endl;
1446 return;
1447}
1448
1449
1450/* --Methode-- */
1451string Commander::GetTmpDir()
1452{
1453 return("/tmp");
1454}
1455
1456/* --Methode-- */
1457void Commander::SetCurrentPrompt(const char* pr)
1458{
1459 curprompt = pr;
1460}
1461
1462/* --Methode-- */
1463void Commander::ShowMessage(const char * msg, int att)
1464{
1465 cout << msg ;
1466}
1467
1468
1469
1470/* --Methode-- */
1471int Commander::EvaluateTest(vector<string> & args, string & line, bool & res)
1472{
1473 res = true;
1474 if ((args.size() != 6) || (args[5] != "then") ||
1475 (args[0] != "(") || (args[4] != ")") ) return(1);
1476 if (args[2] == "==") res = (args[1] == args[3]);
1477 else if (args[2] == "!=") res = (args[1] != args[3]);
1478 else if (args[2] == "<")
1479 res = (atof(args[1].c_str()) < atof(args[3].c_str()));
1480 else if (args[2] == ">")
1481 res = (atof(args[1].c_str()) > atof(args[3].c_str()));
1482 else if (args[2] == "<=")
1483 res = (atof(args[1].c_str()) <= atof(args[3].c_str()));
1484 else if (args[2] == ">=")
1485 res = (atof(args[1].c_str()) >= atof(args[3].c_str()));
1486 else return(2);
1487 return(0);
1488}
1489
1490
1491/* --Methode-- */
1492int Commander::EvalRPNExpr(vector<string> & args, string & line)
1493{
1494 // A virer - Reza 15/03/2004
1495 return(0);
1496}
1497
1498/* --Methode-- */
1499void Commander::PushStack(vector<string>& args)
1500{
1501 // We push the argument list (args) on the stack
1502 ArgsStack.push(args);
1503 // We push also CommanderBloc and testresult on the stack
1504 CmdBlks.push(NULL);
1505 list<char> xtx;
1506 TestsStack.push(xtx);
1507
1508}
1509
1510/* --Methode-- */
1511void Commander::PopStack(bool psta)
1512{
1513 // We remove the argument list (args) from the stack
1514 if (psta) ArgsStack.pop();
1515 // And CommanderBloc and TestResult from the corresponding stacks
1516 CommanderBloc* curb = CmdBlks.top();
1517 while (curb != NULL) {
1518 CommanderBloc* parb = curb->Parent();
1519 delete curb; curb = parb;
1520 }
1521 CmdBlks.pop();
1522 TestsStack.pop();
1523}
1524
1525/* --Methode-- */
1526int Commander::ExecuteCommandLine(string & kw, vector<string> & tokens, string & toks)
1527{
1528int rc = 0;
1529
1530// >>>>>>>>>>> Commande d'interpreteur
1531if (kw == "help") {
1532 if (tokens.size() > 0) cout << GetUsage(tokens[0]) << endl;
1533 else {
1534 string kwh = "Commander";
1535 cout << GetUsage(kwh) << endl;
1536 }
1537 }
1538else if (kw == "sleep") {
1539 if (tokens.size() < 1) {
1540 cout << "Commander::Interpret() Usage: sleep nsec " << endl;
1541 return(1);
1542 }
1543 int nsec = atoi(tokens[0].c_str());
1544 cout << "Commander::Interpret() sleep " << nsec << " seconds" << endl;
1545 sleep(nsec);
1546}
1547
1548else if (kw == "set") {
1549 if (tokens.size() < 2) {
1550 cout << "Commander::Interpret() Usage: set varname value or set vecvar ( w1 w2 ... ) " << endl;
1551 return(1);
1552 }
1553
1554 if (tokens.size() == 2)
1555 SetVariable(tokens[0], tokens[1]);
1556 else {
1557 if ( (tokens[1] != "(") || (tokens[tokens.size()-1] != ")") ) {
1558 cout << "Commander::Interpret() Usage: set vecvar ( w1 w2 ... ) " << endl;
1559 return(1);
1560 }
1561 string vname = tokens[0];
1562 vector<string>::iterator vit;
1563 vit = tokens.begin(); tokens.erase(vit);
1564 vit = tokens.begin(); tokens.erase(vit);
1565 tokens.pop_back();
1566 SetVar(vname, tokens);
1567 }
1568 return 0;
1569}
1570else if (kw == "var2words") {
1571 if (tokens.size() < 2) {
1572 cout << "Commander::Interpret() Usage: var2words varname wordvarname [sep]" << endl;
1573 return(1);
1574 }
1575 char sep = ' ';
1576 if (tokens.size() > 2) sep = tokens[2][0];
1577 string vv;
1578 if (!GetVar(tokens[0], vv)) {
1579 cout << "Commander::Interpret() var2words/Error No variable with name " << tokens[0] << endl;
1580 return 2;
1581 }
1582 vector<string> vs;
1583 FillVStringFrString(vv, vs, sep);
1584 SetVar(tokens[1], vs);
1585}
1586else if (kw == "alias") {
1587 if (tokens.size() < 2) { cout << "Commander::Interpret() Usage: alias aliasname string" << endl; return(0); }
1588 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1589 cerr << "Commander::Interpret()/Error alias name should start with alphabetic" << endl;
1590 return(1);
1591 }
1592 string xx = tokens[1];
1593 for (int kk=2; kk<tokens.size(); kk++) xx += (' ' + tokens[kk]);
1594 mAliases[tokens[0]] = xx;
1595}
1596
1597else if ( (kw == "unset") || (kw == "clearvar") ) {
1598 if (tokens.size() < 1) {
1599 cout << "Commander::Interpret() Usage: unset/clearvar varname" << endl;
1600 return(1);
1601 }
1602 else DeleteVar(tokens[0]);
1603}
1604// Evaluation d'expression en notation polonaise inverse
1605else if (kw == "rpneval") {
1606 try {
1607 RPNExpressionEvaluator rpn(tokens, 1);
1608 double res = rpn.Value();
1609 char cbuff[64];
1610 sprintf(cbuff,"%g",res);
1611 string vv = cbuff;
1612 SetVariable(tokens[0],vv);
1613 return 0;
1614 }
1615 catch (RPNExprException& rpnerr) {
1616 cerr << " rpneval: Syntax error - Msg=" << rpnerr.Msg()
1617 << " \n Line=" << toks << endl;
1618 return 98;
1619 }
1620}
1621else if (kw == "echo") {
1622 for (int ii=0; ii<tokens.size(); ii++)
1623 cout << tokens[ii] << " " ;
1624 cout << endl;
1625 }
1626else if (kw == "echo2file") {
1627 if (tokens.size() < 1) {
1628 cout << "Commander::Interpret() Usage: echo2file filename [string ] " << endl;
1629 return(1);
1630 }
1631 ofstream ofs(tokens[0].c_str(), ios::app);
1632 for (int ii=1; ii<tokens.size(); ii++)
1633 ofs << tokens[ii] << " " ;
1634 ofs << endl;
1635 }
1636else if (kw == "readstdin") {
1637 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: readstdin varname" << endl; return(0); }
1638 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1639 cerr << "Commander::Interpret()/Error Variable name should start with alphabetic" << endl;
1640 return(0);
1641 }
1642 ShowMessage(">>> Reading From StdIn \n", _MAGENTA_);
1643 cout << tokens[0] << " ? " << endl;
1644 SetVar(tokens[0], GetStringFrStdin(this) );
1645 }
1646
1647else if (kw == "listvar") ListVar();
1648else if (kw == "listalias") {
1649 cout << "Commander::Interpret() Alias List , AliasName = Value \n";
1650 CmdStrList::iterator it;
1651 for(it = mAliases.begin(); it != mAliases.end(); it++)
1652 cout << (*it).first << " = " << (*it).second << "\n";
1653 cout << endl;
1654 }
1655else if (kw == "listcommands") {
1656 cout << "---- Commander::Interpret() Command List ----- \n";
1657 CmdExmap::iterator it;
1658 int kc = 0;
1659 for(it = cmdexmap.begin(); it != cmdexmap.end(); it++) {
1660 cout << (*it).first << " ";
1661 kc++;
1662 if (kc >= 5) { cout << "\n"; kc = 0; }
1663 }
1664 cout << endl;
1665 }
1666else if (kw == "listscripts") {
1667 cout << "---- Commander::Interpret() Script List ----- \n";
1668 for(ScriptList::iterator sit = mScripts.begin();
1669 sit != mScripts.end(); sit++)
1670 cout << " Script: " << (*sit).second->Name() << " - "
1671 << (*sit).second->Comment() << endl;
1672}
1673else if (kw == "clearscript") {
1674 if (tokens.size() < 1) {
1675 cout << "Commander::Interpret() Usage: clearscript scriptname" << endl;
1676 return(0);
1677 }
1678 ScriptList::iterator sit = mScripts.find(tokens[0]);
1679 if (sit == mScripts.end()) {
1680 cout << "Commander::Interpret() No script with name" << tokens[0] << endl;
1681 return(0);
1682 }
1683 else {
1684 delete (*sit).second;
1685 mScripts.erase(sit);
1686 cout << "Commander::Interpret() script " << tokens[0] << " cleared" << endl;
1687 return(0);
1688 }
1689}
1690else if (kw == "traceon") { cout << "Commander::Interpret() -> Trace ON mode " << endl; trace = true; }
1691else if (kw == "traceoff") { cout << "Commander::Interpret() -> Trace OFF mode " << endl; trace = false; }
1692else if (kw == "timingon") {
1693 cout << "Commander::Interpret() -> Timing ON mode " << endl;
1694 if (gltimer) delete gltimer; gltimer = new Timer("PIA-CmdInterpreter "); timing = true;
1695 }
1696else if (kw == "timingoff") {
1697 cout << "Commander::Interpret() -> Timing OFF mode " << endl;
1698 if (gltimer) delete gltimer; gltimer = NULL; timing = false;
1699 }
1700else if (kw == "exec") {
1701 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: exec filename" << endl; return(0); }
1702 ExecFile(tokens[0], tokens);
1703 }
1704else if (kw == "autoiniranf") {
1705 Auto_Ini_Ranf(1);
1706 return(0);
1707}
1708else if (kw == "shell") {
1709 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: shell cmdline" << endl; return(0); }
1710 string cmd;
1711 for (int ii=0; ii<tokens.size(); ii++)
1712 cmd += (tokens[ii] + ' ');
1713 system(cmd.c_str());
1714 }
1715else if (kw == "cshell") {
1716 if(tokens.size()<1) {cout<<"Commander::Interpret() Usage: cshell cmdline"<<endl; return(0);}
1717 string cmd="";
1718 for(int ii=0;ii<tokens.size();ii++) cmd+=(tokens[ii]+' ');
1719 CShellExecute(cmd);
1720 }
1721
1722// Execution d'une commande enregistree
1723else rc = ExecuteCommand(kw, tokens, toks);
1724
1725if (timing) gltimer->Split();
1726return(rc);
1727}
1728
1729/* --Methode-- */
1730int Commander::ParseLineExecute(string& line, bool qw)
1731 // Si qw == true, on decoupe entre '' ou "" ou espaces
1732{
1733vector<string> tokens;
1734vector<bool> qottoks;
1735string kw, toks;
1736if (line.length() < 1) return(0);
1737LineToWords(line, kw, tokens, qottoks, toks, qw);
1738return(ExecuteCommand(kw, tokens, toks));
1739}
1740
1741/* --Methode-- */
1742int Commander::ExecuteCommand(string& keyw, vector<string>& args, string& toks)
1743{
1744 int rc = -1;
1745 CmdExmap::iterator it = cmdexmap.find(keyw);
1746 if (it == cmdexmap.end()) cout << "No such command : " << keyw << " ! " << endl;
1747 else {
1748 if ((*it).second.cex) rc = (*it).second.cex->Execute(keyw, args, toks);
1749 else cout << "Dont know how to execute " << keyw << " ? " << endl;
1750 }
1751 return(rc);
1752}
1753
1754/* --Methode-- */
1755int Commander::ExecFile(string& file, vector<string>& args)
1756{
1757char line_buff[512];
1758FILE *fip;
1759int rcc = 0;
1760if ( (fip = fopen(file.c_str(),"r")) == NULL ) {
1761 if (file.find('.') >= file.length()) {
1762 cout << "Commander::Exec(): Error opening file " << file << endl;
1763 file += ".pic";
1764 cout << " Trying file " << file << endl;
1765 fip = fopen(file.c_str(),"r");
1766 }
1767 }
1768
1769if(fip == NULL) {
1770 cerr << "Commander::Exec() Error opening file " << file << endl;
1771 hist << "##! Commander::Exec() Error opening file " << file << endl;
1772 return(0);
1773 }
1774
1775// hist << "### Executing commands from " << file << endl;
1776PushStack(args);
1777if (trace) {
1778 ShowMessage("### Executing commands from ", _MAGENTA_);
1779 ShowMessage(file.c_str(), _MAGENTA_);
1780 ShowMessage("\n", _MAGENTA_);
1781 }
1782
1783bool ohv = histon;
1784histon = false;
1785while (fgets(line_buff,511,fip) != NULL)
1786 {
1787 if (trace) ShowMessage(line_buff, _MAGENTA_);
1788 line_buff[strlen(line_buff)-1] = '\0'; /* LF/CR de la fin */
1789 string line(line_buff);
1790 rcc = Interpret(line);
1791 if ((rcc == CMD_RETURN_RC) || (rcc == CMD_BREAKEXE_RC)) break;
1792 }
1793histon = ohv;
1794
1795// hist << "### End of Exec( " << file << " ) " << endl;
1796if (trace) {
1797 ShowMessage("### End of Exec( ", _MAGENTA_);
1798 ShowMessage(file.c_str(), _MAGENTA_);
1799 ShowMessage(" ) \n", _MAGENTA_);
1800 }
1801
1802PopStack(true);
1803
1804return(0);
1805}
1806
1807/* --Methode-- */
1808int Commander::CShellExecute(string cmd)
1809{
1810 if(cmd.size()<=0) return -1;
1811
1812 string fname = GetTmpDir(); fname += "cshell_exec_pia.csh";
1813
1814 string cmdrm = "rm -f " + fname;
1815 system(cmdrm.c_str());
1816
1817 FILE *fip = fopen(fname.c_str(),"w");
1818 if(fip==NULL) {
1819 cout << "Commander/CShellExecute_Error: fopen("<<fname<<") failed"<<endl;
1820 return -2;
1821 }
1822 fprintf(fip,"#!/bin/csh\n\n");
1823 fprintf(fip,"%s\n",cmd.c_str());
1824 fprintf(fip,"\nexit 0\n");
1825 fclose(fip);
1826
1827 cmd = "csh "; cmd += fname;
1828 system(cmd.c_str());
1829
1830 system(cmdrm.c_str());
1831
1832 return 0;
1833}
1834
1835static string* videstr = NULL;
1836/* --Methode-- */
1837string& Commander::GetUsage(const string& kw)
1838{
1839bool fndok = false;
1840CmdExmap::iterator it = cmdexmap.find(kw);
1841if (it == cmdexmap.end()) {
1842 it = helpexmap.find(kw);
1843 if (it != helpexmap.end()) fndok = true;
1844 }
1845 else fndok = true;
1846if (fndok) return( (*it).second.us );
1847// Keyword pas trouve
1848if (videstr == NULL) videstr = new string("");
1849*videstr = "Nothing known about " + kw + " ?? ";
1850return(*videstr);
1851
1852}
1853
1854
1855/* Les definitions suivantes doivent se trouver ds l'en-tete du fichier LaTeX
1856 \newcommand{\piacommand}[1]{
1857 \framebox{\bf \Large #1 } \index{#1} % (Command)
1858 }
1859
1860 \newcommand{\piahelpitem}[1]{
1861 \framebox{\bf \Large #1 } \index{#1} (Help item)
1862 }
1863
1864 \newcommand{\myppageref}[1]{ (p. \pageref{#1} ) }
1865*/
1866
1867// Fonction qui remplace tout caractere non alphanumerique en Z
1868static void check_latex_reflabel(string & prl)
1869{
1870 for(int k=0; k<prl.length(); k++)
1871 if (! isalnum(prl[k]) ) prl[k] = 'Z';
1872}
1873
1874// Fonction qui remplace _ en \_
1875static string check_latex_underscore(string const & mot)
1876{
1877 string rs;
1878 for(int k=0; k<mot.length(); k++) {
1879 if (mot[k] == '_') rs += "\\_";
1880 else rs += mot[k];
1881 }
1882 return rs;
1883}
1884
1885/* --Methode-- */
1886void Commander::HelptoLaTeX(string const & fname)
1887{
1888FILE *fip;
1889if ((fip = fopen(fname.c_str(), "w")) == NULL) {
1890 cout << "Commander::HelptoLaTex_Error: fopen( " << fname << endl;
1891 return;
1892 }
1893
1894fputs("% ----- Liste des groupes de Help ----- \n",fip);
1895fputs("List of {\\bf piapp} on-line Help groups: \n", fip);
1896fputs("\\begin{itemize} \n",fip);
1897string prl;
1898string mol;
1899CmdHGroup::iterator it;
1900for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
1901 if ((*it).first == "All") continue;
1902 prl = (*it).first; check_latex_reflabel(prl);
1903 mol = check_latex_underscore((*it).first);
1904 fprintf(fip,"\\item {\\bf %s } (p. \\pageref{%s}) \n",
1905 mol.c_str(), prl.c_str());
1906}
1907
1908fputs("\\end{itemize} \n",fip);
1909
1910fputs("\\vspace*{10mm} \n",fip);
1911
1912CmdExmap::iterator ite;
1913fputs("% ----- Liste de toutes les commandes et help item ----- \n",fip);
1914fputs("\\vspace{5mm} \n",fip);
1915// fputs("\\begin{table}[h!] \n", fip);
1916fputs("\\begin{center} \n ", fip);
1917fputs("\\rule{2cm}{1mm} List of {\\bf piapp} Help items \\rule{2cm}{1mm} \\\\ \n", fip);
1918fputs("\\vspace{3mm} \n",fip);
1919fputs("\\begin{tabular}{llllll} \n", fip);
1920int kt = 0;
1921for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
1922 prl = (*ite).first; check_latex_reflabel(prl);
1923 mol = check_latex_underscore((*ite).first);
1924 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
1925 kt++;
1926 if (kt < 3) fputs(" & ", fip);
1927 else { fputs(" \\\\ \n", fip); kt = 0; }
1928 }
1929if (kt == 1) fputs(" & & & \\\\ \n", fip);
1930else if (kt == 2) fputs(" & \\\\ \n", fip);
1931fputs("\\end{tabular} \n", fip);
1932fputs("\\end{center} \n", fip);
1933//fputs("\\end{table} \n", fip);
1934fputs("\\newpage \n",fip);
1935
1936int gid;
1937for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
1938 gid = (*it).second.gid;
1939 if (gid == 0) continue;
1940 // fputs("\\begin{table}[h!] \n",fip);
1941 fputs("\\vspace{6mm} \n",fip);
1942 fputs("\\begin{center} \n ", fip);
1943 fprintf(fip, "\\rule{2cm}{0.5mm} \\makebox[60mm]{{ \\bf %s } help group} \\rule{2cm}{0.5mm} \\\\ \n",
1944 (*it).first.c_str());
1945 fputs("\\vspace{3mm} \n",fip);
1946 fputs("\\begin{tabular}{llllll} \n", fip);
1947 kt = 0;
1948 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
1949 if ((*ite).second.group != gid) continue;
1950 prl = (*ite).first; check_latex_reflabel(prl);
1951 mol = check_latex_underscore((*ite).first);
1952 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
1953 kt++;
1954 if (kt < 3) fputs(" & ", fip);
1955 else { fputs(" \\\\ \n", fip); kt = 0; }
1956 }
1957 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
1958 if ((*ite).second.group != gid) continue;
1959 prl = (*ite).first; check_latex_reflabel(prl);
1960 mol = check_latex_underscore((*ite).first);
1961 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
1962 kt++;
1963 if (kt < 3) fputs(" & ", fip);
1964 else { fputs(" \\\\ \n", fip); kt = 0; }
1965 }
1966 if (kt == 1) fputs(" & & & \\\\ \n", fip);
1967 else if (kt == 2) fputs(" & \\\\ \n", fip);
1968 fputs("\\end{tabular} \n", fip);
1969 fputs("\\end{center} \n", fip);
1970 // fputs("\\end{table} \n",fip);
1971 // fputs("\\vspace{5mm} \n",fip);
1972}
1973// fputs("\\newline \n",fip);
1974
1975fputs("% ----- Liste des commandes dans chaque groupe ----- \n",fip);
1976fputs("\\newpage \n",fip);
1977
1978for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
1979 gid = (*it).second.gid;
1980 if (gid == 0) continue;
1981 prl = (*it).first; check_latex_reflabel(prl);
1982 fprintf(fip,"\\subsection{%s} \\label{%s} \n",
1983 (*it).first.c_str(), prl.c_str());
1984 if ((*it).second.desc.length() > 0)
1985 fprintf(fip,"%s \n \\\\[2mm] ", (*it).second.desc.c_str());
1986 fprintf(fip,"\\noindent \n");
1987 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
1988 if ((*ite).second.group != gid) continue;
1989 prl = (*ite).first; check_latex_reflabel(prl);
1990 mol = check_latex_underscore((*ite).first);
1991 fprintf(fip,"\\piahelpitem{%s} \\label{%s} \n",
1992 mol.c_str(), prl.c_str());
1993 fputs("\\begin{verbatim} \n",fip);
1994 fprintf(fip,"%s\n", (*ite).second.us.c_str());
1995 fputs("\\end{verbatim} \n",fip);
1996 }
1997 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
1998 if ((*ite).second.group != gid) continue;
1999 prl = (*ite).first; check_latex_reflabel(prl);
2000 mol = check_latex_underscore((*ite).first);
2001 fprintf(fip,"\\piacommand{%s} \\label{%s} \n",
2002 mol.c_str(), prl.c_str());
2003 fputs("\\begin{verbatim} \n",fip);
2004 fprintf(fip,"%s\n", (*ite).second.us.c_str());
2005 fputs("\\end{verbatim} \n",fip);
2006 }
2007}
2008
2009fclose(fip);
2010cout << " Commander::HelptoLaTeX() - LaTeX format help written to file " << fname << endl;
2011
2012return;
2013}
2014
2015
2016} // End of namespace SOPHYA
2017
Note: See TracBrowser for help on using the repository browser.