Posted to tcl by suchenwi at Sun Nov 10 02:12:53 GMT 2013view raw

  1. /* =================================================== -*- C++ -*-
  2. * tcl.js "A Tcl implementation in Javascript"
  3. *
  4. * Released under the same terms as Tcl itself.
  5. * (BSD license found at <http://www.tcl.tk/software/tcltk/license.html>)
  6. *
  7. * Based on Picol by Salvatore Sanfilippo (<http://antirez.com/page/picol>)
  8. * (c) Stéphane Arnold 2007
  9. * Richard Suchenwirth 2007, 2013: cleanup, additions
  10. * vim: syntax=javascript autoindent softtabwidth=4
  11. */
  12. _step = 0; // set to 1 for debugging
  13. var fs = require('fs');
  14. puts = console.log;
  15.  
  16. function TclInterp () {
  17. this.patchlevel = 0.4;
  18. this.callframe = new Array(new Object());
  19. this.level = 0;
  20. this.commands = new Object();
  21. this.procs = new Array();
  22. this.script = "";
  23. this.OK = 0;
  24. this.RET = 1;
  25. this.BRK = 2;
  26. this.CNT = 3;
  27. this.getVar = function(name) {
  28. var nm = name.toString();
  29. if (nm.match("^::env[(]")) nm=nm.substr(2);
  30. if (nm.match("^env[(]")) {
  31. var key = nm.substr(4,nm.length-5);
  32. var val = process.env[key];
  33. } else if (nm.match("^::")) {
  34. var val = this.callframe[0][nm.substr(2)]; // global
  35. } else {
  36. var val = this.callframe[this.level][name];
  37. }
  38. if (val == null) throw 'can\'t read "'+name+'": no such variable';
  39. return val;
  40. }
  41. this.setVar = function(name, val) {
  42. var nm = name.toString();
  43. if (nm.match("^::")) {
  44. this.callframe[0][nm.substr(2)] = val;
  45. } else {this.callframe[this.level][name] = val;}
  46. return val;
  47. }
  48. this.setVar("argc", process.argv.length-2);
  49. this.setVar("argv0", process.argv[1]);
  50. this.setVar("argv", process.argv.slice(2));
  51. this.setVar("errorInfo", "");
  52.  
  53. this.incrLevel = function() {
  54. this.callframe[++this.level] = new Object();
  55. return this.level;
  56. }
  57. this.decrLevel = function() {
  58. this.callframe[this.level] = null;
  59. this.level--;
  60. if (this.level<0) throw "Exit application";
  61. this.result = null;
  62. }
  63. this.getCommand = function(name) {
  64. try {
  65. return this.commands[name];
  66. } catch (e) {throw "No such command '"+name+"'";}
  67. }
  68. this.registerCommand = function(name, func, privdata) {
  69. if (func == null) throw "No such function: "+name;
  70. this.commands[name] = new TclCommand(func, privdata);
  71. }
  72. this.renameCommand = function (name, newname) {
  73. this.commands[newname] = this.commands[name];
  74. if (this.procs[name]) {
  75. this.procs[name] = null;
  76. this.procs[newname] = true;
  77. }
  78. this.commands[name] = null;
  79. }
  80. this.registerSubCommand = function(name, subcmd, func, privdata) {
  81. if (func == null) throw "No such subcommand: "+ name +" " + subcmd;
  82. var path = name.split(" ");
  83. var ens;
  84. name = path.shift();
  85. var cmd = this.commands[name];
  86. if (cmd == null) {
  87. ens = new Object();
  88. ens["subcommands"] = new TclCommand(Tcl.InfoSubcommands, null);
  89. this.commands[name] = new TclCommand(Tcl.EnsembleCommand, null, ens);
  90. }
  91. ens = this.commands[name].ensemble;
  92. if (ens == null) throw "Not an ensemble command: '"+name+"'";
  93. // walks deeply into the subcommands tree
  94. while (path.length > 0) {
  95. name = path.shift();
  96. cmd = ens[name];
  97. if (cmd == null) {
  98. cmd = new TclCommand(Tcl.EnsembleCommand, null, new Object());
  99. ens[name] = cmd;
  100. ens = cmd.ensemble;
  101. ens["subcommands"] = new TclCommand(Tcl.InfoSubcommands, null);
  102. }
  103. }
  104. ens[subcmd] = new TclCommand(func, privdata);
  105. }
  106. this.eval = function (code) {
  107. try {
  108. return this.eval2(code);
  109. } catch (e) {
  110. var msg = code.substr(0,128);
  111. if(msg.length >= 125) msg += "...";
  112. puts(e);
  113. this.setVar("::errorInfo",e+'\n while executing\n"'+msg+'"');
  114. }
  115. }
  116. this.eval2 = function(code) {
  117. this.code = this.OK;
  118. var parser = new TclParser(code);
  119. var args = new Array(0);
  120. var first = true;
  121. var text, prevtype, result;
  122. result = "";
  123. while (true) {
  124. prevtype = parser.type;
  125. try {
  126. parser.getToken();
  127. } catch (e) {break;}
  128. if (parser.type == (parser.EOF)) break;
  129. text = parser.getText();
  130. if (parser.type == (parser.VAR)) {
  131. try {
  132. text = this.getVar(text);
  133. } catch (e) {throw "No such variable '" + text + "'";}
  134. } else if (parser.type == (parser.CMD)) {
  135. try {
  136. text = this.eval2(text);
  137. } catch (e) {throw (e + "\nwhile parsing \"" + text + "\"");}
  138. } else if (parser.type == (parser.ESC)) {
  139. // escape handling missing!
  140. } else if (parser.type == (parser.SEP)) {
  141. prevtype = parser.type;
  142. continue;
  143. }
  144. text = this.objectify(text);
  145. if (parser.type ==parser.EOL || parser.type == parser.EOF) {
  146. prevtype = parser.type;
  147. if (args.length > 0) {
  148. try {
  149. result = this.call(args);
  150. } catch(e) {
  151. if(e.toString().match("Cannot call method"))
  152. throw 'invalid command name "'+args[0].toString()+'"';
  153. throw e;
  154. }
  155. if (this.code != this.OK) return this.objectify(result);
  156. }
  157. args = new Array();
  158. continue;
  159. }
  160. if (prevtype == parser.SEP || prevtype == parser.EOL) {
  161. args.push(text);
  162. } else {
  163. args[args.length-1] = args[args.length-1].toString() + text.toString();
  164. }
  165. }
  166. if (args.length > 0) result = this.call(args);
  167. return this.objectify(result);
  168. }
  169. //---------------------------------- Commands in alphabetical order
  170. this.registerCommand("append", function (interp, args) {
  171. this.requireMinArgc(args, 2);
  172. var vname = args[1].toString();
  173. if (interp.callframe[interp.level][vname] != null) {
  174. var str = interp.getVar(vname);
  175. } else var str = "";
  176. for (var i = 2; i < args.length; i++) str += args[i].toString();
  177. interp.setVar(vname, str);
  178. return str;
  179. });
  180. this.registerCommand("break", function (interp, args) {
  181. interp.code = interp.BRK;
  182. return;
  183. });
  184. this.registerCommand("cd", function (interp, args) {
  185. this.requireArgcRange(args, 1, 2);
  186. var dir = process.env.HOME;
  187. if (args.length == 2) dir = args[1].toString();
  188. process.chdir(dir);
  189. return;
  190. });
  191. this.registerCommand("continue", function (interp, args) {
  192. interp.code = interp.CNT;
  193. return;
  194. });
  195. this.registerSubCommand("clock", "format", function (interp, args) {
  196. var now = new Date();
  197. now.setTime(args[1]);
  198. return now.toString();
  199. });
  200. this.registerSubCommand("clock", "milliseconds", function (interp, args) {
  201. var t = new Date();
  202. return t.valueOf();
  203. });
  204. this.registerSubCommand("clock", "scan", function (interp, args) {
  205. return Date.parse(args[1]);
  206. });
  207. this.registerSubCommand("clock", "seconds", function (interp, args) {
  208. return Math.floor((new Date()).valueOf()/1000);
  209. });
  210.  
  211. this.registerSubCommand("dict", "create", function (interp, args) {
  212. if(args.length % 2 == 0)
  213. throw 'wrong # args: should be "dict create ?key value ...?';
  214. return new TclObject(args.slice(1));
  215. });
  216. this.registerSubCommand("dict", "get", function (interp, args) {
  217. if(args.length < 2)
  218. throw 'wrong # args: should be "dict get ?key ...?';
  219. var dict = args[1].toList();
  220. var key = args[2].toString();
  221. for (var i=0;i < dict.length;i+=2) {
  222. if(dict[i].toString() == key) return dict[i+1];
  223. }
  224. throw 'key "'+key+'" not known in dictionary';
  225. });
  226. this.registerSubCommand("dict", "set", function (interp, args) {
  227. this.requireExactArgc(args, 4);
  228. var name = args[1];
  229. var dict = interp.getVar(name);
  230. var key = args[2].toString();
  231. var val = args[3].toString();
  232. var found = false;
  233. puts("dict: "+dict+" dict.length: "+dict.length);
  234. dict.toList();
  235. for (var i=0;i < dict.length;i+=2) {
  236. puts("trying "+key+" at "+i+": "+dict[i].toString());
  237. if(dict[i].toString() == key) {
  238. dict[i+1] = val;
  239. found = true;
  240. break;
  241. }
  242. }
  243. if (!found) {
  244. dict.content.push(interp.objectify(key));
  245. dict.content.push(interp.objectify(val));
  246. }
  247. interp.setVar(name, dict);
  248. return dict;
  249. });
  250. /*
  251. if(typeof(jQuery) != 'undefined') {
  252. this.registerCommand("dom", function (interp, args) {
  253. var selector = args[1].toString();
  254. var fn = args[2].toString();
  255. args = args.slice(3);
  256. for (var i in args) args[i] = args[i].toString();
  257. var q = $(selector);
  258. q[fn].apply(q,args);
  259. return "dom " + selector;
  260. });
  261. }*/
  262. this.registerCommand("eval",function (interp, args) {
  263. this.requireMinArgc(args, 2);
  264. for (var i = 1; i < args.length; i++) args[i] = args[i].toString();
  265. if (args.length == 2) var code = args[1];
  266. else var code = args.slice(1).join(" ");
  267. return interp.eval(code);
  268. });
  269. /*
  270. this.registerCommand("exec",function (interp, args) {
  271. this.requireMinArgc(args, 2);
  272. var exec = require('child_process').exec,
  273. child;
  274. puts("exec "+args.slice(1).join(" "));
  275. child = exec(args.slice(1).join(" "),
  276. function (error, stdout, stderr) {
  277. var res = stdout.toString();
  278. //console.log('stdout: ' + stdout.toString());
  279. if (error !== null) {
  280. throw('exec error: ' + error);
  281. }
  282. return res;
  283. });
  284. return this.execres;
  285. });
  286. */
  287. this.registerCommand("exit",function (interp, args) {
  288. this.requireMinArgc(args, 1);
  289. var rc = 0;
  290. if (args.length == 2) rc = args[1];
  291. process.exit(rc);
  292. });
  293. acos = Math.acos;
  294. exp = Math.exp;
  295. sqrt = Math.sqrt; // "publish" other Math.* functions as needed
  296.  
  297. this.registerCommand("expr", function (interp, args) {
  298. var expression = args.slice(1).join(" ");
  299. return interp.expr(interp, expression);
  300. });
  301. this.expr = function ($interp, $expression) {
  302. var $mx = $expression.match(/(\$[A-Za-z0-9_:]+)/g);
  303. for ($i in $mx)
  304. eval("var "+$mx[$i]+" = "+$interp.getVar($mx[$i].slice(1)));
  305. var res = eval($expression);
  306. if(res == false) res = 0; else if(res == true) res = 1;
  307. return res;
  308. };
  309. this.registerCommand("for", function (interp, args) {
  310. this.requireExactArgc(args, 5);
  311. interp.eval(args[1].toString());
  312. if(interp.code != interp.OK) return;
  313. var cond = args[2].toString();
  314. var step = args[3].toString();
  315. var body = args[4].toString();
  316. interp.inLoop = true;
  317. interp.code = interp.OK;
  318. while (true) {
  319. test = interp.objectify(interp.expr(interp, cond));
  320. if (!test.toBoolean()) break;
  321. interp.eval(body);
  322. var ic = interp.code; // tested after step command
  323. interp.eval(step);
  324. if(ic == interp.BRK) break;
  325. if(ic == interp.CNT) continue;
  326. }
  327. interp.inLoop = false;
  328. if(interp.code == interp.BRK || interp.code == interp.CNT)
  329. interp.code = interp.OK;
  330. return "";
  331. });
  332. this.registerCommand("foreach", function (interp, args) {
  333. this.requireExactArgc(args, 4);
  334. var list = args[2].toList();
  335. var body = args[3].toString();
  336. var res = "";
  337. interp.inLoop = true;
  338. interp.code = interp.OK;
  339. for(i in list) {
  340. interp.setVar(args[1],interp.objectify(list[i]));
  341. interp.eval(body);
  342. if(interp.code == interp.BRK) break;
  343. if(interp.code == interp.CNT) continue;
  344. }
  345. interp.inLoop = false;
  346. if(interp.code == interp.BRK || interp.code == interp.CNT)
  347. interp.code=interp.OK;
  348. return "";
  349. });
  350. /* this.registerCommand("gets", function (interp, args) {
  351. this.requireArgcRange(args, 2, 3);
  352. var reply; // = prompt(args[1],"");
  353. process.stdin.resume();
  354. process.stdin.on('data', function(str) {
  355. reply = str;
  356. });
  357. if(args[2] != null) {
  358. interp.setVar(args[2],interp.objectify(reply));
  359. return reply.length;
  360. } else return reply;
  361. }); */
  362. this.registerCommand("if", function (interp, args) {
  363. this.requireMinArgc(args, 3);
  364. var cond = args[1].toString();
  365. var test = interp.objectify(interp.expr(interp, cond));
  366. if (test.toBoolean()) return interp.eval(args[2].toString());
  367. if (args.length == 3) return;
  368. for (var i = 3; i < args.length; ) {
  369. switch (args[i].toString()) {
  370. case "else":
  371. this.requireExactArgc(args, i + 2);
  372. return interp.eval(args[i+1].toString());
  373. case "elseif":
  374. this.requireMinArgc(args, i + 3);
  375. test = interp.objectify(interp.expr(interp, args[i+1].toString()));
  376. if (test.toBoolean())
  377. return interp.eval(args[i+2].toString());
  378. i += 3;
  379. break;
  380. default:
  381. throw "Expected 'else' or 'elseif', got "+ args[i];
  382. }
  383. }
  384. });
  385. this.registerCommand("incr", function (interp, args) {
  386. this.requireArgcRange(args, 2, 3);
  387. var name = args[1];
  388. if (args.length == 2) var incr = 1;
  389. else var incr = interp.objectify(args[2]).toInteger();
  390. incr += interp.getVar(name).toInteger();
  391. return interp.setVar(name, new TclObject(incr, "INTEGER"));
  392. });
  393. this.registerSubCommand("info", "args", function (interp, args) {
  394. this.requireExactArgc(args, 2);
  395. var name = args[1].toString();
  396. if (!interp.procs[name]) throw '"'+name+'" isn\'t a procedure';
  397. return interp.getCommand(name).privdata[0];
  398. });
  399. this.registerSubCommand("info", "body", function (interp, args) {
  400. this.requireExactArgc(args, 2);
  401. var name = args[1].toString();
  402. if (!interp.procs[name]) throw '"'+name+'" isn\'t a procedure';
  403. return interp.getCommand(name).privdata[1];
  404. });
  405. this.registerSubCommand("info", "commands", function (interp, args) {
  406. return interp.mkList(interp.commands);
  407. });
  408. this.registerSubCommand("info", "globals", function (interp, args) {
  409. return interp.mkList(interp.callframe[0]);
  410. });
  411. this.registerSubCommand("info", "isensemble", function (interp, args) {
  412. this.requireExactArgc(args, 2);
  413. var name = args[1].toString();
  414. return (interp.getCommand(name).ensemble != null);
  415. });
  416. this.registerSubCommand("info", "patchlevel", function (interp, args) {
  417. return interp.patchlevel.toString();
  418. });
  419. this.registerSubCommand("info", "na", function (interp, args) {
  420. return process.execPath;
  421. });
  422. this.registerSubCommand("info", "procs", function (interp, args) {
  423. return interp.mkList(interp.procs);
  424. });
  425. this.registerSubCommand("info", "exists", function (interp, args) {
  426. var name = args[1];
  427. try {interp.getVar(name); return 1;} catch(e) {return 0;}
  428. });
  429. this.registerSubCommand("info", "script", function (interp, args) {
  430. return interp.script;
  431. });
  432. this.registerSubCommand("info", "vars", function (interp, args) {
  433. return interp.mkList(interp.callframe[interp.level]);
  434. });
  435. this.registerCommand("join", function (interp, args) {
  436. this.requireArgcRange(args, 2, 3);
  437. var lst = args[1].toList();
  438. var sep = " ";
  439. if(args.length == 3) sep = args[2].toString();
  440. return lst.join(sep);
  441. });
  442. this.registerCommand("jseval", function (interp, args) {
  443. return eval(args[1].toString());
  444. });
  445. this.registerCommand("lappend", function (interp, args) {
  446. this.requireMinArgc(args, 2);
  447. var vname = args[1].toString();
  448. if (interp.callframe[interp.level][vname] != null) {
  449. var list = interp.getVar(vname);
  450. } else var list = new TclObject([]);
  451. list.toList();
  452. for (var i = 2; i < args.length; i++) {
  453. list.content.push(interp.objectify(args[i]));
  454. }
  455. interp.setVar(vname, list);
  456. return list;
  457. });
  458. this.registerCommand("lindex", function (interp, args) {
  459. this.requireMinArgc(args, 3);
  460. var list = interp.objectify(args[1]);
  461. for (var i = 2; i < args.length; i++) {
  462. try {
  463. var index = list.listIndex(args[i]);
  464. } catch (e) {
  465. if (e == "Index out of bounds") return "";
  466. throw e;
  467. }
  468. list = list.content[index];
  469. }
  470. return interp.objectify(list);
  471. });
  472. this.registerCommand("list", function (interp, args) {
  473. args.shift();
  474. return new TclObject(args);
  475. });
  476. this.registerCommand("llength", function (interp, args) {
  477. this.requireExactArgc(args, 2);
  478. return args[1].toList().length;
  479. });
  480. this.registerCommand("lrange", function (interp, args) {
  481. this.requireExactArgc(args, 4);
  482. var list = interp.objectify(args[1]);
  483. var start = list.listIndex(args[2]);
  484. var end = list.listIndex(args[3])+1;
  485. try {
  486. return list.content.slice(start, end);
  487. } catch (e) {return new Array();}
  488. });
  489. this.registerCommand("lset", function (interp, args) {
  490. this.requireMinArgc(args, 4);
  491. var list = interp.getVar(args[1].toString());
  492. var elt = list;
  493. for (var i = 2; i < args.length-2; i++) {
  494. elt.toList();
  495. elt = interp.objectify(elt.content[elt.listIndex(args[i])]);
  496. }
  497. elt.toList();
  498. i = args.length - 2;
  499. elt.content[elt.listIndex(args[i])] = interp.objectify(args[i+1]);
  500. return list;
  501. });
  502. this.registerCommand("lsearch", function (interp, args) {
  503. this.requireExactArgc(args, 3);
  504. var lst = args[1].toList();
  505. for(i in lst) if(lst[i] == args[2].toString()) return i;
  506. return -1;
  507. });
  508. this.registerCommand("lsort", function (interp, args) {
  509. this.requireExactArgc(args, 2);
  510. return args[1].toList().sort();
  511. });
  512. this.registerCommand("pid", function (interp, args) {
  513. return process.pid;
  514. });
  515. this.registerCommand("puts", function (interp, args) {
  516. this.requireExactArgc(args, 2);
  517. puts(args[1].toString());
  518. });
  519. this.registerCommand("pwd", function (interp, args) {
  520. return process.cwd();
  521. });
  522. this.registerCommand("proc", function (interp, args) {
  523. this.requireExactArgc(args, 4);
  524. var name = args[1].toString();
  525. var argl = interp.parseList(args[2]);
  526. var body = args[3].toString();
  527. var priv = new Array(argl,body);
  528. interp.commands[name] = new TclCommand(Tcl.Proc, priv);
  529. interp.procs[name] = true;
  530. });
  531. this.registerCommand("regexp", function (interp, args) {
  532. this.requireExactArgc(args, 3);
  533. var re = new RegExp(args[1].toString());
  534. var str = args[2].toString();
  535. return (str.search(re) > -1? "1":"0");
  536. });
  537. this.registerCommand("regsub", function (interp, args) {
  538. this.requireExactArgc(args, 4);
  539. var re = new RegExp(args[1].toString());
  540. var str = args[2].toString();
  541. var trg = args[3].toString();
  542. return (str.replace(re,trg));
  543. });
  544. this.registerCommand("rename", function (interp, args) {
  545. this.requireExactArgc(args, 3);
  546. interp.renameCommand(args[1], args[2]);
  547. });
  548. this.registerCommand("return", function (interp, args) {
  549. this.requireArgcRange(args, 1, 2);
  550. var r = args[1];
  551. interp.code = interp.RET;
  552. return r;
  553. });
  554. this.registerCommand("set", function (interp, args) {
  555. this.requireArgcRange(args, 2, 3);
  556. var name = args[1];
  557. if (args.length == 3) interp.setVar(name, args[2]);
  558. return interp.getVar(name);
  559. });
  560. this.registerCommand("source", function (interp, args) {
  561. this.requireExactArgc(args, 2);
  562. interp.script = args[1].toString();
  563. try {
  564. var data = fs.readFileSync(interp.script).toString();
  565. } catch(e) {throw 'couldn\' read file "'+interp.script+
  566. '": no such file or directory';}
  567. var res = interp.eval(data);
  568. interp.script = "";
  569. return res;
  570. });
  571. this.registerCommand("split", function (interp, args) {
  572. this.requireArgcRange(args, 2, 3);
  573. var str = args[1].toString();
  574. var sep = " ";
  575. if (args.length == 3) sep = args[2].toString();
  576. return str.split(sep);
  577. });
  578. this.registerSubCommand("string", "equal", function (interp, args) {
  579. this.requireExactArgc(args, 3);
  580. return (args[1].toString() == args[2].toString())? "1": "0";
  581. });
  582. this.registerSubCommand("string", "index", function (interp, args) {
  583. this.requireExactArgc(args, 3);
  584. var s = args[1].toString();
  585. try {
  586. return s.charAt(args[1].stringIndex(args[2]));
  587. } catch (e) {return "";}
  588. });
  589. this.registerSubCommand("string", "length", function (interp, args) {
  590. this.requireExactArgc(args, 2);
  591. return args[1].toString().length;
  592. });
  593. this.registerSubCommand("string", "range", function (interp, args) {
  594. this.requireExactArgc(args, 4);
  595. var s = args[1];
  596. try {
  597. var b = s.stringIndex(args[2]);
  598. var e = s.stringIndex(args[3]);
  599. if (b > e) return "";
  600. return s.toString().substring(b, e + 1);
  601. } catch (e) {return "";}
  602. });
  603. this.registerSubCommand("string", "tolower", function (interp, args) {
  604. this.requireExactArgc(args, 2);
  605. return args[1].toString().toLowerCase();
  606. });
  607. this.registerSubCommand("string", "toupper", function (interp, args) {
  608. this.requireExactArgc(args, 2);
  609. return args[1].toString().toUpperCase();
  610. });
  611. this.registerSubCommand("string", "trim", function (interp, args) {
  612. this.requireExactArgc(args, 2);
  613. return args[1].toString().trim();
  614. });
  615. function sec_msec () {
  616. var t = new Date();
  617. return t.getSeconds()*1000 + t.getMilliseconds();
  618. }
  619. this.registerCommand("time", function (interp, args) {
  620. this.requireArgcRange(args, 2, 3);
  621. var body = args[1].toString();
  622. var n = (args.length == 3)? args[2] : 1;
  623. var t0 = sec_msec();
  624. for(var i = 0; i < n; i++) interp.eval(body);
  625. return (sec_msec()-t0)*1000/n + " microseconds per iteration";
  626. });
  627. this.registerCommand("unset", function (interp, args) {
  628. this.requireMinArgc(args, 2);
  629. for (var i = 2; i < args.length; i++)
  630. interp.setVar(args[i], null);
  631. });
  632. this.registerCommand("uplevel",function (interp, args) {
  633. this.requireMinArgc(args, 3);
  634. var delta = args[1].toInteger();
  635. interp.level -= delta;
  636. for (var i = 2; i < args.length; i++) args[i] = args[i].toString();
  637. if (args.length == 3) var code = args[2];
  638. else var code = args.slice(2).join(" ");
  639. var res = interp.eval(code);
  640. interp.level += delta;
  641. return res;
  642. });
  643. this.registerCommand("while", function (interp, args) {
  644. this.requireExactArgc(args, 3);
  645. var cond = args[1].toString();
  646. var body = args[2].toString();
  647. var res = "";
  648. interp.inLoop = true;
  649. interp.code = interp.OK;
  650. while (true) {
  651. test = interp.objectify(interp.eval(cond));
  652. if (!test.toBoolean()) break;
  653. res = interp.eval(body);
  654. if(interp.code == interp.CNT) continue;
  655. if(interp.code != interp.OK) break;
  656. }
  657. interp.inLoop = false;
  658. if(interp.code == interp.BRK || interp.code == interp.CNT)
  659. interp.code=interp.OK;
  660. return interp.objectify(res);
  661. });
  662. // native cmdname {function(interp, args) {...}}
  663. this.registerCommand("native", function (interp, args) {
  664. this.requireExactArgc(args, 3);
  665. var cmd = args[1].toList();
  666. var func = eval(args[2].toString());
  667. //alert("in: "+args[2].toString()+", func: "+ func);
  668. if (cmd.length == 1) {
  669. interp.registerCommand(cmd[0].toString(), func);
  670. return;
  671. }
  672. base = cmd[0].toString();
  673. cmd.shift();
  674. interp.registerSubCommand(base, cmd.join(" "), eval(args[2].toString()));
  675. return;
  676. });
  677. this.math = function (name, a, b) {
  678. switch (name) {
  679. case "+": return a + b;
  680. case "-": return a - b;
  681. case "*": return a * b;
  682. case "/": return a / b;
  683. case "%": return a % b;
  684. case "<": return a < b? "1":"0";
  685. case ">": return a > b? "1":"0";
  686. case "==": return a == b? "1":"0";
  687. case "!=": return a != b? "1":"0";
  688. default: throw "Unknown operator: '"+name+"'";
  689. }
  690. }
  691. var ops = ["+","-","*","/","%","<",">","==","!="];
  692. for (i in ops)
  693. this.registerCommand(ops[i],function (interp, args) {
  694. this.requireExactArgc(args, 3);
  695. var name = args[0].toString();
  696. var a = interp.objectify(args[1]);
  697. var b = interp.objectify(args[2]);
  698. if (name == '==')
  699. return new TclObject(a.toString() == b.toString()?"1":"0","BOOL");
  700. if (name == '!=')
  701. return new TclObject(a.toString() != b.toString()?"1":"0","BOOL");
  702.  
  703. var x = a.getNumber();
  704. var y = b.getNumber();
  705. if (a.isInteger() && b.isInteger())
  706. return new TclObject(interp.math(name, x, y),"INTEGER");
  707. if (a.isReal() && b.isReal())
  708. return new TclObject(interp.math(name, x, y),"REAL");
  709. return new TclObject(interp.math(name, args[1].toString(),
  710. args[2].toString()));
  711. });
  712. this.mkList = function(x) {
  713. var list = new Array();
  714. for (var name in x) {list.push(name);}
  715. return list;
  716. }
  717. this.objectify = function (text) {
  718. if (text == null) text = "";
  719. else if (text instanceof TclObject) return text;
  720. return new TclObject(text);
  721. }
  722. this.parseString = function (text) {
  723. text = text.toString();
  724. switch (text.charAt(0)+text.substr(text.length-1)) {
  725. case "{}":
  726. case "\"\"":
  727. text = text.substr(1,text.length-2);
  728. break;
  729. }
  730. return this.objectify(text);
  731. }
  732. this.parseList = function (text) {
  733. text = text.toString();
  734. switch (text.charAt(0)+text.substr(text.length-1)) {
  735. case "{}":
  736. case "\"\"":
  737. text = new Array(text);
  738. break;
  739. }
  740. return this.objectify(text);
  741. }
  742. this.call = function(args) {
  743. if(_step) console.log("this.call "+args);
  744. var func = this.getCommand(args[0].toString());
  745. var r = func.call(this,args);
  746. switch (this.code) {
  747. case this.OK: case this.RET: return r;
  748. case this.BRK:
  749. if (!this.inLoop) throw "Invoked break outside of a loop";
  750. break;
  751. case this.CNT:
  752. if (!this.inLoop) throw "Invoked continue outside of a loop";
  753. break;
  754. default: throw "Unknown return code " + this.code;
  755. }
  756. return r;
  757. }
  758. }
  759. var Tcl = new Object();
  760. Tcl.isReal = new RegExp("^[+\\-]?[0-9]+\\.[0-9]*([eE][+\\-]?[0-9]+)?$");
  761. Tcl.isDecimal = new RegExp("^[+\\-]?[1-9][0-9]*$");
  762. Tcl.isHex = new RegExp("^0x[0-9a-fA-F]+$");
  763. Tcl.isOctal = new RegExp("^[+\\-]?0[0-7]*$");
  764. Tcl.isHexSeq = new RegExp("[0-9a-fA-F]*");
  765. Tcl.isOctalSeq = new RegExp("[0-7]*");
  766. Tcl.isList = new RegExp("[\\{\\} ]");
  767. Tcl.isNested = new RegExp("^\\{.*\\}$");
  768. Tcl.getVar = new RegExp("^[a-zA-Z0-9_]+", "g");
  769.  
  770. Tcl.Proc = function (interp, args) {
  771. var priv = this.privdata;
  772. interp.incrLevel();
  773. var arglist = priv[0].toList();
  774. var body = priv[1];
  775. args.shift();
  776. for (var i = 0; i < arglist.length; i++) {
  777. var name = arglist[i].toString();
  778. if (i >= args.length) {
  779. if (name == "args") {
  780. interp.setVar("args", Tcl.empty);
  781. break;
  782. }
  783. }
  784. if (Tcl.isList.test(name)) {
  785. name = interp.parseString(name).toList();
  786. if (name[0] == "args") throw "'args' defaults to the empty string";
  787. if (i >= args.length)
  788. interp.setVar(name.shift(), interp.parseString(name.join(" ")));
  789. else interp.setVar(name[0], interp.objectify(args[i]));
  790. } else if (name == "args") {
  791. interp.setVar("args", new TclObject(args.slice(i, args.length)));
  792. break;
  793. }
  794. interp.setVar(name, interp.objectify(args[i]));
  795. }
  796. if (name == "args" && i+1 < arglist.length)
  797. throw "'args' should be the last argument";
  798. try {
  799. var r = interp.eval(body);
  800. interp.code = interp.OK;
  801. interp.decrLevel();
  802. return r;
  803. } catch (e) {
  804. interp.decrLevel();
  805. throw "Tcl.Proc exception "+e;
  806. }
  807. }
  808. /** Manage subcommands */
  809. Tcl.EnsembleCommand = function (interp, args) {
  810. var sub = args[1].toString();
  811. var main = args.shift().toString()+" "+sub;
  812. args[0] = main;
  813. var ens = this.ensemble;
  814. if (ens == null) {
  815. throw "Not an ensemble command: "+main;
  816. } else if( ens[sub] == null) {
  817. throw 'unknown or ambiguous subcommand "'+sub+'": must be '+
  818. ens["subcommands"].valueOf();
  819. }
  820. return ens[sub].call(interp, args);
  821. }
  822. /** Get subcommands of the current ensemble command. */
  823. Tcl.InfoSubcommands = function(interp, args) {
  824. var r = new Array();
  825. for (var i in this.ensemble) r.push(i);
  826. return interp.objectify(r);
  827. }
  828. function TclObject(text) {
  829. this.TEXT = 0;
  830. this.LIST = 1;
  831. this.INTEGER = 2;
  832. this.REAL = 3;
  833. this.BOOL = 4;
  834. switch (arguments[0]) {
  835. case "LIST":
  836. case "INTEGER":
  837. case "REAL":
  838. case "BOOL":
  839. this.type = this[arguments[0]];
  840. break;
  841. default:
  842. this.type = this.TEXT;
  843. if (text instanceof Array) this.type = this.LIST;
  844. else text = text.toString();
  845. break;
  846. }
  847. this.content = text;
  848. this.stringIndex = function (i) {
  849. this.toString();
  850. return this.index(i, this.content.length);
  851. }
  852. this.listIndex = function (i) {
  853. this.toList();
  854. return this.index(i, this.content.length);
  855. }
  856. this.index = function (i, len) {
  857. var index = i.toString();
  858. if (index.substring(0,4) == "end-")
  859. index = len - parseInt(index.substring(4)) - 1;
  860. else if (index == "end") index = len-1;
  861. else index = parseInt(index);
  862. if (isNaN(index)) throw "Bad index "+i;
  863. if (index < 0 || index >= len) throw "Index out of bounds";
  864. return index;
  865. }
  866. this.isInteger = function () {return (this.type == this.INTEGER);}
  867. this.isReal = function () {return (this.type == this.REAL);}
  868. this.getString = function (list, nested) {
  869. var res = new Array();
  870. for (var i in list) {
  871. res[i] = list[i].toString();
  872. if (Tcl.isList.test(res[i]) && !Tcl.isNested.test(res[i]))
  873. res[i] = "{" + res[i] + "}";
  874. }
  875. if (res.length == 1) return res[0];
  876. return res.join(" ");
  877. }
  878. this.toString = function () {
  879. if (this.type != this.TEXT) {
  880. if (this.type == this.LIST)
  881. this.content = this.getString(this.content);
  882. else this.content = this.content.toString();
  883. this.type = this.TEXT;
  884. }
  885. return this.content;
  886. }
  887. this.getList = function (text) {
  888. if (text.charAt(0) == "{" && text.charAt(text.length-1) == "}")
  889. text = text.substring(1, text.length-1);
  890. if (text == "") return [];
  891. var parser = new TclParser(text.toString());
  892. var content = new Array();
  893. for (var i = 0; ; i++) {
  894. parser.parseList();
  895. content[i] = new TclObject(parser.getText());
  896. if (parser.type == parser.EOL || parser.type == parser.ESC)
  897. break;
  898. }
  899. return content;
  900. }
  901. this.toList = function () {
  902. if (this.type != this.LIST) {
  903. if (this.type != this.TEXT) this.content[0] = this.content;
  904. else this.content = this.getList(this.content);
  905. this.type = this.LIST;
  906. }
  907. return this.content;
  908. }
  909. this.toInteger = function () {
  910. if (this.type == this.INTEGER) return this.content;
  911. this.toString();
  912. if (this.content.match(Tcl.isHex))
  913. this.content = parseInt(this.content.substring(2), 16);
  914. else if (this.content.match(Tcl.isOctal))
  915. this.content = parseInt(this.content, 8);
  916. else if (this.content.match(Tcl.isDecimal))
  917. this.content = parseInt(this.content);
  918. else throw "Not an integer: '"+this.content+"'";
  919. if (isNaN(this.content)) throw "Not an integer: '"+this.content+"'";
  920. this.type = this.INTEGER;
  921. return this.content;
  922. }
  923. this.getFloat = function (text) {
  924. if (!text.toString().match(Tcl.isReal))
  925. throw "Not a real: '"+text+"'";
  926. return parseFloat(text);
  927. }
  928. this.toReal = function () {
  929. if (this.type == this.REAL)
  930. return this.content;
  931. this.toString();
  932. // parseFloat doesn't control all the string, so need to check it
  933. this.content = this.getFloat(this.content);
  934. if (isNaN(this.content)) throw "Not a real: '"+this.content+"'";
  935. this.type = this.REAL;
  936. return this.content;
  937. }
  938. this.getNumber = function () {
  939. try {
  940. return this.toInteger();
  941. } catch (e) {return this.toReal();}
  942. }
  943. this.toBoolean = function () {
  944. if (this.type == this.BOOL) return this.content;
  945. try {
  946. this.content = (this.toInteger() != 0);
  947. } catch (e) {
  948. var t = this.content;
  949. if (t instanceof Boolean) return t;
  950. switch (t.toString().toLowerCase()) {
  951. case "yes":case "true":case "on":
  952. this.content = true;
  953. break;
  954. case "false":case "off":case "no":
  955. this.content = false;
  956. break;
  957. default:
  958. throw "Boolean expected, got: '"+this.content+"'";
  959. }
  960. }
  961. this.type = this.BOOL;
  962. return this.content;
  963. }
  964. }
  965. function TclCommand(func, privdata) {
  966. if (func == null) throw "No such function";
  967. this.func = func;
  968. this.privdata = privdata;
  969. this.ensemble = arguments[2];
  970.  
  971. this.call = function(interp, args) {
  972. var r = (this.func)(interp, args);
  973. r = interp.objectify(r);
  974. return r;
  975. }
  976. this.requireExactArgc = function (args, argc) {
  977. if (args.length != argc) {
  978. throw argc + " words expected, got "+args.length;
  979. }
  980. }
  981. this.requireMinArgc = function (args, argc) {
  982. if (args.length < argc) {
  983. throw argc + " words expected at least, got "+args.length;
  984. }
  985. }
  986. this.requireArgcRange = function (args, min, max) {
  987. if (args.length < min || args.length > max) {
  988. throw min + " to "+max + " words expected, got "+args.length;
  989. }
  990. }
  991. }
  992. function TclParser(text) {
  993. this.OK = 0;
  994. this.SEP = 0;
  995. this.STR = 1;
  996. this.EOL = 2;
  997. this.EOF = 3;
  998. this.ESC = 4;
  999. this.CMD = 5;
  1000. this.VAR = 6;
  1001. this.text = text;
  1002. this.start = 0;
  1003. this.end = 0;
  1004. this.insidequote = false;
  1005. this.index = 0;
  1006. this.len = text.length;
  1007. this.type = this.EOL;
  1008. this.cur = this.text.charAt(0);
  1009. this.getText = function () {
  1010. return this.text.substring(this.start,this.end+1);
  1011. }
  1012. this.parseString = function () {
  1013. var newword = (this.type==this.SEP ||
  1014. this.type == this.EOL || this.type == this.STR);
  1015. if (newword && this.cur == "{") return this.parseBrace();
  1016. else if (newword && this.cur == '"') {
  1017. this.insidequote = true;
  1018. this.feedchar();
  1019. }
  1020. this.start = this.index;
  1021. while (true) {
  1022. if (this.len == 0) {
  1023. this.end = this.index-1;
  1024. this.type = this.ESC;
  1025. return this.OK;
  1026. }
  1027. if (this.cur == "\\") {
  1028. if (this.len >= 2) this.feedSequence();
  1029. }
  1030. else if ("$[ \t\n\r;".indexOf(this.cur)>=0) {
  1031. if ("$[".indexOf(this.cur)>=0 || !this.insidequote) {
  1032. this.end = this.index-1;
  1033. this.type = this.ESC;
  1034. return this.OK;
  1035. }
  1036. }
  1037. else if (this.cur == '"' && this.insidequote) {
  1038. this.end = this.index-1;
  1039. this.type = this.ESC;
  1040. this.feedchar();
  1041. this.insidequote = false;
  1042. return this.OK;
  1043. }
  1044. this.feedchar();
  1045. }
  1046. return this.OK;
  1047. }
  1048. this.parseList = function () {
  1049. level = 0;
  1050. this.start = this.index;
  1051. while (true) {
  1052. if (this.len == 0) {
  1053. this.end = this.index;
  1054. this.type = this.EOL;
  1055. return;
  1056. }
  1057. switch (this.cur) {
  1058. case "\\":
  1059. if (this.len >= 2) this.feedSequence();
  1060. break;
  1061. case " ": case "\t": case "\n": case "\r":
  1062. if (level > 0) break;
  1063. this.end = this.index - 1;
  1064. this.type = this.SEP;
  1065. this.feedchar();
  1066. return;
  1067. case '{': level++; break;
  1068. case '}': level--; break;
  1069. }
  1070. this.feedchar();
  1071. }
  1072. if (level != 0) throw "Not a list";
  1073. this.end = this.index;
  1074. return;
  1075. }
  1076. this.parseSep = function () {
  1077. this.start = this.index;
  1078. while (" \t\r\n".indexOf(this.cur)>=0) this.feedchar();
  1079. this.end = this.index - 1;
  1080. this.type = this.SEP;
  1081. return this.OK;
  1082. }
  1083. this.parseEol = function () {
  1084. this.start = this.index;
  1085. while(" \t\n\r;".indexOf(this.cur)>=0) this.feedchar();
  1086. this.end = this.index - 1;
  1087. this.type = this.EOL;
  1088. return this.OK;
  1089. }
  1090. this.parseCommand = function () {
  1091. var level = 1;
  1092. var blevel = 0;
  1093. this.feedcharstart();
  1094. while (true) {
  1095. if (this.len == 0) break;
  1096. if (this.cur == "[" && blevel == 0)
  1097. level++;
  1098. else if (this.cur == "]" && blevel == 0) {
  1099. level--;
  1100. if (level == 0) break;
  1101. } else if (this.cur == "\\") {
  1102. this.feedSequence();
  1103. } else if (this.cur == "{") {
  1104. blevel++;
  1105. } else if (this.cur == "}") {
  1106. if (blevel != 0) blevel--;
  1107. }
  1108. this.feedchar();
  1109. }
  1110. this.end = this.index-1;
  1111. this.type = this.CMD;
  1112. if (this.cur == "]") this.feedchar();
  1113. return this.OK;
  1114. }
  1115. this.parseVar = function () {
  1116. this.feedcharstart();
  1117. this.end = this.index
  1118. + this.text.substring(this.index).match(Tcl.getVar).toString().length-1;
  1119. if (this.end == this.index-1) {
  1120. this.end = --this.index;
  1121. this.type = this.STR;
  1122. } else this.type = this.VAR;
  1123. this.setPos(this.end+1);
  1124. return this.OK;
  1125. }
  1126. this.parseBrace = function () {
  1127. var level = 1;
  1128. this.feedcharstart();
  1129. while (true) {
  1130. if (this.len > 1 && this.cur == "\\") {
  1131. this.feedSequence();
  1132. } else if (this.len == 0 || this.cur == "}") {
  1133. level--;
  1134. if (level == 0 || this.len == 0) {
  1135. this.end = this.index-1;
  1136. if (this.len > 0) this.feedchar();
  1137. this.type = this.STR;
  1138. return this.OK;
  1139. }
  1140. } else if (this.cur == "{") level++;
  1141. this.feedchar();
  1142. }
  1143. return this.OK; // unreached
  1144. }
  1145. this.parseComment = function () {
  1146. while (this.cur != "\n" && this.cur != "\r") this.feedchar();
  1147. }
  1148. this.getToken = function () {
  1149. while (true) {
  1150. if (this.len == 0) {
  1151. if (this.type == this.EOL) this.type = this.EOF;
  1152. if (this.type != this.EOF) this.type = this.EOL;
  1153. return this.OK;
  1154. }
  1155. switch (this.cur) {
  1156. case ' ':
  1157. case '\t':
  1158. if (this.insidequote) return this.parseString();
  1159. return this.parseSep();
  1160. case '\n':
  1161. case '\r':
  1162. case ';':
  1163. if (this.insidequote) return this.parseString();
  1164. return this.parseEol();
  1165. case '[': return this.parseCommand();
  1166. case '$': return this.parseVar();
  1167. }
  1168. if (this.cur == "#" && this.type == this.EOL) {
  1169. this.parseComment();
  1170. continue;
  1171. }
  1172. return this.parseString();
  1173. }
  1174. return this.OK; // unreached
  1175. }
  1176. this.feedSequence = function () {
  1177. if (this.cur != "\\") throw "Invalid escape sequence";
  1178. var cur = this.steal(1);
  1179. var specials = new Object();
  1180. specials.a = "\a";
  1181. specials.b = "\b";
  1182. specials.f = "\f";
  1183. specials.n = "\n";
  1184. specials.r = "\r";
  1185. specials.t = "\t";
  1186. specials.v = "\v";
  1187. switch (cur) {
  1188. case 'u':
  1189. var hex = this.steal(4);
  1190. if (hex != Tcl.isHexSeq.exec(hex))
  1191. throw "Invalid unicode escape sequence: "+hex;
  1192. cur = String.fromCharCode(parseInt(hex,16));
  1193. break;
  1194. case 'x':
  1195. var hex = this.steal(2);
  1196. if (hex != Tcl.isHexSeq.exec(hex))
  1197. throw "Invalid unicode escape sequence: "+hex;
  1198. cur = String.fromCharCode(parseInt(hex,16));
  1199. break;
  1200. case "a": case "b": case "f": case "n":
  1201. case "r": case "t": case "v":
  1202. cur = specials[cur];
  1203. break;
  1204. default:
  1205. if ("0123456789".indexOf(cur) >= 0) {
  1206. cur = cur + this.steal(2);
  1207. if (cur != Tcl.isOctalSeq.exec(cur))
  1208. throw "Invalid octal escape sequence: "+cur;
  1209. cur = String.fromCharCode(parseInt(cur, 8));
  1210. }
  1211. break;
  1212. }
  1213. this.text[index] = cur;
  1214. this.feedchar();
  1215. }
  1216. this.steal = function (n) {
  1217. var tail = this.text.substring(this.index+1);
  1218. var word = tail.substr(0, n);
  1219. this.text = this.text.substring(0, this.index-1) + tail.substring(n);
  1220. return word;
  1221. }
  1222. this.feedcharstart = function () {
  1223. this.feedchar();
  1224. this.start = this.index;
  1225. }
  1226. this.setPos = function (index) {
  1227. var d = index-this.index;
  1228. this.index = index;
  1229. this.len -= d;
  1230. this.cur = this.text.charAt(this.index);
  1231. }
  1232. this.feedchar = function () {
  1233. this.index++;
  1234. this.len--;
  1235. if (this.len < 0) throw "End of file reached";
  1236. this.cur = this.text.charAt(this.index);
  1237. }
  1238. }
  1239. //------------------------------------- main Read-Eval-Print loop
  1240. var itp = new TclInterp();
  1241. var res;
  1242. process.argv.slice(2).forEach(function(cmd,index,array) {
  1243. itp.eval(cmd);
  1244. });
  1245. var readline = require('readline');
  1246. var rl = readline.createInterface(process.stdin, process.stdout);
  1247. rl.setPrompt('% ');
  1248. rl.prompt();
  1249. rl.on('line', function(line) {
  1250. try {
  1251. res = itp.eval(line.trim());
  1252. } catch(e) {res = e;}
  1253. if(res != null && res.toString() != "" && res.toString().length)
  1254. console.log(res.toString());
  1255. rl.prompt();
  1256. }).on('close',function() {
  1257. process.exit(0);
  1258. });
  1259.